title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Text-based Causal Inference. Tutorial on analyzing voter fraud... | by Haaya Naushan | Towards Data Science | Science fiction tells us that rampant disinformation is a foresign of a society’s descent into a dystopia. It could be argued that disinformation destabilizes a democracy (Morgan 2018, Farkas & Schou 2019). Tangibly, people disregarding medical evidence has a negative impact on public health. For instance, people who are willing to ignore evidence might choose to refuse vaccines and thereby endanger others’ lives and their own. One should be cautious because scientific disinformation is pervasive, but it is hard to hold people accountable when access to trustworthy news material is garbled by the influx of fake news. A more insidious form of disinformation is the subversion of reality for a subset of the population; a type of mass hysteria that captures those cognitively vulnerable in an alternative reality. I am speaking of the surreal claims of voter fraud over the last American election, when Trump’s sycophants refused to accept that he lost the election. The fake news around voter fraud had an undeniably incendiary impact on the following January 6th insurrection, a tragic event that screamed dystopian society.
Hannah Arendt, the political philosopher, claimed it was necessary for people to engage with politics as a part of living a good life. In “The Human Condition”, Arendt says that it is not enough to work and spend time with those you love, you must also engage in political life (Arendt, 1958). There are many Americans who follow this ethos and engage with politics; viewing it as their right and responsibility as a citizen. Unfortunately, some of them are susceptible to fallacious thinking and fall prey to bizarre conspiracies like QAnon. In “Networked Propaganda” by Benkler, Faris and Roberts, the authors claim that the propaganda feedback loop is partly fueled by people’s desire to avoid cognitive discomfort. That is to say, people will seek out information that reinforces their worldview while ignoring or discounting evidence to the contrary. In an epidemiological sense, fake news acts as a vector of disease, spreading dangerous disinformation and saturating the public sphere with conflicting accounts that make it nigh impossible to discern the truth.
But what does politics have to do with data science? As a researcher interested in disinformation, I naturally seek to use data science tools to answer questions of social and political interest. Of immediate interest, is understanding the relationship between social media and fake news. There are claims that the toxic nature of social media, which is driven by shock-value and upvoting, has an impact on the dissemination of fake news. More specifically, looking at Twitter, I question whether fake news has a causal impact on the outcome of retweet count. Does sharing fake news lead to a higher retweet count? This tutorial is a result of my attempt to answer that question, and is a follow up to a previous article about causal inference using NLP.
In this article, to estimate causal effects using text, I make use of the Twitter VoterFraud2020 dataset curated by the Jacobs Technion — Cornell Institute. This dataset was made publicly available by the researchers and shared on this dashboard, the original paper is attributed to Abilov et al. (2021). I start by discussing the data and describing the preliminary analysis. Next, I introduce the causal-text algorithim and walkthrough the corresponding study on causal effects of linguistic properties (Pryzant, 2021). Additionally, I cover guidelines for using observational data for causal inference, and detail the estimation procedure of the causal-text algorithm. Following that, I lay out the framework for the causal experiment, which leads directly into a tutorial of how to set up and use the causal-text tool (which I fork and adapt from the original repo). I also cover the steps required to address the proposed causal question with the causal-text algorithm. Lastly, I briefly discuss the results and consider possible extensions.
The open source Cornell VoterFraud2020 Twitter dataset contains 7.6M tweets and 25.6M retweets from 2.6M users, all related to the claims of voter fraud between October 23, 2020 to December 16, 2020. Due to Twitter’s privacy policies only the tweet ids and user ids are shared; however, the GitHub repository for the dataset includes scripts to hydrate the data. For this experiment, I focused only on the 7.6M original tweets. Once the tweets were collected, it was necessary to do some preprocessing to clean the tweet text and extract urls. The urls were all in Twitter’s shortened format of “t.co”, and thus had to be resolved. To better understand the popularity of the resolved urls, each url was given an Alexa rank from Amazon’s analysis of web traffic statistics.
Media Cloud is an open-source media content analysis tool developed at the Berkman Klein Center for Internet & Society at Harvard University. This platform has curated source lists for American media sources, divided by political affiliation, covering the left, center-left, center, center-right and right. Using these US news source lists, I cross referenced with the urls resolved from the voter fraud tweets dataset. This selected for urls that linked specifically to news articles. Media Cloud has great investigative capabilities for news media, so I was able to use Media Cloud queries to determine the media in-link share count and Facebook share count of the isolated articles. In addition to this article metadata, I scraped the full text of all the news articles that were still online at the time.
These steps gave me a combined dataset of original tweets that shared news articles, with the full text of the news articles, article metadata, tweet metadata and Alexa rankings for the urls. To be clear, the dataset of 7.6M tweets was pared down such that every tweet had a corresponding news article. The purpose of collecting the full text of the articles was to perform topic modeling with latent Dirichlet allocation (LDA) to see if it was possible to isolate the fake news articles. Additionally, the VoterFraud2020 dataset of 2.6M users also contained each user’s community or cluster as determined by a community detection algorithm (e.g. Louvain method). Given the multiple data streams and richness of the resulting tweet-article dataset it was necessary to run some preliminary analysis, which is covered next.
Firstly, considering the tweets themselves, the text of the tweets may have value in identifying fake news. Hence, I started by topic modeling the tweet text with LDA to gain a general sense of the content of the Twitter discourse.
The results of the LDA model highlighted several topics that were expressly about aspects of the voter fraud disinformation conversation. For instance, one notable topic that was isolated from the other topics, was about the alt-right hashtag “#stopthesteal”. Also notable was the similarly isolated Wall Street Journal and New York Times fact checking topic. Interestingly, tweets that claimed to have evidence of fraud greatly overlapped with tweets from right-wing news media sources, like Fox News. Overall, there are several threads of disinformation, ranging from ballot harvesting, conspiracies about the voting software, affidavits asserting fraud, and rumours of military involvement.
Analysis of the user communities with a community detection algorithm provided 5 distinct communities that varied in user count, as shown below.
The amplifier groups were those that pushed the voter fraud agenda, and the foreign groups represent potential foreign influence and are tiny in comparison.
Focusing on the spread of fake news, these five communities behaved differently when it came to sharing urls of news articles. The Media Cloud metadata contained the media inlink count which represents the number of times an article was linked to by other media sources. A highly in-linked article could be considered to be more mainstream. The graph below shows the trend of media in-link count over time for the three largest communities.
The above time series suggests that the center-left community tended to share articles that were more “mainstream” when compared to the two amplifier communities. Although the center-left community was more likely to share mainstream articles, they did not garner high retweet counts. This is shown below in a time series of mean retweet counts by community.
In fact, it is the third largest community “Amplifiers_1” that had the highest retweet counts for shared urls, despite representing only 11.5% of users. The concern here is that even if the center-left were trying to fact check those spreading the fake news of voter fraud, they were not getting much visibility on Twitter. It is also startling to realize that the relatively small group of “Amplifiers_1” was highly influential in spreading information, despite not sharing mainstream media.
It is commonly assumed that fake news is often on fringe websites, far out of the mainstream. Having calculated the Alexa rank or popularity of each news article url, it was possible to look at the relationship between a website’s “fringiness” and which communities were retweeting these fringe sites. In the heatmap below, the Alexa rank or “fringe-score” is weighted by retweet count and the community distribution by topic is mapped.
Here we can see that the “Amplifier_1” group not only garners the largest retweet count shares, but they also share the most fringe websites. Since we are interested in the causal question of whether the treatment of fake news has a causal effect on the outcome of retweet count, the relationship between fringe-scores and fake news articles is also of interest.
At this point, it became necessary to look at the actual text of the news articles to better help classify fake news. The process of topic modeling the news articles with LDA resulted in five of the seven topics being explicitly fake news articles. This allowed for labeling each url, and thereby each tweet, as either fake news or not. This NLP derived label is used as a proxy label in the setup of the causal experiment that is described later. Furthermore, in order to test the usefulness of the causal-text algorithm, I also labeled 100 of the most popular urls for fake news. This labeling covered 18% of the tweet-article dataset, and gave me roughly 28K tweet-article pairs that had both proxy labels via topic modeling and true labels via manual annotation. Having both proxy treatment labels and true treatment labels, allows for benchmarking the causal-text algorithm for this task. In the next three sections, I will discuss the details of the causal-text algorithm and introduce some of the causal concepts needed to understand the tool.
The causal-text algorithm used in this tutorial was created by Pryzant et al. (2021), it was introduced as “TEXTCAUSE” in a paper titled “Causal Effects of Linguistic Properties”. This causal algorithm makes use of another tool — CausalBERT, that was originally designed by Veitch et al. (2020). CausalBERT was developed to produce text embeddings for causal inference; in essence, the authors designed a way to use AI language models to adjust for text when testing for causality.
The causal-text algorithm has two components, first it makes use of distant supervision to improve the quality of proxy labels, and second, CausalBERT is used to adjust for the text. Pryzant et al. tried to formalize the causal effect of a writer’s intent, along with establishing the assumptions necessary to identify the causal effect from observational data. Another contribution of this work is that they proposed an estimator for this setting where the bias is bounded when adjusting for text.
The VoterFraud2020 dataset represents observational data, where the tweets were obtained without an intervention. Since, the measurement of causal effect requires the fulfillment of the ceteris paribus assumption, where all covariates are kept fixed, we must reason about interventions. Pryzant et al. describe two challenges to estimating causal effects from observational data. Firstly, there is a need to “formalize the causal effect of interest by specifying the hypothetical intervention to which it corresponds.” (Pryzant et al., 2021). This challenge is overcome by imagining an intervention on the writer of a text, where they are told to use a different linguistic property.
The second challenge to causal inference is identification, where the actual linguistic property we are interested in can only be measured by a noisy proxy (e.g. topic labels). Therefore, the study also established the assumptions needed to recover the true causal effects of linguistic properties from the noisy proxy labels. The creators of the causal-text algorithm adjust for confounding in text with CausalBERT and prove that this process bounds the bias of the causal estimates. In my previous article about causality and NLP, I discussed in detail the issue of confounding due to text.
When discussing causal inference with observational data, it is necessary to talk about the average treatment effect (ATE). As seen in the image below, the ATE is the difference in potential outcomes between the real world (T=1) and the counterfactual world (T=0). I have previously described the potential outcomes framework in intuitive ways in two articles: Causal inference using NLP, and CausalML for Econometrics: Causal Forests.
However, as mentioned, we are also concerned with confounding. To deal with confounders (Wi), the backdoor adjustment formula (Pearl, 2009) can be used to rewrite the ATE in terms of all the observed variables: Ti for treatment and Yi for outcome. This confounding relationship is seen in the image below, where the confounder Wi has an effect on both the treatment and outcome.
The confounding effect of Wi results in a spurious correlation, which can also be referred to as “open backdoor paths that induce non-causal associations” (Pryzant et al., 2021). I have previously discussed spurious correlations and backdoor paths in an article about improving NLP models with causality. The backdoor adjustment formula for the ATE is shown in the image below.
If we assume the confounder Wi is discrete, then the data can be grouped into values of W, the average difference in potential outcomes can be calculated, and lastly, we take the average over the groups of W.
Pryzant et al. (2021) propose the following causal model of text and outcomes:
The text is represented by W, which has the linguistic property T (as treatment), and other qualities Z (as covariates). Here, Z could be the topic, sentiment, length or other qualities of a text. This causal model is built with the literary argument that language is subject to two perspectives: the text as intended by the author and the text as interpreted by the reader. The second perspective of the reader is shown by T_tilde and Z_tilde — where T_tilde represents the treatment as received by the reader, and Z_tilde represents the other qualities of the text W as perceived by the reader. The outcome Y is affected by the tilde variables instead of Z and T directly. The T_hat variable represents the proxy label as derived from the text W, which could be topic labels.
The hypothetical intervention on the treatment, is to ask the writer to use (or not use) a linguistic property T, where T is a binary choice. It is not possible to use observational data to capture the unobserved linguistic characteristics of Z, because it is correlated with T. It is, however, possible to estimate the linguistic properties as perceived by a reader, which is represented by the tilde variables. The ATE of the reader’s perspective is defined as:
In order to calculate the causal effect of interest, the ATE of the writer’s perspective, Pryzant et al. (2021) developed a theorem (Theorem 1) which exploited the ATE of the reader’s perspective as calculated from T_tilde. They define Z_tilde as a function of the text W, as seen in the image below, where the potential outcomes of Y are equivalent given either W or both T_tilde and Z_tilde.
Having defined Z_tilde as such, it is then possible to define the ATErea as the following equation:
The ATErea is said to be equal to the ATEwri, and the text W, splits into the information that the reader uses to perceive the tilde variables. Z_tilde represents confounding properties, since it affects the outcome and is correlated with T_tilde. To be clear, this theorem only holds under certain assumptions, of which there are three. Firstly, unobserved confounding (W) blocks the backdoor paths between T_tilde and the outcome Y. Secondly, we need to assume that T = T_tilde, that is to say, there is an agreement of intent (ATEwri) and perception (ATErea). The last assumption is the positivity (or overlap) assumption, which is that the probability of the treatment is between 0 and 1. I provided an intuitive explanation of the positivity assumption in another article about causality.
A further complication is that we cannot observe the perception of the reader, in addition to not being able to directly observe the intent of the writer; hence, the need for proxies. For T_tilde it is possible to use a proxy T_hat to calculate the causal effect of interest, where the T_tilde is substituted out by T_hat in the previous equation to calculate an estimand (ATEproxγ).
At this point it is necessary to adjust the estimand for confounding, in other words, adjust the ATEproxγ for Z_tilde. This is made possible using CausalBERT, a pre-trained language model, to measure T_hat. The other advantage of this approach is that the bias due to the proxy label is bounded, such that it is benign — “it can only decrease the magnitude to the effect but it will not change the sign.”. Pryzant et al. (2021), refer to this as Theorem 2, and state that a “more accurate proxy will yield a lower estimation bias.”.
Now that we have discussed how to use observational data for causal inference with text, the practical part is the estimation procedure. The causal-text algorithm has two important features: improving proxy labels and adjusting for text. The approach to improving the accuracy of the proxy labels is based on the fact that the bias is bounded. The proxy labels are improved using distant supervision, which was inspired by work on lexicon induction and label propagation. The goal is to improve the recall of proxy labels by training a classifier to predict the proxy label, then using that classifier to relabel examples that were labeled T=0 but look like T=1. Essentially, the proxy labels are relabeled if necessary.
The second feature of the causal-text algorithm is that it adjusts for the text using a pre-trained language model. The ATEproxγ is measured by using the text (W), the improved proxy labels (T_hat*) and the outcomes (Y). This relies on Theorem 1, which as described earlier shows how to adjust for the confounding parts of text. Pryzant et al. (2021) use a DistilBERT model to produce a representation of the text with embeddings and then select the vector corresponding to a prepended classification token, [CLS]. Pryzant et al. use Huggingface transformers implementation of DistilBERT which has 66M parameters, and the vectors for text adjustment Mt , add 3,080 parameters. This model is then optimized such that the representation b(W), directly approximates the confounding information, Z_tilde. An estimator, Q, is trained for the expected conditional outcome, as seen in the image below.
In this equation, the estimator Q is shown to be equivalent to the expected conditional outcome for Y, when given the proxy T_hat, which itself is based on not only the treatment, t, but also the model representation of Z_tilde (b(W)), and the covariates C. The proxy estimator, Q_hat, is equivalent to the parameterized sum of a bias term (b) and two vectors (Mbt , Mct ), that rely on representation b(W) and a c vector. The c vector is a one-hot encoding vector of covariates C, and the two Mt are learned for value t of the treatment. The training objective of this model is to optimize:
In this equation, Θ is all the parameters of the model, and L(.) is the cross-entropy loss which is used with the estimator Q_hat, itself based on the Mt vectors. The original BERT masked language modeling objective (MLM) is represented as R(.), and the α hyperparameter is a penalty for the MLM objective. With the Q_hat estimator, the parameters Mbt and Mct are updated on examples where the improved proxy label is equivalent to t.
This setup is shown in the diagram below, where W represents the text, C represents the covariates and the CausalBERT model is a representation of the text such that it is possible to predict the potential outcomes of Y.
In summary, estimation with the full causal-text algorithm requires the improved proxy labels, and a causal model of the text and outcomes which extracts and adjusts for the confounding of Z_tilde. The algorithm also allows for the inclusion of covariates C when estimating the causal effect. As seen in the image above, the vector c and the model representation b(W) are used to predict the potential outcomes of Y while using information from T_hat*, the proxy label. The representation b(W) directly approximates the confounding information (Z_tilde), which allows it to adjust for the text.
Once the estimator Q_hat is fitted, it is possible to calculate the hatted ATEproxγ as seen in the equation below:
The ATE that is derived with this method can be used to determine the causal effect of the reader’s perspective, which itself is assumed to be equivalent to the causal effect of the writer’s perspective. The accuracy of this ATE is dependent on how accurate the proxies are and how well CausalBERT adjusts for the text. The next section describes the experimental framework used to test for the causal effect of fake news on retweet count.
The causal question is whether fake news has a causal effect on retweet count. A few years ago, a very popular study in Science claimed that on social media, fake news spreads more rapidly than real news. This study, however, does not rely on causal analysis. There is a possibility that the results were based on spurious correlations between confounders and the retweet count. For instance, the community a user belonged to was not investigated, nor was the popularity of the news site. Some communities might be more vulnerable to spreading fake news, and people might be more likely to share popular news sites. Moreover, language is complex and the text of tweets can act as a confounder, so we need to control for topic, writing style, tone and length of the tweet. Therefore, there is value in designing a causal study where possible confounders are controlled for, and the tweet text itself is adjusted for confounding qualities.
As previously mentioned, there are two challenges to estimating causal effects from observational data: interventions and identification. Firstly, we need to reason about the hypothetical intervention that we would make on the writer’s intent, such that they would use (or not use) a particular linguistic property. It is necessary to think of the sharing of fake news as a linguistic property that represents the writer’s intent, then it can be a treatment, T, that can be intervened upon. More simply, we view the sharing of a url that links to fake news as a linguistic property, where the intervention would be to tell the user to share a real news article (T=0) instead of a fake news article (T=1). While intervening on this treatment, the remaining qualities of the tweet must be kept constant. We will refer to these other text qualities as Z, such that Z represents potential confounding factors like topic, style, tone or length. The tweet text will be referred to as W (or simply “text”), and additional covariates such as user community or Alexa rank will be denoted as C. This setup is shown in the image below.
The proxy treatment is a fake news label as determined by topic modeling of the articles with LDA. Since the dataset has gold labels for the fake news articles, there are two treatment variables (T_true and T_proxy) so that it is possible to benchmark the T_proxy against T_true. Lastly, the outcome Y is the retweet count. For a first test, the C variable is categorical, where a number is used to represent the user community. All other variables, except the text, are binary numerical indicators (0 or 1). For a second test, the Alexa rank is used as the covariate C, and we look specifically at a single community: “Amplifiers_1”. In this test, the Alexa rank for each url is turned into a categorical variable by binning the values by quantile. The next section details how I adapted the causal-text algorithm for this tutorial, and explains how to interpret the results.
Pryzant et al. (2021) shared the causal-text algorithm on GitHub, which utilized a Pytorch implementation of CausalBERT. For this tutorial, it was necessary to adapt the original causal-text package since it was specifically tailored to the causal experiments described in the introductory paper. Furthermore, it does not appear to be maintained (updated) by the authors, so I had to update the requirements. I also simplified the output and removed the extraneous simulation parts that were not needed for this tutorial. The rest of the changes were minor and were made in the process of debugging. Overall, I made very few changes to the original algorithm, my adaptation can be accessed on GitHub. If you find this algorithm useful, please star Pryzant et al.’s original repository for the causal-text algorithm.
The tool runs from the command line, and I suggest running it with a GPU to make use of the speed for deep learning. Here, I explain how to set up Colab (to make use of the free GPU instance) and run the causal-text algorithm. First though, the data needs to be in the correct format. The tool accepts a “.tsv” file with five columns, for five variables: T_proxy, T_true, C, Y, text. The covariates C have to be categorical, and represented by simple integers. The T_proxy, T_true and outcome, Y, variables must be binary numerical indicators (0 or 1). The “text” is simply the tweet text. The adapted causal-text algorithm produces seven different ATE result values.
Using the T_true label, the causal-text algorithm calculates an “oracle” ATE value; this can be thought of as the true ATE which will act as a baseline. Next, an “unadjusted” ATE value is calculated as an additional baseline, where the ATE is the expected difference in outcomes conditioned on T_hat without accounting for covariates. The next two values are “T-boost” ATE values, where T-boost refers to treatment boosting by improving proxy labels. The proxy labels are improved in two ways by two different classifiers. One classifier works only with positive and unlabeled data, while the other is a straightforward regression, specifically Sci-kit Learn’s stochastic gradient descent classifier. The next ATE value is one where the text has been adjusted for, this is the “W adjust” value. The last two ATE values combine the T-boosting with text adjustment, for one ATE value per classifier type. These last two values represent the full “TEXTCAUSE” algorithm as designed by Pryzant et al. (2021).
The first step is to install the needed packages in Colab. This is done with the following single line of code:
!pip install sklearn transformers tensorflow
Next, we check to see if the GPU is available.
import torchif torch.cuda.is_available(): device = torch.device("cuda") print('There are %d GPU(s) available.' % torch.cuda.device_count()) print('We will use the GPU:', torch.cuda.get_device_name(0)) !nvidia-smielse: print('No GPU available, using the CPU instead.') device = torch.device("cpu")
The “.tsv” file with the data should be saved in Google Drive for easy access. We simply mount the drive to get access to the files.
from google.colab import drivedrive.mount('/content/gdrive')
Then we navigate to the folder where the data is saved.
%cd gdrive/My Drive/my_folder
Next we clone the adapted repo for the causal-text algorithm from GitHub.
!git clone https://github.com/haayanau/causal-text.git
After the causal-text package has been cloned, it is necessary to navigate to the directory where the main script is located.
%cd causal-text/src
Running the algorithm is very simple, run the following command with the path leading to the “.tsv” file. The “run_cb” argument means that CausalBERT will be used to adjust for the text. The models are trained for 3 epochs each.
!python main.py --run_cb --data /content/gdrive/MyDrive/my_folder/my_data.tsv
This command results in seven types of ATE values as described earlier. Pryzant et al.(2021) do caution that “ATE estimates lose fidelity when the proxy is less than 80% accurate”. They also claim that it is crucial to adjust for the confounding parts of text, and that estimates that account for C without adjusting for the text, might be worse than the unadjusted estimate. The next section briefly discusses the results of the two experiments, and suggests some extensions.
Results and Extensions
For the first test, we are looking at the ATE of fake news (T) on retweet count (Y), with the user community (C) and tweet text as confounders. There are 15,468 observations and the results are shown below.
The true (oracle) ATE value suggests that there is practically no causal effect, which is contrary to the popular expectation that fake news spreads quicker than real news, and would garner higher retweet counts. The unadjusted ATE value also does not show causal effect, despite not accounting for covariate C. In terms of matching the true ATE value, the (W adjust) ATE that adjusts for text with CausalBERT comes the closest. Neither of the values from the full “TEXTCAUSE” algorithm (adjusts for text and improves labels) are as close to the true ATE as the W adjust value, which does not use the improved labels.
The second test looked only at the “Amplifiers_1” community and accounts for Alexa rank as a potentially confounding covariate. There are 1,485 observations and the results are shown below.
Here again, there does not appear to be a causal effect of fake news on retweet count, once we control for the Alexa rank. The true (oracle) ATE value is mildly negative, and the full version of the “TEXTCAUSE” algorithm that uses the “pu” classifier for T-boosting, produces the ATE that most closely matches the true value. This treatment boosted value (TextCause pu), not only includes improved proxy labels but also adjusts for the text with CausalBERT. The unadjusted ATE had the worst performance, however, all of the other ATE values had a similarly poor performance.
There is a strong possibility that there are unobserved confounders that have not been controlled for in this experiment. This might explain the lack of causal effect being detected, or conversely, there simply is no causal effect. At this point, we have not proven that there is a causal effect of fake news on retweet count, nor have we definitively proven that there is no causal effect. All we have done is bring into question the assumption popularly claimed by researchers, that fake news spreads faster than real news on social media. It might be possible that including further covariates would improve the experiment, however, it will be tricky to determine which covariates to include. There is also a possibility that the sample sizes were not big enough, especially for the second test where there were only 1,485 observations.
There are several extensions that we could implement. Starting with the first test, we could substitute the user community with Alexa rank for the covariate, C. For the second test, we could increase the sample size or even compare across communities. It would be helpful if the causal-text algorithm could accommodate more than one covariate (higher dimensionality). Even more useful, would be if the causal-text algorithm could deal with heterogeneous treatment effects and calculate the conditional average treatment effect (CATE). For instance, we could condition on user community, to see if there is a difference in CATEs across the groups.
The intersection of causal inference and NLP is fascinating, and the causal-text algorithm is a great example of creativity and initiative. My hope is that this research will continue to push the boundaries of what is possible with regards to methods for estimating a causal effect with text. In terms of application, the causal-text algorithm can be applied to various fields such as economics, healthcare, marketing, public policy and even epidemiology. There is a shift in thinking around the phenomenon of fake news, for instance, there are calls to treat the issue as a public health issue (Donovan, 2020). The WHO has taken an epidemiological approach, and are referring to incidents of fake news as “infodemics”. All of these changes suggest that it might be time to take a causal approach to disinformation. Exploring causality could be a way of developing an economics-inspired framework, for looking at the causal effect of disinformation on society (True Costs of Misinformation Workshop, TaSC, Shorenstein Center). Personally, I am interested in applying this method to economic research that utilizes open source social media data.
I welcome questions and feedback, please feel free to connect with me on Linkedin. | [
{
"code": null,
"e": 1305,
"s": 172,
"text": "Science fiction tells us that rampant disinformation is a foresign of a society’s descent into a dystopia. It could be argued that disinformation destabilizes a democracy (Morgan 2018, Farkas & Schou 2019). Tangibly, people disregarding medical evidence has a negative impact on public health. For instance, people who are willing to ignore evidence might choose to refuse vaccines and thereby endanger others’ lives and their own. One should be cautious because scientific disinformation is pervasive, but it is hard to hold people accountable when access to trustworthy news material is garbled by the influx of fake news. A more insidious form of disinformation is the subversion of reality for a subset of the population; a type of mass hysteria that captures those cognitively vulnerable in an alternative reality. I am speaking of the surreal claims of voter fraud over the last American election, when Trump’s sycophants refused to accept that he lost the election. The fake news around voter fraud had an undeniably incendiary impact on the following January 6th insurrection, a tragic event that screamed dystopian society."
},
{
"code": null,
"e": 2374,
"s": 1305,
"text": "Hannah Arendt, the political philosopher, claimed it was necessary for people to engage with politics as a part of living a good life. In “The Human Condition”, Arendt says that it is not enough to work and spend time with those you love, you must also engage in political life (Arendt, 1958). There are many Americans who follow this ethos and engage with politics; viewing it as their right and responsibility as a citizen. Unfortunately, some of them are susceptible to fallacious thinking and fall prey to bizarre conspiracies like QAnon. In “Networked Propaganda” by Benkler, Faris and Roberts, the authors claim that the propaganda feedback loop is partly fueled by people’s desire to avoid cognitive discomfort. That is to say, people will seek out information that reinforces their worldview while ignoring or discounting evidence to the contrary. In an epidemiological sense, fake news acts as a vector of disease, spreading dangerous disinformation and saturating the public sphere with conflicting accounts that make it nigh impossible to discern the truth."
},
{
"code": null,
"e": 3129,
"s": 2374,
"text": "But what does politics have to do with data science? As a researcher interested in disinformation, I naturally seek to use data science tools to answer questions of social and political interest. Of immediate interest, is understanding the relationship between social media and fake news. There are claims that the toxic nature of social media, which is driven by shock-value and upvoting, has an impact on the dissemination of fake news. More specifically, looking at Twitter, I question whether fake news has a causal impact on the outcome of retweet count. Does sharing fake news lead to a higher retweet count? This tutorial is a result of my attempt to answer that question, and is a follow up to a previous article about causal inference using NLP."
},
{
"code": null,
"e": 4176,
"s": 3129,
"text": "In this article, to estimate causal effects using text, I make use of the Twitter VoterFraud2020 dataset curated by the Jacobs Technion — Cornell Institute. This dataset was made publicly available by the researchers and shared on this dashboard, the original paper is attributed to Abilov et al. (2021). I start by discussing the data and describing the preliminary analysis. Next, I introduce the causal-text algorithim and walkthrough the corresponding study on causal effects of linguistic properties (Pryzant, 2021). Additionally, I cover guidelines for using observational data for causal inference, and detail the estimation procedure of the causal-text algorithm. Following that, I lay out the framework for the causal experiment, which leads directly into a tutorial of how to set up and use the causal-text tool (which I fork and adapt from the original repo). I also cover the steps required to address the proposed causal question with the causal-text algorithm. Lastly, I briefly discuss the results and consider possible extensions."
},
{
"code": null,
"e": 4949,
"s": 4176,
"text": "The open source Cornell VoterFraud2020 Twitter dataset contains 7.6M tweets and 25.6M retweets from 2.6M users, all related to the claims of voter fraud between October 23, 2020 to December 16, 2020. Due to Twitter’s privacy policies only the tweet ids and user ids are shared; however, the GitHub repository for the dataset includes scripts to hydrate the data. For this experiment, I focused only on the 7.6M original tweets. Once the tweets were collected, it was necessary to do some preprocessing to clean the tweet text and extract urls. The urls were all in Twitter’s shortened format of “t.co”, and thus had to be resolved. To better understand the popularity of the resolved urls, each url was given an Alexa rank from Amazon’s analysis of web traffic statistics."
},
{
"code": null,
"e": 5758,
"s": 4949,
"text": "Media Cloud is an open-source media content analysis tool developed at the Berkman Klein Center for Internet & Society at Harvard University. This platform has curated source lists for American media sources, divided by political affiliation, covering the left, center-left, center, center-right and right. Using these US news source lists, I cross referenced with the urls resolved from the voter fraud tweets dataset. This selected for urls that linked specifically to news articles. Media Cloud has great investigative capabilities for news media, so I was able to use Media Cloud queries to determine the media in-link share count and Facebook share count of the isolated articles. In addition to this article metadata, I scraped the full text of all the news articles that were still online at the time."
},
{
"code": null,
"e": 6580,
"s": 5758,
"text": "These steps gave me a combined dataset of original tweets that shared news articles, with the full text of the news articles, article metadata, tweet metadata and Alexa rankings for the urls. To be clear, the dataset of 7.6M tweets was pared down such that every tweet had a corresponding news article. The purpose of collecting the full text of the articles was to perform topic modeling with latent Dirichlet allocation (LDA) to see if it was possible to isolate the fake news articles. Additionally, the VoterFraud2020 dataset of 2.6M users also contained each user’s community or cluster as determined by a community detection algorithm (e.g. Louvain method). Given the multiple data streams and richness of the resulting tweet-article dataset it was necessary to run some preliminary analysis, which is covered next."
},
{
"code": null,
"e": 6812,
"s": 6580,
"text": "Firstly, considering the tweets themselves, the text of the tweets may have value in identifying fake news. Hence, I started by topic modeling the tweet text with LDA to gain a general sense of the content of the Twitter discourse."
},
{
"code": null,
"e": 7506,
"s": 6812,
"text": "The results of the LDA model highlighted several topics that were expressly about aspects of the voter fraud disinformation conversation. For instance, one notable topic that was isolated from the other topics, was about the alt-right hashtag “#stopthesteal”. Also notable was the similarly isolated Wall Street Journal and New York Times fact checking topic. Interestingly, tweets that claimed to have evidence of fraud greatly overlapped with tweets from right-wing news media sources, like Fox News. Overall, there are several threads of disinformation, ranging from ballot harvesting, conspiracies about the voting software, affidavits asserting fraud, and rumours of military involvement."
},
{
"code": null,
"e": 7651,
"s": 7506,
"text": "Analysis of the user communities with a community detection algorithm provided 5 distinct communities that varied in user count, as shown below."
},
{
"code": null,
"e": 7808,
"s": 7651,
"text": "The amplifier groups were those that pushed the voter fraud agenda, and the foreign groups represent potential foreign influence and are tiny in comparison."
},
{
"code": null,
"e": 8249,
"s": 7808,
"text": "Focusing on the spread of fake news, these five communities behaved differently when it came to sharing urls of news articles. The Media Cloud metadata contained the media inlink count which represents the number of times an article was linked to by other media sources. A highly in-linked article could be considered to be more mainstream. The graph below shows the trend of media in-link count over time for the three largest communities."
},
{
"code": null,
"e": 8608,
"s": 8249,
"text": "The above time series suggests that the center-left community tended to share articles that were more “mainstream” when compared to the two amplifier communities. Although the center-left community was more likely to share mainstream articles, they did not garner high retweet counts. This is shown below in a time series of mean retweet counts by community."
},
{
"code": null,
"e": 9101,
"s": 8608,
"text": "In fact, it is the third largest community “Amplifiers_1” that had the highest retweet counts for shared urls, despite representing only 11.5% of users. The concern here is that even if the center-left were trying to fact check those spreading the fake news of voter fraud, they were not getting much visibility on Twitter. It is also startling to realize that the relatively small group of “Amplifiers_1” was highly influential in spreading information, despite not sharing mainstream media."
},
{
"code": null,
"e": 9538,
"s": 9101,
"text": "It is commonly assumed that fake news is often on fringe websites, far out of the mainstream. Having calculated the Alexa rank or popularity of each news article url, it was possible to look at the relationship between a website’s “fringiness” and which communities were retweeting these fringe sites. In the heatmap below, the Alexa rank or “fringe-score” is weighted by retweet count and the community distribution by topic is mapped."
},
{
"code": null,
"e": 9901,
"s": 9538,
"text": "Here we can see that the “Amplifier_1” group not only garners the largest retweet count shares, but they also share the most fringe websites. Since we are interested in the causal question of whether the treatment of fake news has a causal effect on the outcome of retweet count, the relationship between fringe-scores and fake news articles is also of interest."
},
{
"code": null,
"e": 10952,
"s": 9901,
"text": "At this point, it became necessary to look at the actual text of the news articles to better help classify fake news. The process of topic modeling the news articles with LDA resulted in five of the seven topics being explicitly fake news articles. This allowed for labeling each url, and thereby each tweet, as either fake news or not. This NLP derived label is used as a proxy label in the setup of the causal experiment that is described later. Furthermore, in order to test the usefulness of the causal-text algorithm, I also labeled 100 of the most popular urls for fake news. This labeling covered 18% of the tweet-article dataset, and gave me roughly 28K tweet-article pairs that had both proxy labels via topic modeling and true labels via manual annotation. Having both proxy treatment labels and true treatment labels, allows for benchmarking the causal-text algorithm for this task. In the next three sections, I will discuss the details of the causal-text algorithm and introduce some of the causal concepts needed to understand the tool."
},
{
"code": null,
"e": 11434,
"s": 10952,
"text": "The causal-text algorithm used in this tutorial was created by Pryzant et al. (2021), it was introduced as “TEXTCAUSE” in a paper titled “Causal Effects of Linguistic Properties”. This causal algorithm makes use of another tool — CausalBERT, that was originally designed by Veitch et al. (2020). CausalBERT was developed to produce text embeddings for causal inference; in essence, the authors designed a way to use AI language models to adjust for text when testing for causality."
},
{
"code": null,
"e": 11933,
"s": 11434,
"text": "The causal-text algorithm has two components, first it makes use of distant supervision to improve the quality of proxy labels, and second, CausalBERT is used to adjust for the text. Pryzant et al. tried to formalize the causal effect of a writer’s intent, along with establishing the assumptions necessary to identify the causal effect from observational data. Another contribution of this work is that they proposed an estimator for this setting where the bias is bounded when adjusting for text."
},
{
"code": null,
"e": 12617,
"s": 11933,
"text": "The VoterFraud2020 dataset represents observational data, where the tweets were obtained without an intervention. Since, the measurement of causal effect requires the fulfillment of the ceteris paribus assumption, where all covariates are kept fixed, we must reason about interventions. Pryzant et al. describe two challenges to estimating causal effects from observational data. Firstly, there is a need to “formalize the causal effect of interest by specifying the hypothetical intervention to which it corresponds.” (Pryzant et al., 2021). This challenge is overcome by imagining an intervention on the writer of a text, where they are told to use a different linguistic property."
},
{
"code": null,
"e": 13210,
"s": 12617,
"text": "The second challenge to causal inference is identification, where the actual linguistic property we are interested in can only be measured by a noisy proxy (e.g. topic labels). Therefore, the study also established the assumptions needed to recover the true causal effects of linguistic properties from the noisy proxy labels. The creators of the causal-text algorithm adjust for confounding in text with CausalBERT and prove that this process bounds the bias of the causal estimates. In my previous article about causality and NLP, I discussed in detail the issue of confounding due to text."
},
{
"code": null,
"e": 13646,
"s": 13210,
"text": "When discussing causal inference with observational data, it is necessary to talk about the average treatment effect (ATE). As seen in the image below, the ATE is the difference in potential outcomes between the real world (T=1) and the counterfactual world (T=0). I have previously described the potential outcomes framework in intuitive ways in two articles: Causal inference using NLP, and CausalML for Econometrics: Causal Forests."
},
{
"code": null,
"e": 14025,
"s": 13646,
"text": "However, as mentioned, we are also concerned with confounding. To deal with confounders (Wi), the backdoor adjustment formula (Pearl, 2009) can be used to rewrite the ATE in terms of all the observed variables: Ti for treatment and Yi for outcome. This confounding relationship is seen in the image below, where the confounder Wi has an effect on both the treatment and outcome."
},
{
"code": null,
"e": 14403,
"s": 14025,
"text": "The confounding effect of Wi results in a spurious correlation, which can also be referred to as “open backdoor paths that induce non-causal associations” (Pryzant et al., 2021). I have previously discussed spurious correlations and backdoor paths in an article about improving NLP models with causality. The backdoor adjustment formula for the ATE is shown in the image below."
},
{
"code": null,
"e": 14612,
"s": 14403,
"text": "If we assume the confounder Wi is discrete, then the data can be grouped into values of W, the average difference in potential outcomes can be calculated, and lastly, we take the average over the groups of W."
},
{
"code": null,
"e": 14691,
"s": 14612,
"text": "Pryzant et al. (2021) propose the following causal model of text and outcomes:"
},
{
"code": null,
"e": 15469,
"s": 14691,
"text": "The text is represented by W, which has the linguistic property T (as treatment), and other qualities Z (as covariates). Here, Z could be the topic, sentiment, length or other qualities of a text. This causal model is built with the literary argument that language is subject to two perspectives: the text as intended by the author and the text as interpreted by the reader. The second perspective of the reader is shown by T_tilde and Z_tilde — where T_tilde represents the treatment as received by the reader, and Z_tilde represents the other qualities of the text W as perceived by the reader. The outcome Y is affected by the tilde variables instead of Z and T directly. The T_hat variable represents the proxy label as derived from the text W, which could be topic labels."
},
{
"code": null,
"e": 15933,
"s": 15469,
"text": "The hypothetical intervention on the treatment, is to ask the writer to use (or not use) a linguistic property T, where T is a binary choice. It is not possible to use observational data to capture the unobserved linguistic characteristics of Z, because it is correlated with T. It is, however, possible to estimate the linguistic properties as perceived by a reader, which is represented by the tilde variables. The ATE of the reader’s perspective is defined as:"
},
{
"code": null,
"e": 16327,
"s": 15933,
"text": "In order to calculate the causal effect of interest, the ATE of the writer’s perspective, Pryzant et al. (2021) developed a theorem (Theorem 1) which exploited the ATE of the reader’s perspective as calculated from T_tilde. They define Z_tilde as a function of the text W, as seen in the image below, where the potential outcomes of Y are equivalent given either W or both T_tilde and Z_tilde."
},
{
"code": null,
"e": 16427,
"s": 16327,
"text": "Having defined Z_tilde as such, it is then possible to define the ATErea as the following equation:"
},
{
"code": null,
"e": 17221,
"s": 16427,
"text": "The ATErea is said to be equal to the ATEwri, and the text W, splits into the information that the reader uses to perceive the tilde variables. Z_tilde represents confounding properties, since it affects the outcome and is correlated with T_tilde. To be clear, this theorem only holds under certain assumptions, of which there are three. Firstly, unobserved confounding (W) blocks the backdoor paths between T_tilde and the outcome Y. Secondly, we need to assume that T = T_tilde, that is to say, there is an agreement of intent (ATEwri) and perception (ATErea). The last assumption is the positivity (or overlap) assumption, which is that the probability of the treatment is between 0 and 1. I provided an intuitive explanation of the positivity assumption in another article about causality."
},
{
"code": null,
"e": 17605,
"s": 17221,
"text": "A further complication is that we cannot observe the perception of the reader, in addition to not being able to directly observe the intent of the writer; hence, the need for proxies. For T_tilde it is possible to use a proxy T_hat to calculate the causal effect of interest, where the T_tilde is substituted out by T_hat in the previous equation to calculate an estimand (ATEproxγ)."
},
{
"code": null,
"e": 18138,
"s": 17605,
"text": "At this point it is necessary to adjust the estimand for confounding, in other words, adjust the ATEproxγ for Z_tilde. This is made possible using CausalBERT, a pre-trained language model, to measure T_hat. The other advantage of this approach is that the bias due to the proxy label is bounded, such that it is benign — “it can only decrease the magnitude to the effect but it will not change the sign.”. Pryzant et al. (2021), refer to this as Theorem 2, and state that a “more accurate proxy will yield a lower estimation bias.”."
},
{
"code": null,
"e": 18859,
"s": 18138,
"text": "Now that we have discussed how to use observational data for causal inference with text, the practical part is the estimation procedure. The causal-text algorithm has two important features: improving proxy labels and adjusting for text. The approach to improving the accuracy of the proxy labels is based on the fact that the bias is bounded. The proxy labels are improved using distant supervision, which was inspired by work on lexicon induction and label propagation. The goal is to improve the recall of proxy labels by training a classifier to predict the proxy label, then using that classifier to relabel examples that were labeled T=0 but look like T=1. Essentially, the proxy labels are relabeled if necessary."
},
{
"code": null,
"e": 19754,
"s": 18859,
"text": "The second feature of the causal-text algorithm is that it adjusts for the text using a pre-trained language model. The ATEproxγ is measured by using the text (W), the improved proxy labels (T_hat*) and the outcomes (Y). This relies on Theorem 1, which as described earlier shows how to adjust for the confounding parts of text. Pryzant et al. (2021) use a DistilBERT model to produce a representation of the text with embeddings and then select the vector corresponding to a prepended classification token, [CLS]. Pryzant et al. use Huggingface transformers implementation of DistilBERT which has 66M parameters, and the vectors for text adjustment Mt , add 3,080 parameters. This model is then optimized such that the representation b(W), directly approximates the confounding information, Z_tilde. An estimator, Q, is trained for the expected conditional outcome, as seen in the image below."
},
{
"code": null,
"e": 20346,
"s": 19754,
"text": "In this equation, the estimator Q is shown to be equivalent to the expected conditional outcome for Y, when given the proxy T_hat, which itself is based on not only the treatment, t, but also the model representation of Z_tilde (b(W)), and the covariates C. The proxy estimator, Q_hat, is equivalent to the parameterized sum of a bias term (b) and two vectors (Mbt , Mct ), that rely on representation b(W) and a c vector. The c vector is a one-hot encoding vector of covariates C, and the two Mt are learned for value t of the treatment. The training objective of this model is to optimize:"
},
{
"code": null,
"e": 20781,
"s": 20346,
"text": "In this equation, Θ is all the parameters of the model, and L(.) is the cross-entropy loss which is used with the estimator Q_hat, itself based on the Mt vectors. The original BERT masked language modeling objective (MLM) is represented as R(.), and the α hyperparameter is a penalty for the MLM objective. With the Q_hat estimator, the parameters Mbt and Mct are updated on examples where the improved proxy label is equivalent to t."
},
{
"code": null,
"e": 21002,
"s": 20781,
"text": "This setup is shown in the diagram below, where W represents the text, C represents the covariates and the CausalBERT model is a representation of the text such that it is possible to predict the potential outcomes of Y."
},
{
"code": null,
"e": 21597,
"s": 21002,
"text": "In summary, estimation with the full causal-text algorithm requires the improved proxy labels, and a causal model of the text and outcomes which extracts and adjusts for the confounding of Z_tilde. The algorithm also allows for the inclusion of covariates C when estimating the causal effect. As seen in the image above, the vector c and the model representation b(W) are used to predict the potential outcomes of Y while using information from T_hat*, the proxy label. The representation b(W) directly approximates the confounding information (Z_tilde), which allows it to adjust for the text."
},
{
"code": null,
"e": 21712,
"s": 21597,
"text": "Once the estimator Q_hat is fitted, it is possible to calculate the hatted ATEproxγ as seen in the equation below:"
},
{
"code": null,
"e": 22152,
"s": 21712,
"text": "The ATE that is derived with this method can be used to determine the causal effect of the reader’s perspective, which itself is assumed to be equivalent to the causal effect of the writer’s perspective. The accuracy of this ATE is dependent on how accurate the proxies are and how well CausalBERT adjusts for the text. The next section describes the experimental framework used to test for the causal effect of fake news on retweet count."
},
{
"code": null,
"e": 23090,
"s": 22152,
"text": "The causal question is whether fake news has a causal effect on retweet count. A few years ago, a very popular study in Science claimed that on social media, fake news spreads more rapidly than real news. This study, however, does not rely on causal analysis. There is a possibility that the results were based on spurious correlations between confounders and the retweet count. For instance, the community a user belonged to was not investigated, nor was the popularity of the news site. Some communities might be more vulnerable to spreading fake news, and people might be more likely to share popular news sites. Moreover, language is complex and the text of tweets can act as a confounder, so we need to control for topic, writing style, tone and length of the tweet. Therefore, there is value in designing a causal study where possible confounders are controlled for, and the tweet text itself is adjusted for confounding qualities."
},
{
"code": null,
"e": 24215,
"s": 23090,
"text": "As previously mentioned, there are two challenges to estimating causal effects from observational data: interventions and identification. Firstly, we need to reason about the hypothetical intervention that we would make on the writer’s intent, such that they would use (or not use) a particular linguistic property. It is necessary to think of the sharing of fake news as a linguistic property that represents the writer’s intent, then it can be a treatment, T, that can be intervened upon. More simply, we view the sharing of a url that links to fake news as a linguistic property, where the intervention would be to tell the user to share a real news article (T=0) instead of a fake news article (T=1). While intervening on this treatment, the remaining qualities of the tweet must be kept constant. We will refer to these other text qualities as Z, such that Z represents potential confounding factors like topic, style, tone or length. The tweet text will be referred to as W (or simply “text”), and additional covariates such as user community or Alexa rank will be denoted as C. This setup is shown in the image below."
},
{
"code": null,
"e": 25092,
"s": 24215,
"text": "The proxy treatment is a fake news label as determined by topic modeling of the articles with LDA. Since the dataset has gold labels for the fake news articles, there are two treatment variables (T_true and T_proxy) so that it is possible to benchmark the T_proxy against T_true. Lastly, the outcome Y is the retweet count. For a first test, the C variable is categorical, where a number is used to represent the user community. All other variables, except the text, are binary numerical indicators (0 or 1). For a second test, the Alexa rank is used as the covariate C, and we look specifically at a single community: “Amplifiers_1”. In this test, the Alexa rank for each url is turned into a categorical variable by binning the values by quantile. The next section details how I adapted the causal-text algorithm for this tutorial, and explains how to interpret the results."
},
{
"code": null,
"e": 25908,
"s": 25092,
"text": "Pryzant et al. (2021) shared the causal-text algorithm on GitHub, which utilized a Pytorch implementation of CausalBERT. For this tutorial, it was necessary to adapt the original causal-text package since it was specifically tailored to the causal experiments described in the introductory paper. Furthermore, it does not appear to be maintained (updated) by the authors, so I had to update the requirements. I also simplified the output and removed the extraneous simulation parts that were not needed for this tutorial. The rest of the changes were minor and were made in the process of debugging. Overall, I made very few changes to the original algorithm, my adaptation can be accessed on GitHub. If you find this algorithm useful, please star Pryzant et al.’s original repository for the causal-text algorithm."
},
{
"code": null,
"e": 26576,
"s": 25908,
"text": "The tool runs from the command line, and I suggest running it with a GPU to make use of the speed for deep learning. Here, I explain how to set up Colab (to make use of the free GPU instance) and run the causal-text algorithm. First though, the data needs to be in the correct format. The tool accepts a “.tsv” file with five columns, for five variables: T_proxy, T_true, C, Y, text. The covariates C have to be categorical, and represented by simple integers. The T_proxy, T_true and outcome, Y, variables must be binary numerical indicators (0 or 1). The “text” is simply the tweet text. The adapted causal-text algorithm produces seven different ATE result values."
},
{
"code": null,
"e": 27580,
"s": 26576,
"text": "Using the T_true label, the causal-text algorithm calculates an “oracle” ATE value; this can be thought of as the true ATE which will act as a baseline. Next, an “unadjusted” ATE value is calculated as an additional baseline, where the ATE is the expected difference in outcomes conditioned on T_hat without accounting for covariates. The next two values are “T-boost” ATE values, where T-boost refers to treatment boosting by improving proxy labels. The proxy labels are improved in two ways by two different classifiers. One classifier works only with positive and unlabeled data, while the other is a straightforward regression, specifically Sci-kit Learn’s stochastic gradient descent classifier. The next ATE value is one where the text has been adjusted for, this is the “W adjust” value. The last two ATE values combine the T-boosting with text adjustment, for one ATE value per classifier type. These last two values represent the full “TEXTCAUSE” algorithm as designed by Pryzant et al. (2021)."
},
{
"code": null,
"e": 27692,
"s": 27580,
"text": "The first step is to install the needed packages in Colab. This is done with the following single line of code:"
},
{
"code": null,
"e": 27737,
"s": 27692,
"text": "!pip install sklearn transformers tensorflow"
},
{
"code": null,
"e": 27784,
"s": 27737,
"text": "Next, we check to see if the GPU is available."
},
{
"code": null,
"e": 28099,
"s": 27784,
"text": "import torchif torch.cuda.is_available(): device = torch.device(\"cuda\") print('There are %d GPU(s) available.' % torch.cuda.device_count()) print('We will use the GPU:', torch.cuda.get_device_name(0)) !nvidia-smielse: print('No GPU available, using the CPU instead.') device = torch.device(\"cpu\")"
},
{
"code": null,
"e": 28232,
"s": 28099,
"text": "The “.tsv” file with the data should be saved in Google Drive for easy access. We simply mount the drive to get access to the files."
},
{
"code": null,
"e": 28293,
"s": 28232,
"text": "from google.colab import drivedrive.mount('/content/gdrive')"
},
{
"code": null,
"e": 28349,
"s": 28293,
"text": "Then we navigate to the folder where the data is saved."
},
{
"code": null,
"e": 28379,
"s": 28349,
"text": "%cd gdrive/My Drive/my_folder"
},
{
"code": null,
"e": 28453,
"s": 28379,
"text": "Next we clone the adapted repo for the causal-text algorithm from GitHub."
},
{
"code": null,
"e": 28508,
"s": 28453,
"text": "!git clone https://github.com/haayanau/causal-text.git"
},
{
"code": null,
"e": 28634,
"s": 28508,
"text": "After the causal-text package has been cloned, it is necessary to navigate to the directory where the main script is located."
},
{
"code": null,
"e": 28654,
"s": 28634,
"text": "%cd causal-text/src"
},
{
"code": null,
"e": 28883,
"s": 28654,
"text": "Running the algorithm is very simple, run the following command with the path leading to the “.tsv” file. The “run_cb” argument means that CausalBERT will be used to adjust for the text. The models are trained for 3 epochs each."
},
{
"code": null,
"e": 28961,
"s": 28883,
"text": "!python main.py --run_cb --data /content/gdrive/MyDrive/my_folder/my_data.tsv"
},
{
"code": null,
"e": 29438,
"s": 28961,
"text": "This command results in seven types of ATE values as described earlier. Pryzant et al.(2021) do caution that “ATE estimates lose fidelity when the proxy is less than 80% accurate”. They also claim that it is crucial to adjust for the confounding parts of text, and that estimates that account for C without adjusting for the text, might be worse than the unadjusted estimate. The next section briefly discusses the results of the two experiments, and suggests some extensions."
},
{
"code": null,
"e": 29461,
"s": 29438,
"text": "Results and Extensions"
},
{
"code": null,
"e": 29668,
"s": 29461,
"text": "For the first test, we are looking at the ATE of fake news (T) on retweet count (Y), with the user community (C) and tweet text as confounders. There are 15,468 observations and the results are shown below."
},
{
"code": null,
"e": 30286,
"s": 29668,
"text": "The true (oracle) ATE value suggests that there is practically no causal effect, which is contrary to the popular expectation that fake news spreads quicker than real news, and would garner higher retweet counts. The unadjusted ATE value also does not show causal effect, despite not accounting for covariate C. In terms of matching the true ATE value, the (W adjust) ATE that adjusts for text with CausalBERT comes the closest. Neither of the values from the full “TEXTCAUSE” algorithm (adjusts for text and improves labels) are as close to the true ATE as the W adjust value, which does not use the improved labels."
},
{
"code": null,
"e": 30476,
"s": 30286,
"text": "The second test looked only at the “Amplifiers_1” community and accounts for Alexa rank as a potentially confounding covariate. There are 1,485 observations and the results are shown below."
},
{
"code": null,
"e": 31051,
"s": 30476,
"text": "Here again, there does not appear to be a causal effect of fake news on retweet count, once we control for the Alexa rank. The true (oracle) ATE value is mildly negative, and the full version of the “TEXTCAUSE” algorithm that uses the “pu” classifier for T-boosting, produces the ATE that most closely matches the true value. This treatment boosted value (TextCause pu), not only includes improved proxy labels but also adjusts for the text with CausalBERT. The unadjusted ATE had the worst performance, however, all of the other ATE values had a similarly poor performance."
},
{
"code": null,
"e": 31891,
"s": 31051,
"text": "There is a strong possibility that there are unobserved confounders that have not been controlled for in this experiment. This might explain the lack of causal effect being detected, or conversely, there simply is no causal effect. At this point, we have not proven that there is a causal effect of fake news on retweet count, nor have we definitively proven that there is no causal effect. All we have done is bring into question the assumption popularly claimed by researchers, that fake news spreads faster than real news on social media. It might be possible that including further covariates would improve the experiment, however, it will be tricky to determine which covariates to include. There is also a possibility that the sample sizes were not big enough, especially for the second test where there were only 1,485 observations."
},
{
"code": null,
"e": 32538,
"s": 31891,
"text": "There are several extensions that we could implement. Starting with the first test, we could substitute the user community with Alexa rank for the covariate, C. For the second test, we could increase the sample size or even compare across communities. It would be helpful if the causal-text algorithm could accommodate more than one covariate (higher dimensionality). Even more useful, would be if the causal-text algorithm could deal with heterogeneous treatment effects and calculate the conditional average treatment effect (CATE). For instance, we could condition on user community, to see if there is a difference in CATEs across the groups."
},
{
"code": null,
"e": 33683,
"s": 32538,
"text": "The intersection of causal inference and NLP is fascinating, and the causal-text algorithm is a great example of creativity and initiative. My hope is that this research will continue to push the boundaries of what is possible with regards to methods for estimating a causal effect with text. In terms of application, the causal-text algorithm can be applied to various fields such as economics, healthcare, marketing, public policy and even epidemiology. There is a shift in thinking around the phenomenon of fake news, for instance, there are calls to treat the issue as a public health issue (Donovan, 2020). The WHO has taken an epidemiological approach, and are referring to incidents of fake news as “infodemics”. All of these changes suggest that it might be time to take a causal approach to disinformation. Exploring causality could be a way of developing an economics-inspired framework, for looking at the causal effect of disinformation on society (True Costs of Misinformation Workshop, TaSC, Shorenstein Center). Personally, I am interested in applying this method to economic research that utilizes open source social media data."
}
] |
Clear a list in C# | Firstly, set a list −
List<int> myList = new List<int>();
myList.Add(45);
myList.Add(77);
Now, to clear the above list, use Clear() −
myList.Clear();
Here is the complete code −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
List<int> myList = new List<int>();
myList.Add(45);
myList.Add(77);
Console.WriteLine("Elements: "+myList.Count);
myList.Clear();
Console.WriteLine("Elements after using clear: "+myList.Count);
}
}
Elements: 2
Elements after using clear: 0 | [
{
"code": null,
"e": 1084,
"s": 1062,
"text": "Firstly, set a list −"
},
{
"code": null,
"e": 1152,
"s": 1084,
"text": "List<int> myList = new List<int>();\nmyList.Add(45);\nmyList.Add(77);"
},
{
"code": null,
"e": 1196,
"s": 1152,
"text": "Now, to clear the above list, use Clear() −"
},
{
"code": null,
"e": 1212,
"s": 1196,
"text": "myList.Clear();"
},
{
"code": null,
"e": 1240,
"s": 1212,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1251,
"s": 1240,
"text": " Live Demo"
},
{
"code": null,
"e": 1587,
"s": 1251,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n List<int> myList = new List<int>();\n myList.Add(45);\n myList.Add(77);\n Console.WriteLine(\"Elements: \"+myList.Count);\n myList.Clear();\n Console.WriteLine(\"Elements after using clear: \"+myList.Count);\n }\n}"
},
{
"code": null,
"e": 1629,
"s": 1587,
"text": "Elements: 2\nElements after using clear: 0"
}
] |
C/C++ Tricky Programs - GeeksforGeeks | 28 Mar, 2022
We may come across various tricky programs in our day to day life. Maybe in technical interviews, coding tests, or in C/C++ classrooms.
Here is a list of such programs:-
Print text within double quotes (” “). This may seem easy but beginners may get puzzled while printing text within double-quotes.
C++
// CPP program to print double quotes#include<iostream> int main(){ std::cout << "\"geeksforgeeks\""; return 0;}
Output:
"geeksforgeeks"
To check if two numbers are equal without using arithmetic operators or comparison operators. The simplest solution for this is using Bitwise XOR operator (^). We know that, for two equal numbers XOR operator returns 0. We will use this trick to solve this problem.
C++
C
// C++ program to check if two numbers are equal// without using arithmetic operators or// comparison operators#include <iostream>using namespace std; int main(){ int x = 10; int y = 10; if (!(x ^ y)) cout << " x is equal to y "; else cout << " x is not equal to y "; return 0;} // This code is contributed by shivani
// C program to check if two numbers are equal// without using arithmetic operators or// comparison operators#include<stdio.h> int main(){ int x = 10; int y = 10; if ( !(x ^ y) ) printf(" x is equal to y "); else printf(" x is not equal to y "); return 0;}
Output:
x is equal to y
Print all natural numbers upto N without using semi-colon. We use the idea of recursively calling main function.
C++
// C++ program to print all natural numbers upto// N without using semi-colon#include<iostream> using namespace std;int N = 10; int main(){ static int x = 1; if (cout << x << " " && x++ < N && main()) { } return 0;}
Output:
1 2 3 4 5 6 7 8 9 10
To Swap the values of two variables without using any extra variable.
C++
// C++ program to check if two numbers are equal#include<iostream> int main(){ int x = 10; int y = 70; x = x + y; y = x - y; x = x - y; cout << "X : " << x << "\n"; cout << "Y : " << y << "\n"; return 0;}
Output:
X : 70
Y : 10
Program to find Maximum and minimum of two numbers without using any loop or condition. The simplest trick is-
C++
// C++ program to find maximum and minimum of// two numbers without using loop and any// condition.#include<bits/stdc++.h> int main (){ int a = 15, b = 20; printf("max = %d\n", ((a + b) + abs(a - b)) / 2); printf("min = %d", ((a + b) - abs(a - b)) / 2); return 0;}
Output:
max = 20
min = 15
Print the maximum value of an unsigned int using One’s Complement (~) Operator in C. Here is a trick to find the maximum value of an unsigned int using one’s complement operator:
C
// C program to print maximum value of// unsigned int.#include<stdio.h> int main(){ unsigned int max; max = 0; max = ~max; printf("Max value : %u ", max); return 0;}
To find sum of two integers without using ‘+’ operator. This is a very easy mathematics trick. We know that a + b = – (-a-b). So this will work as a trick for us.
C++
// CPP program to print sum of two integers// without +#include<iostream> using namespace std;int main(){ int a = 5; int b = 5; int sum = -( -a-b ); cout << sum; return 0;}
Output:
10
Program to verifies the condition inside if block.
C++
// CPP program to verifies the condition inside if block// It just verifies the condition inside if block,// i.e., cout << "geeks" which returns a non-zero value,// !(non-zero value) is false, hence it executes else// Hence technically it only executes else block#include<iostream> using namespace std;int main(){ if (!(cout << "geeks")) cout <<" geeks "; else cout << "forgeeks "; return 0;}
Output:
geeksforgeeks
Program to divide an integer by 4 without using ‘/’ operator. One of the most efficient way to divide an integer by 4 is to use right shift operator (“>>”).
C++
// CPP program to divide a number by 4// without using '/'#include<iostream> using namespace std;int main(){ int n = 4; n = n >> 2; cout << n; return 0;}
Output:
1
Program to check endianness of the computer.
C
// C program to find if machine is little// endian or big endian.#include <stdio.h> int main(){ unsigned int n = 1; char *c = (char*)&n; if (*c) printf("LITTLE ENDIAN"); else printf("BIG ENDIAN"); return 0;}
This article is contributed by Smitha Dinesh Semwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rajiv Saxena
harinibachu
tusharmonga014
shivanisinghss2110
sooda367
sumitgumber28
c-puzzle
cpp-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 24371,
"s": 24234,
"text": "We may come across various tricky programs in our day to day life. Maybe in technical interviews, coding tests, or in C/C++ classrooms. "
},
{
"code": null,
"e": 24406,
"s": 24371,
"text": "Here is a list of such programs:- "
},
{
"code": null,
"e": 24536,
"s": 24406,
"text": "Print text within double quotes (” “). This may seem easy but beginners may get puzzled while printing text within double-quotes."
},
{
"code": null,
"e": 24540,
"s": 24536,
"text": "C++"
},
{
"code": "// CPP program to print double quotes#include<iostream> int main(){ std::cout << \"\\\"geeksforgeeks\\\"\"; return 0;}",
"e": 24657,
"s": 24540,
"text": null
},
{
"code": null,
"e": 24666,
"s": 24657,
"text": "Output: "
},
{
"code": null,
"e": 24682,
"s": 24666,
"text": "\"geeksforgeeks\""
},
{
"code": null,
"e": 24948,
"s": 24682,
"text": "To check if two numbers are equal without using arithmetic operators or comparison operators. The simplest solution for this is using Bitwise XOR operator (^). We know that, for two equal numbers XOR operator returns 0. We will use this trick to solve this problem."
},
{
"code": null,
"e": 24952,
"s": 24948,
"text": "C++"
},
{
"code": null,
"e": 24954,
"s": 24952,
"text": "C"
},
{
"code": "// C++ program to check if two numbers are equal// without using arithmetic operators or// comparison operators#include <iostream>using namespace std; int main(){ int x = 10; int y = 10; if (!(x ^ y)) cout << \" x is equal to y \"; else cout << \" x is not equal to y \"; return 0;} // This code is contributed by shivani",
"e": 25303,
"s": 24954,
"text": null
},
{
"code": "// C program to check if two numbers are equal// without using arithmetic operators or// comparison operators#include<stdio.h> int main(){ int x = 10; int y = 10; if ( !(x ^ y) ) printf(\" x is equal to y \"); else printf(\" x is not equal to y \"); return 0;}",
"e": 25580,
"s": 25303,
"text": null
},
{
"code": null,
"e": 25589,
"s": 25580,
"text": "Output: "
},
{
"code": null,
"e": 25605,
"s": 25589,
"text": "x is equal to y"
},
{
"code": null,
"e": 25718,
"s": 25605,
"text": "Print all natural numbers upto N without using semi-colon. We use the idea of recursively calling main function."
},
{
"code": null,
"e": 25722,
"s": 25718,
"text": "C++"
},
{
"code": "// C++ program to print all natural numbers upto// N without using semi-colon#include<iostream> using namespace std;int N = 10; int main(){ static int x = 1; if (cout << x << \" \" && x++ < N && main()) { } return 0;}",
"e": 25942,
"s": 25722,
"text": null
},
{
"code": null,
"e": 25951,
"s": 25942,
"text": "Output: "
},
{
"code": null,
"e": 25973,
"s": 25951,
"text": "1 2 3 4 5 6 7 8 9 10 "
},
{
"code": null,
"e": 26043,
"s": 25973,
"text": "To Swap the values of two variables without using any extra variable."
},
{
"code": null,
"e": 26047,
"s": 26043,
"text": "C++"
},
{
"code": "// C++ program to check if two numbers are equal#include<iostream> int main(){ int x = 10; int y = 70; x = x + y; y = x - y; x = x - y; cout << \"X : \" << x << \"\\n\"; cout << \"Y : \" << y << \"\\n\"; return 0;}",
"e": 26274,
"s": 26047,
"text": null
},
{
"code": null,
"e": 26283,
"s": 26274,
"text": "Output: "
},
{
"code": null,
"e": 26297,
"s": 26283,
"text": "X : 70\nY : 10"
},
{
"code": null,
"e": 26408,
"s": 26297,
"text": "Program to find Maximum and minimum of two numbers without using any loop or condition. The simplest trick is-"
},
{
"code": null,
"e": 26412,
"s": 26408,
"text": "C++"
},
{
"code": "// C++ program to find maximum and minimum of// two numbers without using loop and any// condition.#include<bits/stdc++.h> int main (){ int a = 15, b = 20; printf(\"max = %d\\n\", ((a + b) + abs(a - b)) / 2); printf(\"min = %d\", ((a + b) - abs(a - b)) / 2); return 0;}",
"e": 26685,
"s": 26412,
"text": null
},
{
"code": null,
"e": 26694,
"s": 26685,
"text": "Output: "
},
{
"code": null,
"e": 26712,
"s": 26694,
"text": "max = 20\nmin = 15"
},
{
"code": null,
"e": 26891,
"s": 26712,
"text": "Print the maximum value of an unsigned int using One’s Complement (~) Operator in C. Here is a trick to find the maximum value of an unsigned int using one’s complement operator:"
},
{
"code": null,
"e": 26893,
"s": 26891,
"text": "C"
},
{
"code": "// C program to print maximum value of// unsigned int.#include<stdio.h> int main(){ unsigned int max; max = 0; max = ~max; printf(\"Max value : %u \", max); return 0;} ",
"e": 27072,
"s": 26893,
"text": null
},
{
"code": null,
"e": 27235,
"s": 27072,
"text": "To find sum of two integers without using ‘+’ operator. This is a very easy mathematics trick. We know that a + b = – (-a-b). So this will work as a trick for us."
},
{
"code": null,
"e": 27239,
"s": 27235,
"text": "C++"
},
{
"code": "// CPP program to print sum of two integers// without +#include<iostream> using namespace std;int main(){ int a = 5; int b = 5; int sum = -( -a-b ); cout << sum; return 0;}",
"e": 27417,
"s": 27239,
"text": null
},
{
"code": null,
"e": 27426,
"s": 27417,
"text": "Output: "
},
{
"code": null,
"e": 27429,
"s": 27426,
"text": "10"
},
{
"code": null,
"e": 27480,
"s": 27429,
"text": "Program to verifies the condition inside if block."
},
{
"code": null,
"e": 27484,
"s": 27480,
"text": "C++"
},
{
"code": "// CPP program to verifies the condition inside if block// It just verifies the condition inside if block,// i.e., cout << \"geeks\" which returns a non-zero value,// !(non-zero value) is false, hence it executes else// Hence technically it only executes else block#include<iostream> using namespace std;int main(){ if (!(cout << \"geeks\")) cout <<\" geeks \"; else cout << \"forgeeks \"; return 0;}",
"e": 27897,
"s": 27484,
"text": null
},
{
"code": null,
"e": 27906,
"s": 27897,
"text": "Output: "
},
{
"code": null,
"e": 27920,
"s": 27906,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 28077,
"s": 27920,
"text": "Program to divide an integer by 4 without using ‘/’ operator. One of the most efficient way to divide an integer by 4 is to use right shift operator (“>>”)."
},
{
"code": null,
"e": 28081,
"s": 28077,
"text": "C++"
},
{
"code": "// CPP program to divide a number by 4// without using '/'#include<iostream> using namespace std;int main(){ int n = 4; n = n >> 2; cout << n; return 0;} ",
"e": 28244,
"s": 28081,
"text": null
},
{
"code": null,
"e": 28253,
"s": 28244,
"text": "Output: "
},
{
"code": null,
"e": 28255,
"s": 28253,
"text": "1"
},
{
"code": null,
"e": 28300,
"s": 28255,
"text": "Program to check endianness of the computer."
},
{
"code": null,
"e": 28302,
"s": 28300,
"text": "C"
},
{
"code": "// C program to find if machine is little// endian or big endian.#include <stdio.h> int main(){ unsigned int n = 1; char *c = (char*)&n; if (*c) printf(\"LITTLE ENDIAN\"); else printf(\"BIG ENDIAN\"); return 0;}",
"e": 28535,
"s": 28302,
"text": null
},
{
"code": null,
"e": 28963,
"s": 28535,
"text": "This article is contributed by Smitha Dinesh Semwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28976,
"s": 28963,
"text": "Rajiv Saxena"
},
{
"code": null,
"e": 28988,
"s": 28976,
"text": "harinibachu"
},
{
"code": null,
"e": 29003,
"s": 28988,
"text": "tusharmonga014"
},
{
"code": null,
"e": 29022,
"s": 29003,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 29031,
"s": 29022,
"text": "sooda367"
},
{
"code": null,
"e": 29045,
"s": 29031,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29054,
"s": 29045,
"text": "c-puzzle"
},
{
"code": null,
"e": 29065,
"s": 29054,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 29076,
"s": 29065,
"text": "C Language"
},
{
"code": null,
"e": 29080,
"s": 29076,
"text": "C++"
},
{
"code": null,
"e": 29084,
"s": 29080,
"text": "CPP"
},
{
"code": null,
"e": 29182,
"s": 29084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29191,
"s": 29182,
"text": "Comments"
},
{
"code": null,
"e": 29204,
"s": 29191,
"text": "Old Comments"
},
{
"code": null,
"e": 29242,
"s": 29204,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29268,
"s": 29242,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29288,
"s": 29268,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29310,
"s": 29288,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29348,
"s": 29310,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29366,
"s": 29348,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29412,
"s": 29366,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29431,
"s": 29412,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29474,
"s": 29431,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Arcade inbuilt functions to draw polygon in Python3 - GeeksforGeeks | 11 Oct, 2020
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions.
Arcade has two inbuilt functions for drawing a polygon:
1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of the polygon.
Syntax: arcade.draw_polygon_outline (point_list, color, line_width )
Parameters:
point_list: List of points making up the lines. Each point is in a list. So it is a list of lists.
color (Color): specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters.)
line_width:- Width of the line in pixels.
Example:
Python3
import arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, "Draw a polygon for GfG ") arcade.set_background_color(arcade.color.ORANGE) # Start the render process.arcade.start_render() point_list = ((30, 240), (45, 240), (60, 255), (60, 285), (45, 300), (30, 300))arcade.draw_polygon_outline(point_list, arcade.color.SPANISH_VIOLET, 3) arcade.finish_render() arcade.run()
Output:
2. arcade.draw_polygon_filled( ): This inbuilt function of arcade is used to draw polygon filled with color.
Syntax: arcade.draw_polygon_filled (point_list, color )
Parameters:
point_list- It is basically List of points where each point is in a list. So it is a list of lists.
Color – specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters. )
Example:
Python3
import arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, "Draw a polygon for GfG ") arcade.set_background_color(arcade.color.ORANGE) # Start the render process.arcade.start_render() point_list = ((150, 240), (165, 240), (180, 255), (180, 285), (165, 300), (150, 300))arcade.draw_polygon_filled(point_list, arcade.color.SPANISH_VIOLET) arcade.finish_render() arcade.run()
Output:
Python-Arcade
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 24138,
"s": 23927,
"text": "The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions."
},
{
"code": null,
"e": 24194,
"s": 24138,
"text": "Arcade has two inbuilt functions for drawing a polygon:"
},
{
"code": null,
"e": 24289,
"s": 24194,
"text": "1. arcade.draw_polygon_outline( ) : This function is used to draw the outline of the polygon. "
},
{
"code": null,
"e": 24360,
"s": 24289,
"text": "Syntax: arcade.draw_polygon_outline (point_list, color, line_width )"
},
{
"code": null,
"e": 24372,
"s": 24360,
"text": "Parameters:"
},
{
"code": null,
"e": 24471,
"s": 24372,
"text": "point_list: List of points making up the lines. Each point is in a list. So it is a list of lists."
},
{
"code": null,
"e": 24581,
"s": 24471,
"text": "color (Color): specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters.)"
},
{
"code": null,
"e": 24623,
"s": 24581,
"text": "line_width:- Width of the line in pixels."
},
{
"code": null,
"e": 24632,
"s": 24623,
"text": "Example:"
},
{
"code": null,
"e": 24640,
"s": 24632,
"text": "Python3"
},
{
"code": "import arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, \"Draw a polygon for GfG \") arcade.set_background_color(arcade.color.ORANGE) # Start the render process.arcade.start_render() point_list = ((30, 240), (45, 240), (60, 255), (60, 285), (45, 300), (30, 300))arcade.draw_polygon_outline(point_list, arcade.color.SPANISH_VIOLET, 3) arcade.finish_render() arcade.run()",
"e": 25140,
"s": 24640,
"text": null
},
{
"code": null,
"e": 25148,
"s": 25140,
"text": "Output:"
},
{
"code": null,
"e": 25258,
"s": 25148,
"text": "2. arcade.draw_polygon_filled( ): This inbuilt function of arcade is used to draw polygon filled with color. "
},
{
"code": null,
"e": 25314,
"s": 25258,
"text": "Syntax: arcade.draw_polygon_filled (point_list, color )"
},
{
"code": null,
"e": 25326,
"s": 25314,
"text": "Parameters:"
},
{
"code": null,
"e": 25426,
"s": 25326,
"text": "point_list- It is basically List of points where each point is in a list. So it is a list of lists."
},
{
"code": null,
"e": 25530,
"s": 25426,
"text": "Color – specify color using arcade.color.COLOR NAME. (Note that color name should in Capital letters. )"
},
{
"code": null,
"e": 25539,
"s": 25530,
"text": "Example:"
},
{
"code": null,
"e": 25547,
"s": 25539,
"text": "Python3"
},
{
"code": "import arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, \"Draw a polygon for GfG \") arcade.set_background_color(arcade.color.ORANGE) # Start the render process.arcade.start_render() point_list = ((150, 240), (165, 240), (180, 255), (180, 285), (165, 300), (150, 300))arcade.draw_polygon_filled(point_list, arcade.color.SPANISH_VIOLET) arcade.finish_render() arcade.run()",
"e": 26049,
"s": 25547,
"text": null
},
{
"code": null,
"e": 26057,
"s": 26049,
"text": "Output:"
},
{
"code": null,
"e": 26071,
"s": 26057,
"text": "Python-Arcade"
},
{
"code": null,
"e": 26078,
"s": 26071,
"text": "Python"
},
{
"code": null,
"e": 26176,
"s": 26078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26185,
"s": 26176,
"text": "Comments"
},
{
"code": null,
"e": 26198,
"s": 26185,
"text": "Old Comments"
},
{
"code": null,
"e": 26230,
"s": 26198,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26286,
"s": 26230,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26328,
"s": 26286,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26370,
"s": 26328,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26406,
"s": 26370,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26428,
"s": 26406,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26467,
"s": 26428,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26494,
"s": 26467,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26525,
"s": 26494,
"text": "Python | os.path.join() method"
}
] |
Add Column to Pandas DataFrame with a Default Value - GeeksforGeeks | 29 Aug, 2020
The three ways to add a column to Pandas DataFrame with Default Value.
Using pandas.DataFrame.assign(**kwargs)
Using [] operator
Using pandas.DataFrame.insert()
It Assigns new columns to a DataFrame and returns a new object with all existing columns to new ones. Existing columns that are re-assigned will be overwritten.
Syntax: Pandas.DataFrame.assign(**kwargs)
Parameters : **kwargsdict of {str: callable or Series}
Returns : DataFrame
Let’s understand with examples:
First, create a simple DataFrame.
Python3
# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({"Name": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], "Address": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], "ID": [20123, 20124, 20145, 20146, 20147], "Sell": [140000, 300000, 600000, 200000, 600000]}) print("Original DataFrame :")display(df)
Output:
Add a new column:
Python3
new_df = df.assign(profit=[40000, 20000, 30000, 60000, 200000])new_df
Output:
Add a new column with Default Value:
Python3
new_df = df.assign(profit='NAN')new_df
Output:
We can use DataFrame indexing to create a new column in DataFrame and set it to default values.
Syntax:
df[col_name]=value
Let’s understand with an example:
Python3
# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({"Name": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], "Address": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], "ID": [20123, 20124, 20145, 20146, 20147], "Sell": [140000, 300000, 600000, 200000, 600000]}) print("Original DataFrame :")display(df)
Output:
Add new column in Dataframe:
Python3
df['loss'] = [40000, 20000, 30000, 60000, 200000]df
Output:
Add a new column with default values:
Python3
df['loss'] = 'NAN'df
Output:
Add new column into DataFrame at specified location.
Syntax: DataFrame.insert(loc, column, value, allow_duplicates=False)
Parameters
loc : int Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hashable object Label of the inserted column.
value : int, Series, or array-like
allow_duplicates : bool, optional
Let’s understand with examples:
Python3
# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({"Name": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], "Address": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], "ID": [20123, 20124, 20145, 20146, 20147], "Sell": [140000, 300000, 600000, 200000, 600000]}) print("Original DataFrame :")display(df)
Output:
Add a new column with default value:
Python3
df.insert(2, "expenditure", 4500, allow_duplicates=False)df
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 23972,
"s": 23901,
"text": "The three ways to add a column to Pandas DataFrame with Default Value."
},
{
"code": null,
"e": 24012,
"s": 23972,
"text": "Using pandas.DataFrame.assign(**kwargs)"
},
{
"code": null,
"e": 24030,
"s": 24012,
"text": "Using [] operator"
},
{
"code": null,
"e": 24062,
"s": 24030,
"text": "Using pandas.DataFrame.insert()"
},
{
"code": null,
"e": 24223,
"s": 24062,
"text": "It Assigns new columns to a DataFrame and returns a new object with all existing columns to new ones. Existing columns that are re-assigned will be overwritten."
},
{
"code": null,
"e": 24265,
"s": 24223,
"text": "Syntax: Pandas.DataFrame.assign(**kwargs)"
},
{
"code": null,
"e": 24320,
"s": 24265,
"text": "Parameters : **kwargsdict of {str: callable or Series}"
},
{
"code": null,
"e": 24340,
"s": 24320,
"text": "Returns : DataFrame"
},
{
"code": null,
"e": 24372,
"s": 24340,
"text": "Let’s understand with examples:"
},
{
"code": null,
"e": 24406,
"s": 24372,
"text": "First, create a simple DataFrame."
},
{
"code": null,
"e": 24414,
"s": 24406,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({\"Name\": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], \"Address\": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], \"ID\": [20123, 20124, 20145, 20146, 20147], \"Sell\": [140000, 300000, 600000, 200000, 600000]}) print(\"Original DataFrame :\")display(df)",
"e": 24890,
"s": 24414,
"text": null
},
{
"code": null,
"e": 24898,
"s": 24890,
"text": "Output:"
},
{
"code": null,
"e": 24916,
"s": 24898,
"text": "Add a new column:"
},
{
"code": null,
"e": 24924,
"s": 24916,
"text": "Python3"
},
{
"code": "new_df = df.assign(profit=[40000, 20000, 30000, 60000, 200000])new_df",
"e": 24994,
"s": 24924,
"text": null
},
{
"code": null,
"e": 25002,
"s": 24994,
"text": "Output:"
},
{
"code": null,
"e": 25039,
"s": 25002,
"text": "Add a new column with Default Value:"
},
{
"code": null,
"e": 25047,
"s": 25039,
"text": "Python3"
},
{
"code": "new_df = df.assign(profit='NAN')new_df",
"e": 25086,
"s": 25047,
"text": null
},
{
"code": null,
"e": 25094,
"s": 25086,
"text": "Output:"
},
{
"code": null,
"e": 25190,
"s": 25094,
"text": "We can use DataFrame indexing to create a new column in DataFrame and set it to default values."
},
{
"code": null,
"e": 25198,
"s": 25190,
"text": "Syntax:"
},
{
"code": null,
"e": 25218,
"s": 25198,
"text": "df[col_name]=value\n"
},
{
"code": null,
"e": 25252,
"s": 25218,
"text": "Let’s understand with an example:"
},
{
"code": null,
"e": 25260,
"s": 25252,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({\"Name\": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], \"Address\": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], \"ID\": [20123, 20124, 20145, 20146, 20147], \"Sell\": [140000, 300000, 600000, 200000, 600000]}) print(\"Original DataFrame :\")display(df)",
"e": 25794,
"s": 25260,
"text": null
},
{
"code": null,
"e": 25802,
"s": 25794,
"text": "Output:"
},
{
"code": null,
"e": 25831,
"s": 25802,
"text": "Add new column in Dataframe:"
},
{
"code": null,
"e": 25839,
"s": 25831,
"text": "Python3"
},
{
"code": "df['loss'] = [40000, 20000, 30000, 60000, 200000]df",
"e": 25891,
"s": 25839,
"text": null
},
{
"code": null,
"e": 25899,
"s": 25891,
"text": "Output:"
},
{
"code": null,
"e": 25937,
"s": 25899,
"text": "Add a new column with default values:"
},
{
"code": null,
"e": 25945,
"s": 25937,
"text": "Python3"
},
{
"code": "df['loss'] = 'NAN'df",
"e": 25966,
"s": 25945,
"text": null
},
{
"code": null,
"e": 25974,
"s": 25966,
"text": "Output:"
},
{
"code": null,
"e": 26027,
"s": 25974,
"text": "Add new column into DataFrame at specified location."
},
{
"code": null,
"e": 26096,
"s": 26027,
"text": "Syntax: DataFrame.insert(loc, column, value, allow_duplicates=False)"
},
{
"code": null,
"e": 26107,
"s": 26096,
"text": "Parameters"
},
{
"code": null,
"e": 26172,
"s": 26107,
"text": "loc : int Insertion index. Must verify 0 <= loc <= len(columns)."
},
{
"code": null,
"e": 26243,
"s": 26172,
"text": "column : str, number, or hashable object Label of the inserted column."
},
{
"code": null,
"e": 26278,
"s": 26243,
"text": "value : int, Series, or array-like"
},
{
"code": null,
"e": 26312,
"s": 26278,
"text": "allow_duplicates : bool, optional"
},
{
"code": null,
"e": 26344,
"s": 26312,
"text": "Let’s understand with examples:"
},
{
"code": null,
"e": 26352,
"s": 26344,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating the dataframedf = pd.DataFrame({\"Name\": ['Anurag', 'Manjeet', 'Shubham', 'Saurabh', 'Ujjawal'], \"Address\": ['Patna', 'Delhi', 'Coimbatore', 'Greater noida', 'Patna'], \"ID\": [20123, 20124, 20145, 20146, 20147], \"Sell\": [140000, 300000, 600000, 200000, 600000]}) print(\"Original DataFrame :\")display(df)",
"e": 26886,
"s": 26352,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26886,
"text": "Output:"
},
{
"code": null,
"e": 26931,
"s": 26894,
"text": "Add a new column with default value:"
},
{
"code": null,
"e": 26939,
"s": 26931,
"text": "Python3"
},
{
"code": "df.insert(2, \"expenditure\", 4500, allow_duplicates=False)df",
"e": 26999,
"s": 26939,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26999,
"text": "Output:"
},
{
"code": null,
"e": 27031,
"s": 27007,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27054,
"s": 27031,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 27068,
"s": 27054,
"text": "Python-pandas"
},
{
"code": null,
"e": 27075,
"s": 27068,
"text": "Python"
},
{
"code": null,
"e": 27173,
"s": 27075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27182,
"s": 27173,
"text": "Comments"
},
{
"code": null,
"e": 27195,
"s": 27182,
"text": "Old Comments"
},
{
"code": null,
"e": 27227,
"s": 27195,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27283,
"s": 27227,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27325,
"s": 27283,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27367,
"s": 27325,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27403,
"s": 27367,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27425,
"s": 27403,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27464,
"s": 27425,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27491,
"s": 27464,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27522,
"s": 27491,
"text": "Python | os.path.join() method"
}
] |
EasyMock - Verifying Behavior | EasyMock can ensure whether a mock is being used or not. It is done using the verify() method. Take a look at the following code snippet.
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
Step 1: Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2: Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
//return calcService.add(input1, input2);
return input1 + input2;
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3: Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(EasyMockRunner.class)
public class MathApplicationTester {
// @TestSubject annotation is used to identify class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
//EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
Now run the Test Runner to see the result.
C:\EasyMock_WORKSPACE>java TestRunner
Verify the output.
true
Step 1: Create an interface CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2: Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
//return calcService.add(input1, input2);
return input1 + input2;
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3: Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(EasyMockRunner.class)
public class MathApplicationTester {
// @TestSubject annotation is used to identify class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Verify the output.
testAdd(MathApplicationTester):
Expectation failure on verify:
CalculatorService.add(10.0, 20.0): expected: 1, actual: 0
false
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2047,
"s": 1909,
"text": "EasyMock can ensure whether a mock is being used or not. It is done using the verify() method. Take a look at the following code snippet."
},
{
"code": null,
"e": 2263,
"s": 2047,
"text": "//activate the mock\nEasyMock.replay(calcService);\n\n//test the add functionality\nAssert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n\n//verify call to calcService is made or not\nEasyMock.verify(calcService);"
},
{
"code": null,
"e": 2350,
"s": 2263,
"text": "Step 1: Create an interface called CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2379,
"s": 2350,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2639,
"s": 2379,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2696,
"s": 2639,
"text": "Step 2: Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2723,
"s": 2696,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3379,
"s": 2723,
"text": "public class MathApplication {\n private CalculatorService calcService;\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n public double add(double input1, double input2){\n //return calcService.add(input1, input2);\n return input1 + input2;\n }\n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3418,
"s": 3379,
"text": "Step 3: Test the MathApplication class"
},
{
"code": null,
"e": 3538,
"s": 3418,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock."
},
{
"code": null,
"e": 3571,
"s": 3538,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 4663,
"s": 3571,
"text": "import org.easymock.EasyMock;\nimport org.easymock.EasyMockRunner;\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(EasyMockRunner.class)\npublic class MathApplicationTester {\n // @TestSubject annotation is used to identify class which is going to use the mock object\n @TestSubject\n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);\n\n //activate the mock\n EasyMock.replay(calcService);\t\n\t\t\n //test the add functionality\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n\n //verify call to calcService is made or not\n //EasyMock.verify(calcService);\n }\n}"
},
{
"code": null,
"e": 4690,
"s": 4663,
"text": "Step 4: Execute test cases"
},
{
"code": null,
"e": 4784,
"s": 4690,
"text": "Create a java class file named TestRunner in C:\\> EasyMock_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 4806,
"s": 4784,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 5233,
"s": 4806,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 5259,
"s": 5233,
"text": "Step 5: Verify the Result"
},
{
"code": null,
"e": 5313,
"s": 5259,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 5434,
"s": 5313,
"text": "C:\\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java\n"
},
{
"code": null,
"e": 5477,
"s": 5434,
"text": "Now run the Test Runner to see the result."
},
{
"code": null,
"e": 5516,
"s": 5477,
"text": "C:\\EasyMock_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 5535,
"s": 5516,
"text": "Verify the output."
},
{
"code": null,
"e": 5541,
"s": 5535,
"text": "true\n"
},
{
"code": null,
"e": 5621,
"s": 5541,
"text": "Step 1: Create an interface CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 5650,
"s": 5621,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 5910,
"s": 5650,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 5967,
"s": 5910,
"text": "Step 2: Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 5994,
"s": 5967,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 6650,
"s": 5994,
"text": "public class MathApplication {\n private CalculatorService calcService;\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n public double add(double input1, double input2){\n //return calcService.add(input1, input2);\n return input1 + input2;\n }\n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 6689,
"s": 6650,
"text": "Step 3: Test the MathApplication class"
},
{
"code": null,
"e": 6809,
"s": 6689,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock."
},
{
"code": null,
"e": 6842,
"s": 6809,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 7932,
"s": 6842,
"text": "import org.easymock.EasyMock;\nimport org.easymock.EasyMockRunner;\nimport org.easymock.Mock;\nimport org.easymock.TestSubject;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(EasyMockRunner.class)\npublic class MathApplicationTester {\n // @TestSubject annotation is used to identify class which is going to use the mock object\n @TestSubject\n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);\n\n //activate the mock\n EasyMock.replay(calcService);\t\n\t\t\n //test the add functionality\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n\n //verify call to calcService is made or not\n EasyMock.verify(calcService);\n }\n}"
},
{
"code": null,
"e": 7959,
"s": 7932,
"text": "Step 4: Execute test cases"
},
{
"code": null,
"e": 8053,
"s": 7959,
"text": "Create a java class file named TestRunner in C:\\> EasyMock_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 8075,
"s": 8053,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 8502,
"s": 8075,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 8528,
"s": 8502,
"text": "Step 5: Verify the Result"
},
{
"code": null,
"e": 8582,
"s": 8528,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 8703,
"s": 8582,
"text": "C:\\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java\n"
},
{
"code": null,
"e": 8747,
"s": 8703,
"text": "Now run the Test Runner to see the result −"
},
{
"code": null,
"e": 8786,
"s": 8747,
"text": "C:\\EasyMock_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 8805,
"s": 8786,
"text": "Verify the output."
},
{
"code": null,
"e": 8943,
"s": 8805,
"text": "testAdd(MathApplicationTester): \n Expectation failure on verify:\n CalculatorService.add(10.0, 20.0): expected: 1, actual: 0\nfalse\n"
},
{
"code": null,
"e": 8950,
"s": 8943,
"text": " Print"
},
{
"code": null,
"e": 8961,
"s": 8950,
"text": " Add Notes"
}
] |
Materialize CSS - Modals - GeeksforGeeks | 09 Sep, 2020
Materialize CSS uses modal component for creating dialog boxes, confirmation messages or presenting important content to the viewers where underlying content becomes inactive until the modal window is closed.
In order for the modal to work, add the modal Id to the link of the trigger and include the reference materialize.min.js along with jQuery on the web page. To add a “close” button, add the class modal-close to your button.
Types of Modals:
Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal"> <div class="modal-content"> <h4>Demo of Simple Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn green lighten-1"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>Output:Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body> <div class="container center"> <div class="card-panel"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal-fixed-footer"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal-fixed-footer" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Modal with Fixed Footer</h4> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn green darken-1"> Agree </a> <a href="#!" class="modal-action modal-close btn red darken-1"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container. Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal bottom-sheet"> <div class="modal-content"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class="modal-footer"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn red"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:
Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal"> <div class="modal-content"> <h4>Demo of Simple Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn green lighten-1"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>Output:
Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used.
Example:
HTML
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal"> <div class="modal-content"> <h4>Demo of Simple Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn green lighten-1"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>
Output:
Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body> <div class="container center"> <div class="card-panel"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal-fixed-footer"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal-fixed-footer" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Modal with Fixed Footer</h4> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn green darken-1"> Agree </a> <a href="#!" class="modal-action modal-close btn red darken-1"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:
Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element.
Example:
HTML
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src= "https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body> <div class="container center"> <div class="card-panel"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal-fixed-footer"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal-fixed-footer" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Modal with Fixed Footer</h4> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class="center"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close btn green darken-1"> Agree </a> <a href="#!" class="modal-action modal-close btn red darken-1"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html>
Output:
Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container. Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal bottom-sheet"> <div class="modal-content"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class="modal-footer"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn red"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:
Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container.
Example:
HTML
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"> </script></head> <body class="container "> <div class="card-panel center"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class="waves-effect waves-light btn green darken-1 modal-trigger" href="#demo-modal"> Click Here! </a> <!-- Modal Structure --> <div id="demo-modal" class="modal bottom-sheet"> <div class="modal-content"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class="red-text"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class="modal-footer"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn red"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html>
Output:
Materialize-CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 25585,
"s": 25376,
"text": "Materialize CSS uses modal component for creating dialog boxes, confirmation messages or presenting important content to the viewers where underlying content becomes inactive until the modal window is closed."
},
{
"code": null,
"e": 25808,
"s": 25585,
"text": "In order for the modal to work, add the modal Id to the link of the trigger and include the reference materialize.min.js along with jQuery on the web page. To add a “close” button, add the class modal-close to your button."
},
{
"code": null,
"e": 25825,
"s": 25808,
"text": "Types of Modals:"
},
{
"code": null,
"e": 33544,
"s": 25825,
"text": "Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal\"> <div class=\"modal-content\"> <h4>Demo of Simple Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close waves-effect waves-green btn green lighten-1\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>Output:Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body> <div class=\"container center\"> <div class=\"card-panel\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal-fixed-footer\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal-fixed-footer\" class=\"modal modal-fixed-footer\"> <div class=\"modal-content\"> <h4>Modal with Fixed Footer</h4> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close btn green darken-1\"> Agree </a> <a href=\"#!\" class=\"modal-action modal-close btn red darken-1\"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container. Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal bottom-sheet\"> <div class=\"modal-content\"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn red\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:"
},
{
"code": null,
"e": 35795,
"s": 33544,
"text": "Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal\"> <div class=\"modal-content\"> <h4>Demo of Simple Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close waves-effect waves-green btn green lighten-1\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>Output:"
},
{
"code": null,
"e": 35992,
"s": 35795,
"text": "Basic Modal: The basic modal consist of content and footer. The modal-content class is referred to the “main” div and the modal-footer class in another “div” tag where the “action” button is used."
},
{
"code": null,
"e": 36001,
"s": 35992,
"text": "Example:"
},
{
"code": null,
"e": 36006,
"s": 36001,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal\"> <div class=\"modal-content\"> <h4>Demo of Simple Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write operating system. The main features of C language include low-level access to memory, simple set of keywords, and clean style, these features make C language suitable for system programming like operating system or compiler development. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close waves-effect waves-green btn green lighten-1\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); } ) </script></body> </html>",
"e": 38038,
"s": 36006,
"text": null
},
{
"code": null,
"e": 38046,
"s": 38038,
"text": "Output:"
},
{
"code": null,
"e": 41445,
"s": 38046,
"text": "Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element.Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body> <div class=\"container center\"> <div class=\"card-panel\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal-fixed-footer\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal-fixed-footer\" class=\"modal modal-fixed-footer\"> <div class=\"modal-content\"> <h4>Modal with Fixed Footer</h4> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close btn green darken-1\"> Agree </a> <a href=\"#!\" class=\"modal-action modal-close btn red darken-1\"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:"
},
{
"code": null,
"e": 41684,
"s": 41445,
"text": "Modal with Fixed Footer: If the content is large, then this type of modal is used. In this we can create “action” buttons that are fixed. For this, modal-fixed-footer class is used along with the modal class in the main container element."
},
{
"code": null,
"e": 41693,
"s": 41684,
"text": "Example:"
},
{
"code": null,
"e": 41698,
"s": 41693,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body> <div class=\"container center\"> <div class=\"card-panel\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal-fixed-footer\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal-fixed-footer\" class=\"modal modal-fixed-footer\"> <div class=\"modal-content\"> <h4>Modal with Fixed Footer</h4> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position<br> of each element by simply adding an offset to a base value,<br> i.e., the memory location of the first element of the array <br>(generally denoted by the name of the array).<br> </p> <p class=\"center\"> An array is a collection of items stored at contiguous memory locations.<br> The idea is to store multiple items of the same type together.<br> This makes it easier to calculate the position of each element <br> by simply adding an offset to a base value, i.e., the memory location of <br> the first element of the array (generally denoted by the name of the array).<br> </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\"modal-action modal-close btn green darken-1\"> Agree </a> <a href=\"#!\" class=\"modal-action modal-close btn red darken-1\"> Disagree </a> </div> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> ",
"e": 44836,
"s": 41698,
"text": null
},
{
"code": null,
"e": 44844,
"s": 44836,
"text": "Output:"
},
{
"code": null,
"e": 46915,
"s": 44844,
"text": "Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container. Example:HTMLHTML<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal bottom-sheet\"> <div class=\"modal-content\"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn red\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> Output:"
},
{
"code": null,
"e": 47237,
"s": 46915,
"text": "Bottom Sheet Modal: Modals can be displayed to the bottom of the user’s screen and not the middle. It is just like the normal modal that can be closed by clicking anywhere on the screen as well as using the button inside that modal. For this, bottom-sheet class is used along with the modal class in the <div> container. "
},
{
"code": null,
"e": 47246,
"s": 47237,
"text": "Example:"
},
{
"code": null,
"e": 47251,
"s": 47246,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js\"> </script></head> <body class=\"container \"> <div class=\"card-panel center\"> <h3>Geeks for Geeks</h3> <!-- Modal Trigger --> <a class=\"waves-effect waves-light btn green darken-1 modal-trigger\" href=\"#demo-modal\"> Click Here! </a> <!-- Modal Structure --> <div id=\"demo-modal\" class=\"modal bottom-sheet\"> <div class=\"modal-content\"> <h4>Demo of Bottom sheet Modal</h4> <p> <div class=\"red-text\"> Content of the modal goes here. <br> Type information here. <br> </div> An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. </p> </div> <div class=\"modal-footer\"> <a href=\"#!\" class=\" modal-action modal-close waves-effect waves-green btn red\"> Close </a> </div> </div> </div> <script> $(document).ready(function () { $('.modal').modal(); }) </script></body> </html> ",
"e": 48978,
"s": 47251,
"text": null
},
{
"code": null,
"e": 48986,
"s": 48978,
"text": "Output:"
},
{
"code": null,
"e": 49002,
"s": 48986,
"text": "Materialize-CSS"
},
{
"code": null,
"e": 49006,
"s": 49002,
"text": "CSS"
},
{
"code": null,
"e": 49023,
"s": 49006,
"text": "Web Technologies"
},
{
"code": null,
"e": 49121,
"s": 49023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49158,
"s": 49121,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 49187,
"s": 49158,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 49226,
"s": 49187,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 49268,
"s": 49226,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 49315,
"s": 49268,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 49357,
"s": 49315,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 49390,
"s": 49357,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 49433,
"s": 49390,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 49478,
"s": 49433,
"text": "Convert a string to an integer in JavaScript"
}
] |
How to get the title and full URL of a document in JavaScript? | Javascript HTML DOM has provided some basic methods to access and manipulate the HTML data. To find the title and URL of a document, javascript has provided document.title and document.URL respectively. Let's discuss them individually.
To get the title of a document javascript HTML DOM has provided document.title method.
In the following example, the title of the document is found out and displayed as shown in the output.
Live Demo
<html>
<head>
<title>Tutorix</title>
</head>
<body>
<script>
document.write("The title of the document is" +" "+ document.title);
</script>
</body>
</html>
Tutorix
To get the URL of a document javascript HTML DOM has provided document.URL method.
In the following example, the URL of the document is found out and displayed in the output.
Live Demo
<html>
<body>
<script>
document.write("The URL of the document is:" + " " +document.URL)
</script>
</body>
</html>
The URL of the document is: https://www.tutorialspoint.com/cg/assets/ovPEzF.php | [
{
"code": null,
"e": 1298,
"s": 1062,
"text": "Javascript HTML DOM has provided some basic methods to access and manipulate the HTML data. To find the title and URL of a document, javascript has provided document.title and document.URL respectively. Let's discuss them individually."
},
{
"code": null,
"e": 1386,
"s": 1298,
"text": "To get the title of a document javascript HTML DOM has provided document.title method. "
},
{
"code": null,
"e": 1490,
"s": 1386,
"text": " In the following example, the title of the document is found out and displayed as shown in the output."
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "Live Demo"
},
{
"code": null,
"e": 1662,
"s": 1500,
"text": "<html>\n<head>\n <title>Tutorix</title>\n</head>\n<body>\n<script>\n document.write(\"The title of the document is\" +\" \"+ document.title);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1670,
"s": 1662,
"text": "Tutorix"
},
{
"code": null,
"e": 1753,
"s": 1670,
"text": "To get the URL of a document javascript HTML DOM has provided document.URL method."
},
{
"code": null,
"e": 1846,
"s": 1753,
"text": " In the following example, the URL of the document is found out and displayed in the output."
},
{
"code": null,
"e": 1856,
"s": 1846,
"text": "Live Demo"
},
{
"code": null,
"e": 1974,
"s": 1856,
"text": "<html>\n<body>\n<script>\n document.write(\"The URL of the document is:\" + \" \" +document.URL)\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2054,
"s": 1974,
"text": "The URL of the document is: https://www.tutorialspoint.com/cg/assets/ovPEzF.php"
}
] |
Forecasting using Granger’s Causality and Vector Auto-regressive Model | by Sarit Maitra | Towards Data Science | FORECASTING of Gold and Oil have garnered major attention from academics, investors and Government agencies like. These two products are known for their substantial influence on global economy. I will show here, how to use Granger’s Causality Test to test the relationships of multiple variables in the time series and Vector Auto Regressive Model (VAR) to forecast the future Gold & Oil prices from the historical data of Gold prices, Silver prices, Crude Oil prices, Stock index , Interest Rate and USD rate.
The Gold prices are closely related with other commodities. A hike in Oil prices will have positive impact on Gold prices and vice versa. Historically, we have seen that, when there is a hike in equities, Gold prices goes down.
Time-series forecasting problem formulation
Uni-variate and multi-variate time series time-series forecasting
Apply VAR to this problem
Let’s understand how a multivariate time series is formulated. Below are the simple K-equations of multivariate time series where each equation is a lag of the other series. X is the exogenous series here. The objective is to see if the series is affected by its own past and also the past of the other series.
This kind of series allow us to model the dynamics of the series itself and also the interdependence of other series. We will explore this inter-dependence through Granger’s Causality Analysis.
Let’s load the data and do some analysis with visualization to know insights of the data. Exploratory data analysis is quite extensive in multivariate time series. I will cover some areas here to get insights of the data. However, it is advisable to conduct all statistical tests to ensure our clear understanding on data distribution.
Let’s fix the dates for all the series.
The NaN values in the data are filled with previous days data. After doing some necessary pre-processing, the dataset now clean for further analysis.
# Plotfig, axes = plt.subplots(nrows=3, ncols=2, dpi=120, figsize=(10,6))for i, ax in enumerate(axes.flatten()): data = dataset[dataset.columns[i]] ax.plot(data, color=’red’, linewidth=1) ax.set_title(dataset.columns[i]) ax.xaxis.set_ticks_position(‘none’) ax.yaxis.set_ticks_position(‘none’) ax.spines[“top”].set_alpha(0) ax.tick_params(labelsize=6)plt.tight_layout();
From the above plots, we can visible conclude that, all the series contain unit root with stochastic trend showing a systematic pattern that is unpredictable.
To extract maximum information from our data, it is important to have a normal or Gaussian distribution of the data. To check for that, we have done a normality test based on the Null and Alternate Hypothesis intuition.
stat,p = stats.normaltest(dataset.Gold)print("Statistics = %.3f, p=%.3f" % (stat,p))alpha = 0.05if p> alpha:print('Data looks Gaussian (fail to reject null hypothesis)')else:print('Data looks non-Gaussian (reject null hypothesis')output: Statistics = 658.293, p=0.000 Data looks Gaussian (reject null hypothesis
These two distributions give us some intuition about the distribution of our data. The kurtosis of this dataset is -0.95. Since this value is less than 0, it is considered to be a light-tailed dataset. It has as much data in each tail as it does in the peak. Moderate skewness refers to the value between -1 and -0.5 or 0.5 and 1.
plt.figure(figsize=(14,6))plt.subplot(1,2,1)dataset['Gold'].hist(bins=50)plt.title('Gold')plt.subplot(1,2,2)stats.probplot(dataset['Gold'], plot=plt);dataset.Gold.describe().T
Normal probability plot also shows the data is far from normally distributed.
Auto-correlation or serial correlation can be a significant problem in analyzing historical data if we do not know how to look out for it.
# plots the autocorrelation plots for each stock's price at 50 lagsfor i in dataset: plt_acf(dataset[i], lags = 50) plt.title('ACF for %s' % i) plt.show()
We see here from the above plots, the auto-correlation of +1 which represents a perfect positive correlation which means, an increase seen in one time series leads to a proportionate increase in the other time series. We definitely need to apply transformation and neutralize this to make the series stationary. It measures linear relationships; even if the auto-correlation is minuscule, there may still be a nonlinear relationship between a time series and a lagged version of itself.
The VAR model will be fitted on X_train and then used to forecast the next 15 observations. These forecasts will be compared against the actual present in test data.
n_obs=15X_train, X_test = dataset[0:-n_obs], dataset[-n_obs:]print(X_train.shape, X_test.shape)(5114, 6) (15, 6)
Applying first differencing on training set to make all the series stationary. However, this is an iterative process where we after first differencing, the series may still be non-stationary. We shall have to apply second difference or log transformation to standardize the series in such cases.
def augmented_dickey_fuller_statistics(time_series): result = adfuller(time_series.values) print('ADF Statistic: %f' % result[0]) print('p-value: %f' % result[1]) print('Critical Values:') for key, value in result[4].items(): print('\t%s: %.3f' % (key, value))print('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Oil'])print('Augmented Dickey-Fuller Test: Interest_rate Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Interest_rate'])print('Augmented Dickey-Fuller Test: Stock_Index Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Stock_Index'])print('Augmented Dickey-Fuller Test: USD_Index Time Series')augmented_dickey_fuller_statistics(X_train_transformed['USD_Index'])
fig, axes = plt.subplots(nrows=3, ncols=2, dpi=120, figsize=(10,6))for i, ax in enumerate(axes.flatten()):d = X_train_transformed[X_train_transformed.columns[i]]ax.plot(d, color='red', linewidth=1)# Decorationsax.set_title(dataset.columns[i])ax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none')ax.spines['top'].set_alpha(0)ax.tick_params(labelsize=6)plt.tight_layout();
The formal definition of Granger causality can be explained as, whether past values of x aid in the prediction of yt, conditional on having already accounted for the effects on yt of past values of y (and perhaps of past values of other variables). If they do, the x is said to “Granger cause” y. So, the basis behind VAR is that each of the time series in the system influences each other.
Granger’s causality Tests the null hypothesis that the coefficients of past values in the regression equation is zero. So, if the p-value obtained from the test is lesser than the significance level of 0.05, then, you can safely reject the null hypothesis. This has been performed on original data-set.
Below piece of code taken from stackoverflow.
maxlag=12test = 'ssr-chi2test'def grangers_causality_matrix(X_train, variables, test = 'ssr_chi2test', verbose=False):dataset = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)for c in dataset.columns:for r in dataset.index:test_result = grangercausalitytests(X_train[[r,c]], maxlag=maxlag, verbose=False)p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')min_p_value = np.min(p_values)dataset.loc[r,c] = min_p_valuedataset.columns = [var + '_x' for var in variables]dataset.index = [var + '_y' for var in variables]return datasetgrangers_causality_matrix(dataset, variables = dataset.columns)
The row are the response (y) and the columns are the predictor series (x).
If we take the value 0.0000 in (row 1, column 2), it refers to the p-value of the Granger’s Causality test for Silver_x causing Gold_y. The 0.0000 in (row 2, column 1) refers to the p-value of Gold_y causing Silver_x and so on.
We can see that, in the case of Interest and USD variables, we cannot reject null hypothesis e.g. USD & Silver, USD & Oil. Our variables of interest are Gold and Oil here. So, for Gold, all the variables cause but for USD doesn’t causes any effect on Oil.
So, looking at the p-Values, we can assume that, except USD, all the other variables (time series) in the system are interchangeably causing each other. This justifies the VAR modeling approach for this system of multi time-series to forecast.
VAR requires stationarity of the series which means the mean to the series do not change over time (we can find this out from the plot drawn next to Augmented Dickey-Fuller Test).
Let’s understand the mathematical intuition of VAR model.
Here each series is modeled by it’s own lag and other series' lag. y{1,t-1, y{2,t-1}.... are the lag of time series y1,y2,.... respectively. The above equations are referred to as a VAR (1) model, because, each equation is of order 1, that is, it contains up to one lag of each of the predictors (y1, y2, .....). Since the y terms in the equations are interrelated, the y’s are considered as endogenous variables, rather than as exogenous predictors. To thwart the issue of structural instability, the VAR framework was utilized choosing the lag length according to AIC.
So, I will fit the VAR model on training set and then used the fitted model to forecast the next 15 observations. These forecasts will be compared against the actual present in test data. I have taken the maximum lag (15) to identify the required lags for VAR model.
mod = smt.VAR(X_train_transformed)res = mod.fit(maxlags=15, ic='aic')print(res.summary())
The biggest correlations are 0.38 (Silver & Gold) and -0.19 (Oil & USD); however, there are small enough to ignore in this case.
Residual plot looks normal with constant mean throughout apart from some large fluctuation during 2009, 2011, 2014 etc.
y_fitted = res.fittedvaluesplt.figure(figsize = (15,5))plt.plot(residuals, label='resid')plt.plot(y_fitted, label='VAR prediction')plt.xlabel('Date')plt.xticks(rotation=45)plt.ylabel('Residuals')plt.grid(True)
Durbin-Watson Statistic is related to related to auto correlation.
The Durbin-Watson statistic will always have a value between 0 and 4. A value of 2.0 means that there is no auto-correlation detected in the sample. Values from 0 to less than 2 indicate positive auto-correlation and values from 2 to 4 indicate negative auto-correlation. A rule of thumb is that test statistic values in the range of 1.5 to 2.5 are relatively normal. Any value outside this range could be a cause for concern.
A stock price displaying positive auto-correlation would indicate that the price yesterday has a positive correlation on the price today — so if the stock fell yesterday, it is also likely that it falls today. A stock that has a negative auto-correlation, on the other hand, has a negative influence on itself over time — so that if it fell yesterday, there is a greater likelihood it will rise today.
There is no auto-correlation (2.0) exist; so, we can proceed with the forecast.
In order to forecast, the VAR model expects up to the lag order number of observations from the past data. This is because, the terms in the VAR model are essentially the lags of the various time series in the data-set, so we need to provide as many of the previous values as indicated by the lag order used by the model.
# Get the lag orderlag_order = res.k_arprint(lag_order)# Input data for forecastinginput_data = X_train_transformed.values[-lag_order:]print(input_data)# forecastingpred = res.forecast(y=input_data, steps=n_obs)pred = (pd.DataFrame(pred, index=X_test.index, columns=X_test.columns + '_pred'))print(pred)
The forecasts are generated but it is on the scale of the training data used by the model. So, to bring it back up to its original scale, we need to de-difference it.
The way to convert the differencing is to add these differences consecutively to the base number. An easy way to do it is to first determine the cumulative sum at index and then add it to the base number.
This process can be reversed by adding the observation at the prior time step to the difference value. inverted(ts) = differenced(ts) + observation(ts-1)
# inverting transformationdef invert_transformation(X_train, pred):forecast = pred.copy()columns = X_train.columnsfor col in columns:forecast[str(col)+'_pred'] = X_train[col].iloc[-1] + forecast[str(col)+'_pred'].cumsum()return forecastoutput = invert_transformation(X_train, pred)#combining predicted and real data setcombine = pd.concat([output['Gold_pred'], X_test['Gold']], axis=1)combine['accuracy'] = round(combine.apply(lambda row: row.Gold_pred /row.Gold *100, axis = 1),2)combine['accuracy'] = pd.Series(["{0:.2f}%".format(val) for val in combine['accuracy']],index = combine.index)combine = combine.round(decimals=2)combine = combine.reset_index()combine = combine.sort_values(by='Date', ascending=False)
To evaluate the forecasts, a comprehensive set of metrics, such as the MAPE, ME, MAE, MPE and RMSE can be computed. We have computed some of these as below.
#Forecast biasforecast_errors = [combine['Gold'][i]- combine['Gold_pred'][i] for i in range(len(combine['Gold']))]bias = sum(forecast_errors) * 1.0/len(combine['Gold'])print('Bias: %f' % bias)print('Mean absolute error:', mean_absolute_error(combine['Gold'].values, combine['Gold_pred'].values))print('Mean squared error:', mean_squared_error(combine['Gold'].values, combine['Gold_pred'].values))print('Root mean squared error:', sqrt(mean_squared_error(combine['Gold'].values, combine['Gold_pred'].values)))
Mean absolute error tells us how big of an error we can expect from the forecast on average. Our error rates are quite low here indicating we have the right fit of the model.
The VAR model is a popular tool for the purpose of predicting joint dynamics of multiple time series based on linear functions of past observations. More analysis e.g. impulse response (IRF) and forecast error variance decomposition (FEVD) can also be done along-with VAR to for assessing the impacts of shock from one asset on another to assess the impacts of shock from one asset on another. However, I will keep this simple here for easy understanding. In real-life business case, we should do multiple models with different approach to do the comparative analysis before zeroed down on one or a hybrid model.
I can be connected here.
Notice: The programs described here are experimental and should be used with caution. All such use at your own risk. | [
{
"code": null,
"e": 557,
"s": 46,
"text": "FORECASTING of Gold and Oil have garnered major attention from academics, investors and Government agencies like. These two products are known for their substantial influence on global economy. I will show here, how to use Granger’s Causality Test to test the relationships of multiple variables in the time series and Vector Auto Regressive Model (VAR) to forecast the future Gold & Oil prices from the historical data of Gold prices, Silver prices, Crude Oil prices, Stock index , Interest Rate and USD rate."
},
{
"code": null,
"e": 785,
"s": 557,
"text": "The Gold prices are closely related with other commodities. A hike in Oil prices will have positive impact on Gold prices and vice versa. Historically, we have seen that, when there is a hike in equities, Gold prices goes down."
},
{
"code": null,
"e": 829,
"s": 785,
"text": "Time-series forecasting problem formulation"
},
{
"code": null,
"e": 895,
"s": 829,
"text": "Uni-variate and multi-variate time series time-series forecasting"
},
{
"code": null,
"e": 921,
"s": 895,
"text": "Apply VAR to this problem"
},
{
"code": null,
"e": 1232,
"s": 921,
"text": "Let’s understand how a multivariate time series is formulated. Below are the simple K-equations of multivariate time series where each equation is a lag of the other series. X is the exogenous series here. The objective is to see if the series is affected by its own past and also the past of the other series."
},
{
"code": null,
"e": 1426,
"s": 1232,
"text": "This kind of series allow us to model the dynamics of the series itself and also the interdependence of other series. We will explore this inter-dependence through Granger’s Causality Analysis."
},
{
"code": null,
"e": 1762,
"s": 1426,
"text": "Let’s load the data and do some analysis with visualization to know insights of the data. Exploratory data analysis is quite extensive in multivariate time series. I will cover some areas here to get insights of the data. However, it is advisable to conduct all statistical tests to ensure our clear understanding on data distribution."
},
{
"code": null,
"e": 1802,
"s": 1762,
"text": "Let’s fix the dates for all the series."
},
{
"code": null,
"e": 1952,
"s": 1802,
"text": "The NaN values in the data are filled with previous days data. After doing some necessary pre-processing, the dataset now clean for further analysis."
},
{
"code": null,
"e": 2322,
"s": 1952,
"text": "# Plotfig, axes = plt.subplots(nrows=3, ncols=2, dpi=120, figsize=(10,6))for i, ax in enumerate(axes.flatten()): data = dataset[dataset.columns[i]] ax.plot(data, color=’red’, linewidth=1) ax.set_title(dataset.columns[i]) ax.xaxis.set_ticks_position(‘none’) ax.yaxis.set_ticks_position(‘none’) ax.spines[“top”].set_alpha(0) ax.tick_params(labelsize=6)plt.tight_layout();"
},
{
"code": null,
"e": 2481,
"s": 2322,
"text": "From the above plots, we can visible conclude that, all the series contain unit root with stochastic trend showing a systematic pattern that is unpredictable."
},
{
"code": null,
"e": 2701,
"s": 2481,
"text": "To extract maximum information from our data, it is important to have a normal or Gaussian distribution of the data. To check for that, we have done a normality test based on the Null and Alternate Hypothesis intuition."
},
{
"code": null,
"e": 3013,
"s": 2701,
"text": "stat,p = stats.normaltest(dataset.Gold)print(\"Statistics = %.3f, p=%.3f\" % (stat,p))alpha = 0.05if p> alpha:print('Data looks Gaussian (fail to reject null hypothesis)')else:print('Data looks non-Gaussian (reject null hypothesis')output: Statistics = 658.293, p=0.000 Data looks Gaussian (reject null hypothesis"
},
{
"code": null,
"e": 3344,
"s": 3013,
"text": "These two distributions give us some intuition about the distribution of our data. The kurtosis of this dataset is -0.95. Since this value is less than 0, it is considered to be a light-tailed dataset. It has as much data in each tail as it does in the peak. Moderate skewness refers to the value between -1 and -0.5 or 0.5 and 1."
},
{
"code": null,
"e": 3520,
"s": 3344,
"text": "plt.figure(figsize=(14,6))plt.subplot(1,2,1)dataset['Gold'].hist(bins=50)plt.title('Gold')plt.subplot(1,2,2)stats.probplot(dataset['Gold'], plot=plt);dataset.Gold.describe().T"
},
{
"code": null,
"e": 3598,
"s": 3520,
"text": "Normal probability plot also shows the data is far from normally distributed."
},
{
"code": null,
"e": 3737,
"s": 3598,
"text": "Auto-correlation or serial correlation can be a significant problem in analyzing historical data if we do not know how to look out for it."
},
{
"code": null,
"e": 3895,
"s": 3737,
"text": "# plots the autocorrelation plots for each stock's price at 50 lagsfor i in dataset: plt_acf(dataset[i], lags = 50) plt.title('ACF for %s' % i) plt.show()"
},
{
"code": null,
"e": 4382,
"s": 3895,
"text": "We see here from the above plots, the auto-correlation of +1 which represents a perfect positive correlation which means, an increase seen in one time series leads to a proportionate increase in the other time series. We definitely need to apply transformation and neutralize this to make the series stationary. It measures linear relationships; even if the auto-correlation is minuscule, there may still be a nonlinear relationship between a time series and a lagged version of itself."
},
{
"code": null,
"e": 4548,
"s": 4382,
"text": "The VAR model will be fitted on X_train and then used to forecast the next 15 observations. These forecasts will be compared against the actual present in test data."
},
{
"code": null,
"e": 4661,
"s": 4548,
"text": "n_obs=15X_train, X_test = dataset[0:-n_obs], dataset[-n_obs:]print(X_train.shape, X_test.shape)(5114, 6) (15, 6)"
},
{
"code": null,
"e": 4957,
"s": 4661,
"text": "Applying first differencing on training set to make all the series stationary. However, this is an iterative process where we after first differencing, the series may still be non-stationary. We shall have to apply second difference or log transformation to standardize the series in such cases."
},
{
"code": null,
"e": 5996,
"s": 4957,
"text": "def augmented_dickey_fuller_statistics(time_series): result = adfuller(time_series.values) print('ADF Statistic: %f' % result[0]) print('p-value: %f' % result[1]) print('Critical Values:') for key, value in result[4].items(): print('\\t%s: %.3f' % (key, value))print('Augmented Dickey-Fuller Test: Gold Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Gold'])print('Augmented Dickey-Fuller Test: Silver Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Silver'])print('Augmented Dickey-Fuller Test: Oil Price Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Oil'])print('Augmented Dickey-Fuller Test: Interest_rate Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Interest_rate'])print('Augmented Dickey-Fuller Test: Stock_Index Time Series')augmented_dickey_fuller_statistics(X_train_transformed['Stock_Index'])print('Augmented Dickey-Fuller Test: USD_Index Time Series')augmented_dickey_fuller_statistics(X_train_transformed['USD_Index'])"
},
{
"code": null,
"e": 6384,
"s": 5996,
"text": "fig, axes = plt.subplots(nrows=3, ncols=2, dpi=120, figsize=(10,6))for i, ax in enumerate(axes.flatten()):d = X_train_transformed[X_train_transformed.columns[i]]ax.plot(d, color='red', linewidth=1)# Decorationsax.set_title(dataset.columns[i])ax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none')ax.spines['top'].set_alpha(0)ax.tick_params(labelsize=6)plt.tight_layout();"
},
{
"code": null,
"e": 6775,
"s": 6384,
"text": "The formal definition of Granger causality can be explained as, whether past values of x aid in the prediction of yt, conditional on having already accounted for the effects on yt of past values of y (and perhaps of past values of other variables). If they do, the x is said to “Granger cause” y. So, the basis behind VAR is that each of the time series in the system influences each other."
},
{
"code": null,
"e": 7078,
"s": 6775,
"text": "Granger’s causality Tests the null hypothesis that the coefficients of past values in the regression equation is zero. So, if the p-value obtained from the test is lesser than the significance level of 0.05, then, you can safely reject the null hypothesis. This has been performed on original data-set."
},
{
"code": null,
"e": 7124,
"s": 7078,
"text": "Below piece of code taken from stackoverflow."
},
{
"code": null,
"e": 7845,
"s": 7124,
"text": "maxlag=12test = 'ssr-chi2test'def grangers_causality_matrix(X_train, variables, test = 'ssr_chi2test', verbose=False):dataset = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)for c in dataset.columns:for r in dataset.index:test_result = grangercausalitytests(X_train[[r,c]], maxlag=maxlag, verbose=False)p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')min_p_value = np.min(p_values)dataset.loc[r,c] = min_p_valuedataset.columns = [var + '_x' for var in variables]dataset.index = [var + '_y' for var in variables]return datasetgrangers_causality_matrix(dataset, variables = dataset.columns)"
},
{
"code": null,
"e": 7920,
"s": 7845,
"text": "The row are the response (y) and the columns are the predictor series (x)."
},
{
"code": null,
"e": 8148,
"s": 7920,
"text": "If we take the value 0.0000 in (row 1, column 2), it refers to the p-value of the Granger’s Causality test for Silver_x causing Gold_y. The 0.0000 in (row 2, column 1) refers to the p-value of Gold_y causing Silver_x and so on."
},
{
"code": null,
"e": 8404,
"s": 8148,
"text": "We can see that, in the case of Interest and USD variables, we cannot reject null hypothesis e.g. USD & Silver, USD & Oil. Our variables of interest are Gold and Oil here. So, for Gold, all the variables cause but for USD doesn’t causes any effect on Oil."
},
{
"code": null,
"e": 8648,
"s": 8404,
"text": "So, looking at the p-Values, we can assume that, except USD, all the other variables (time series) in the system are interchangeably causing each other. This justifies the VAR modeling approach for this system of multi time-series to forecast."
},
{
"code": null,
"e": 8828,
"s": 8648,
"text": "VAR requires stationarity of the series which means the mean to the series do not change over time (we can find this out from the plot drawn next to Augmented Dickey-Fuller Test)."
},
{
"code": null,
"e": 8886,
"s": 8828,
"text": "Let’s understand the mathematical intuition of VAR model."
},
{
"code": null,
"e": 9457,
"s": 8886,
"text": "Here each series is modeled by it’s own lag and other series' lag. y{1,t-1, y{2,t-1}.... are the lag of time series y1,y2,.... respectively. The above equations are referred to as a VAR (1) model, because, each equation is of order 1, that is, it contains up to one lag of each of the predictors (y1, y2, .....). Since the y terms in the equations are interrelated, the y’s are considered as endogenous variables, rather than as exogenous predictors. To thwart the issue of structural instability, the VAR framework was utilized choosing the lag length according to AIC."
},
{
"code": null,
"e": 9724,
"s": 9457,
"text": "So, I will fit the VAR model on training set and then used the fitted model to forecast the next 15 observations. These forecasts will be compared against the actual present in test data. I have taken the maximum lag (15) to identify the required lags for VAR model."
},
{
"code": null,
"e": 9814,
"s": 9724,
"text": "mod = smt.VAR(X_train_transformed)res = mod.fit(maxlags=15, ic='aic')print(res.summary())"
},
{
"code": null,
"e": 9943,
"s": 9814,
"text": "The biggest correlations are 0.38 (Silver & Gold) and -0.19 (Oil & USD); however, there are small enough to ignore in this case."
},
{
"code": null,
"e": 10063,
"s": 9943,
"text": "Residual plot looks normal with constant mean throughout apart from some large fluctuation during 2009, 2011, 2014 etc."
},
{
"code": null,
"e": 10273,
"s": 10063,
"text": "y_fitted = res.fittedvaluesplt.figure(figsize = (15,5))plt.plot(residuals, label='resid')plt.plot(y_fitted, label='VAR prediction')plt.xlabel('Date')plt.xticks(rotation=45)plt.ylabel('Residuals')plt.grid(True)"
},
{
"code": null,
"e": 10340,
"s": 10273,
"text": "Durbin-Watson Statistic is related to related to auto correlation."
},
{
"code": null,
"e": 10767,
"s": 10340,
"text": "The Durbin-Watson statistic will always have a value between 0 and 4. A value of 2.0 means that there is no auto-correlation detected in the sample. Values from 0 to less than 2 indicate positive auto-correlation and values from 2 to 4 indicate negative auto-correlation. A rule of thumb is that test statistic values in the range of 1.5 to 2.5 are relatively normal. Any value outside this range could be a cause for concern."
},
{
"code": null,
"e": 11169,
"s": 10767,
"text": "A stock price displaying positive auto-correlation would indicate that the price yesterday has a positive correlation on the price today — so if the stock fell yesterday, it is also likely that it falls today. A stock that has a negative auto-correlation, on the other hand, has a negative influence on itself over time — so that if it fell yesterday, there is a greater likelihood it will rise today."
},
{
"code": null,
"e": 11249,
"s": 11169,
"text": "There is no auto-correlation (2.0) exist; so, we can proceed with the forecast."
},
{
"code": null,
"e": 11571,
"s": 11249,
"text": "In order to forecast, the VAR model expects up to the lag order number of observations from the past data. This is because, the terms in the VAR model are essentially the lags of the various time series in the data-set, so we need to provide as many of the previous values as indicated by the lag order used by the model."
},
{
"code": null,
"e": 11875,
"s": 11571,
"text": "# Get the lag orderlag_order = res.k_arprint(lag_order)# Input data for forecastinginput_data = X_train_transformed.values[-lag_order:]print(input_data)# forecastingpred = res.forecast(y=input_data, steps=n_obs)pred = (pd.DataFrame(pred, index=X_test.index, columns=X_test.columns + '_pred'))print(pred)"
},
{
"code": null,
"e": 12042,
"s": 11875,
"text": "The forecasts are generated but it is on the scale of the training data used by the model. So, to bring it back up to its original scale, we need to de-difference it."
},
{
"code": null,
"e": 12247,
"s": 12042,
"text": "The way to convert the differencing is to add these differences consecutively to the base number. An easy way to do it is to first determine the cumulative sum at index and then add it to the base number."
},
{
"code": null,
"e": 12401,
"s": 12247,
"text": "This process can be reversed by adding the observation at the prior time step to the difference value. inverted(ts) = differenced(ts) + observation(ts-1)"
},
{
"code": null,
"e": 13116,
"s": 12401,
"text": "# inverting transformationdef invert_transformation(X_train, pred):forecast = pred.copy()columns = X_train.columnsfor col in columns:forecast[str(col)+'_pred'] = X_train[col].iloc[-1] + forecast[str(col)+'_pred'].cumsum()return forecastoutput = invert_transformation(X_train, pred)#combining predicted and real data setcombine = pd.concat([output['Gold_pred'], X_test['Gold']], axis=1)combine['accuracy'] = round(combine.apply(lambda row: row.Gold_pred /row.Gold *100, axis = 1),2)combine['accuracy'] = pd.Series([\"{0:.2f}%\".format(val) for val in combine['accuracy']],index = combine.index)combine = combine.round(decimals=2)combine = combine.reset_index()combine = combine.sort_values(by='Date', ascending=False)"
},
{
"code": null,
"e": 13273,
"s": 13116,
"text": "To evaluate the forecasts, a comprehensive set of metrics, such as the MAPE, ME, MAE, MPE and RMSE can be computed. We have computed some of these as below."
},
{
"code": null,
"e": 13782,
"s": 13273,
"text": "#Forecast biasforecast_errors = [combine['Gold'][i]- combine['Gold_pred'][i] for i in range(len(combine['Gold']))]bias = sum(forecast_errors) * 1.0/len(combine['Gold'])print('Bias: %f' % bias)print('Mean absolute error:', mean_absolute_error(combine['Gold'].values, combine['Gold_pred'].values))print('Mean squared error:', mean_squared_error(combine['Gold'].values, combine['Gold_pred'].values))print('Root mean squared error:', sqrt(mean_squared_error(combine['Gold'].values, combine['Gold_pred'].values)))"
},
{
"code": null,
"e": 13957,
"s": 13782,
"text": "Mean absolute error tells us how big of an error we can expect from the forecast on average. Our error rates are quite low here indicating we have the right fit of the model."
},
{
"code": null,
"e": 14570,
"s": 13957,
"text": "The VAR model is a popular tool for the purpose of predicting joint dynamics of multiple time series based on linear functions of past observations. More analysis e.g. impulse response (IRF) and forecast error variance decomposition (FEVD) can also be done along-with VAR to for assessing the impacts of shock from one asset on another to assess the impacts of shock from one asset on another. However, I will keep this simple here for easy understanding. In real-life business case, we should do multiple models with different approach to do the comparative analysis before zeroed down on one or a hybrid model."
},
{
"code": null,
"e": 14595,
"s": 14570,
"text": "I can be connected here."
}
] |
Java Program for focal length of a spherical mirror | Following is the Java code for focal length of a spherical mirror −
Live Demo
import java.util.*;
import java.lang.*;
public class Demo{
public static float concave_f_len(float val){
return val/2 ;
}
public static float convex_f_len(float val){
return - (val/2 ) ;
}
public static void main(String argc[]){
float val = 55 ;
System.out.print("The focal length of spherical mirror (concave) is : " + concave_f_len(val) + "units\n");
System.out.println("The focal length of spherical mirror (convex) is : "+ convex_f_len(val) + "units");
}
}
The focal length of spherical mirror (concave) is : 27.5units
The focal length of spherical mirror (convex) is : -27.5 units
A class named Demo defines a static function that returns a float value. It takes a float value as the parameter and divides it by 2 and returns the result. Similarly, another static function takes in a float value as parameter and divides by 2 and negates the value and returns the output. In the main function, a value for the float value that was passed to both the static functions is defined. Next, the function is called and relevant message is displayed on the console. | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Following is the Java code for focal length of a spherical mirror −"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": " Live Demo"
},
{
"code": null,
"e": 1650,
"s": 1141,
"text": "import java.util.*;\nimport java.lang.*;\npublic class Demo{\n public static float concave_f_len(float val){\n return val/2 ;\n }\n public static float convex_f_len(float val){\n return - (val/2 ) ;\n }\n public static void main(String argc[]){\n float val = 55 ;\n System.out.print(\"The focal length of spherical mirror (concave) is : \" + concave_f_len(val) + \"units\\n\");\n System.out.println(\"The focal length of spherical mirror (convex) is : \"+ convex_f_len(val) + \"units\");\n }\n}"
},
{
"code": null,
"e": 1775,
"s": 1650,
"text": "The focal length of spherical mirror (concave) is : 27.5units\nThe focal length of spherical mirror (convex) is : -27.5 units"
},
{
"code": null,
"e": 2252,
"s": 1775,
"text": "A class named Demo defines a static function that returns a float value. It takes a float value as the parameter and divides it by 2 and returns the result. Similarly, another static function takes in a float value as parameter and divides by 2 and negates the value and returns the output. In the main function, a value for the float value that was passed to both the static functions is defined. Next, the function is called and relevant message is displayed on the console."
}
] |
Check whether a number has consecutive 0's in the given base or not - GeeksforGeeks | 09 Apr, 2021
Given a decimal number N, the task is to check if a number has consecutive zeroes or not after converting the number to its K-based notation.
Examples:
Input: N = 4, K = 2 Output: No 4 in base 2 is 100, As there are consecutive 2 thus the answer is No.
Input: N = 15, K = 8 Output: Yes 15 in base 8 is 17, As there are no consecutive 0 so the answer is Yes.
Approach: First convert the number N into base K and then simply check if the number has consecutive zeroes or not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to convert N into base Kint toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N/K; s = r * w + s; w *= 10; } return s; } // Function to check for consecutive 0bool check(int N){ // Flag to check if there are consecutive // zero or not bool fl = false; while (N != 0) { int r = N % 10; N = N/10; // If there are two consecutive zero // then returning False if (fl == true and r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true; } // We first convert to given base, then// check if the converted number has two// consecutive 0s or notvoid hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) cout<<"Yes"<<endl; else cout<<"No"<<endl;} // Driver codeint main(){int N = 15;int K = 8;hasConsecutiveZeroes(N, K); }// This code is contributed by// Surendra_Gangwar
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to convert N into base Kstatic int toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N / K; s = r * w + s; w *= 10; } return s; } // Function to check for consecutive 0static boolean check(int N){ // Flag to check if there are consecutive // zero or not boolean fl = false; while (N != 0) { int r = N % 10; N = N / 10; // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notstatic void hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) System.out.println("Yes"); else System.out.println("No");} // Driver codepublic static void main(String[] args){ int N = 15; int K = 8; hasConsecutiveZeroes(N, K);}} // This code is contributed by Princi Singh
# Python implementation of the above approach # We first convert to given base, then# check if the converted number has two# consecutive 0s or notdef hasConsecutiveZeroes(N, K): z = toK(N, K) if (check(z)): print("Yes") else: print("No") # Function to convert N into base Kdef toK(N, K): # Weight of each digit w = 1 s = 0 while (N != 0): r = N % K N = N//K s = r * w + s w* = 10 return s # Function to check for consecutive 0def check(N): # Flag to check if there are consecutive # zero or not fl = False while (N != 0): r = N % 10 N = N//10 # If there are two consecutive zero # then returning False if (fl == True and r == 0): return False if (r > 0): fl = False continue fl = True return True # Driver codeN, K = 15, 8hasConsecutiveZeroes(N, K)
// C# implementation of the above approachusing System; class GFG{ // Function to convert N into base Kstatic int toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N / K; s = r * w + s; w *= 10; } return s;} // Function to check for consecutive 0static Boolean check(int N){ // Flag to check if there are consecutive // zero or not Boolean fl = false; while (N != 0) { int r = N % 10; N = N / 10; // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notstatic void hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver codepublic static void Main(String[] args){ int N = 15; int K = 8; hasConsecutiveZeroes(N, K);}} // This code is contributed by 29AjayKumar
<?php// PHP implementation of the above approach // We first convert to given base,// then check if the converted number// has two consecutive 0s or notfunction hasConsecutiveZeroes($N, $K){ $z = toK($N, $K); if (check($z)) print("Yes"); else print("No");} // Function to convert N into base Kfunction toK($N, $K){ // Weight of each digit $w = 1; $s = 0; while ($N != 0) { $r = $N % $K; $N = (int)($N / $K); $s = $r * $w + $s; $w *= 10; } return $s;} // Function to check for consecutive 0function check($N){ // Flag to check if there are // consecutive zero or not $fl = false; while ($N != 0) { $r = $N % 10; $N = (int)($N / 10); // If there are two consecutive // zero then returning false if ($fl == true and $r == 0) return false; if ($r > 0) { $fl = false; continue; } $fl = true; } return true;} // Driver code$N = 15;$K = 8;hasConsecutiveZeroes($N, $K); // This code is contributed by mits?>
<script> // Javascript implementation of the above approach // Function to convert N into base Kfunction toK(N, K){ // Weight of each digit let w = 1; let s = 0; while (N != 0) { let r = N % K; N = parseInt(N / K); s = r * w + s; w *= 10; } return s;} // Function to check for consecutive 0function check(N){ // Flag to check if there are consecutive // zero or not let fl = false; while (N != 0) { let r = N % 10; N = parseInt(N/10); // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notfunction hasConsecutiveZeroes(N, K){ let z = toK(N, K); if (check(z)) document.write("Yes"); else document.write("No");} // Driver codelet N = 15;let K = 8; hasConsecutiveZeroes(N, K); // This code is contributed by souravmahato348 </script>
Yes
Mithun Kumar
SURENDRA_GANGWAR
princi singh
29AjayKumar
souravmahato348
base-conversion
Mathematical
Python Programs
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Prime Numbers
Program to find sum of elements in a given array
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": 25259,
"s": 25231,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25401,
"s": 25259,
"text": "Given a decimal number N, the task is to check if a number has consecutive zeroes or not after converting the number to its K-based notation."
},
{
"code": null,
"e": 25412,
"s": 25401,
"text": "Examples: "
},
{
"code": null,
"e": 25513,
"s": 25412,
"text": "Input: N = 4, K = 2 Output: No 4 in base 2 is 100, As there are consecutive 2 thus the answer is No."
},
{
"code": null,
"e": 25620,
"s": 25513,
"text": "Input: N = 15, K = 8 Output: Yes 15 in base 8 is 17, As there are no consecutive 0 so the answer is Yes. "
},
{
"code": null,
"e": 25736,
"s": 25620,
"text": "Approach: First convert the number N into base K and then simply check if the number has consecutive zeroes or not."
},
{
"code": null,
"e": 25789,
"s": 25736,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25793,
"s": 25789,
"text": "C++"
},
{
"code": null,
"e": 25798,
"s": 25793,
"text": "Java"
},
{
"code": null,
"e": 25806,
"s": 25798,
"text": "Python3"
},
{
"code": null,
"e": 25809,
"s": 25806,
"text": "C#"
},
{
"code": null,
"e": 25813,
"s": 25809,
"text": "PHP"
},
{
"code": null,
"e": 25824,
"s": 25813,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to convert N into base Kint toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N/K; s = r * w + s; w *= 10; } return s; } // Function to check for consecutive 0bool check(int N){ // Flag to check if there are consecutive // zero or not bool fl = false; while (N != 0) { int r = N % 10; N = N/10; // If there are two consecutive zero // then returning False if (fl == true and r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true; } // We first convert to given base, then// check if the converted number has two// consecutive 0s or notvoid hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) cout<<\"Yes\"<<endl; else cout<<\"No\"<<endl;} // Driver codeint main(){int N = 15;int K = 8;hasConsecutiveZeroes(N, K); }// This code is contributed by// Surendra_Gangwar",
"e": 26991,
"s": 25824,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to convert N into base Kstatic int toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N / K; s = r * w + s; w *= 10; } return s; } // Function to check for consecutive 0static boolean check(int N){ // Flag to check if there are consecutive // zero or not boolean fl = false; while (N != 0) { int r = N % 10; N = N / 10; // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notstatic void hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver codepublic static void main(String[] args){ int N = 15; int K = 8; hasConsecutiveZeroes(N, K);}} // This code is contributed by Princi Singh",
"e": 28209,
"s": 26991,
"text": null
},
{
"code": "# Python implementation of the above approach # We first convert to given base, then# check if the converted number has two# consecutive 0s or notdef hasConsecutiveZeroes(N, K): z = toK(N, K) if (check(z)): print(\"Yes\") else: print(\"No\") # Function to convert N into base Kdef toK(N, K): # Weight of each digit w = 1 s = 0 while (N != 0): r = N % K N = N//K s = r * w + s w* = 10 return s # Function to check for consecutive 0def check(N): # Flag to check if there are consecutive # zero or not fl = False while (N != 0): r = N % 10 N = N//10 # If there are two consecutive zero # then returning False if (fl == True and r == 0): return False if (r > 0): fl = False continue fl = True return True # Driver codeN, K = 15, 8hasConsecutiveZeroes(N, K)",
"e": 29124,
"s": 28209,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to convert N into base Kstatic int toK(int N, int K){ // Weight of each digit int w = 1; int s = 0; while (N != 0) { int r = N % K; N = N / K; s = r * w + s; w *= 10; } return s;} // Function to check for consecutive 0static Boolean check(int N){ // Flag to check if there are consecutive // zero or not Boolean fl = false; while (N != 0) { int r = N % 10; N = N / 10; // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notstatic void hasConsecutiveZeroes(int N, int K){ int z = toK(N, K); if (check(z)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver codepublic static void Main(String[] args){ int N = 15; int K = 8; hasConsecutiveZeroes(N, K);}} // This code is contributed by 29AjayKumar",
"e": 30330,
"s": 29124,
"text": null
},
{
"code": "<?php// PHP implementation of the above approach // We first convert to given base,// then check if the converted number// has two consecutive 0s or notfunction hasConsecutiveZeroes($N, $K){ $z = toK($N, $K); if (check($z)) print(\"Yes\"); else print(\"No\");} // Function to convert N into base Kfunction toK($N, $K){ // Weight of each digit $w = 1; $s = 0; while ($N != 0) { $r = $N % $K; $N = (int)($N / $K); $s = $r * $w + $s; $w *= 10; } return $s;} // Function to check for consecutive 0function check($N){ // Flag to check if there are // consecutive zero or not $fl = false; while ($N != 0) { $r = $N % 10; $N = (int)($N / 10); // If there are two consecutive // zero then returning false if ($fl == true and $r == 0) return false; if ($r > 0) { $fl = false; continue; } $fl = true; } return true;} // Driver code$N = 15;$K = 8;hasConsecutiveZeroes($N, $K); // This code is contributed by mits?>",
"e": 31420,
"s": 30330,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to convert N into base Kfunction toK(N, K){ // Weight of each digit let w = 1; let s = 0; while (N != 0) { let r = N % K; N = parseInt(N / K); s = r * w + s; w *= 10; } return s;} // Function to check for consecutive 0function check(N){ // Flag to check if there are consecutive // zero or not let fl = false; while (N != 0) { let r = N % 10; N = parseInt(N/10); // If there are two consecutive zero // then returning False if (fl == true && r == 0) return false; if (r > 0) { fl = false; continue; } fl = true; } return true;} // We first convert to given base, then// check if the converted number has two// consecutive 0s or notfunction hasConsecutiveZeroes(N, K){ let z = toK(N, K); if (check(z)) document.write(\"Yes\"); else document.write(\"No\");} // Driver codelet N = 15;let K = 8; hasConsecutiveZeroes(N, K); // This code is contributed by souravmahato348 </script>",
"e": 32573,
"s": 31420,
"text": null
},
{
"code": null,
"e": 32577,
"s": 32573,
"text": "Yes"
},
{
"code": null,
"e": 32592,
"s": 32579,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32609,
"s": 32592,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32622,
"s": 32609,
"text": "princi singh"
},
{
"code": null,
"e": 32634,
"s": 32622,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32650,
"s": 32634,
"text": "souravmahato348"
},
{
"code": null,
"e": 32666,
"s": 32650,
"text": "base-conversion"
},
{
"code": null,
"e": 32679,
"s": 32666,
"text": "Mathematical"
},
{
"code": null,
"e": 32695,
"s": 32679,
"text": "Python Programs"
},
{
"code": null,
"e": 32708,
"s": 32695,
"text": "Mathematical"
},
{
"code": null,
"e": 32806,
"s": 32708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32830,
"s": 32806,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32873,
"s": 32830,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32915,
"s": 32873,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32929,
"s": 32915,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32978,
"s": 32929,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33021,
"s": 32978,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 33043,
"s": 33021,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 33089,
"s": 33043,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 33128,
"s": 33089,
"text": "Python | Get dictionary keys as a list"
}
] |
Install Shapely on Windows. Simple instructions for installing... | by Dalya Gartzman | Towards Data Science | Shapely is a Python package full of wonderful possibilities for geometric stuff to do with your data.Though, if you are working on Windows OS, installing Shapely is not a trivial task.
Luckily, once you know the details, it’s not that hard.
Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type .Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 .pip install wheelGo here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .pip install <path-to-Downloads>\<filename_from_item_4> . For example in my case I enteredpip install C:\Users\Dalya\Downloads\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type .
Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 .
pip install wheel
Go here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
pip install <path-to-Downloads>\<filename_from_item_4> . For example in my case I enteredpip install C:\Users\Dalya\Downloads\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .
And that’s it!
Now this is really simple!For more information on why conda install shapely sometimes does not work, and why the first line is needed, go here.
conda config --add channels conda-forgeconda install shapely
And that’s it! | [
{
"code": null,
"e": 357,
"s": 172,
"text": "Shapely is a Python package full of wonderful possibilities for geometric stuff to do with your data.Though, if you are working on Windows OS, installing Shapely is not a trivial task."
},
{
"code": null,
"e": 413,
"s": 357,
"text": "Luckily, once you know the details, it’s not that hard."
},
{
"code": null,
"e": 1079,
"s": 413,
"text": "Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type .Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 .pip install wheelGo here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl .pip install <path-to-Downloads>\\<filename_from_item_4> . For example in my case I enteredpip install C:\\Users\\Dalya\\Downloads\\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl ."
},
{
"code": null,
"e": 1192,
"s": 1079,
"text": "Find out your whether you are using Windows 32-bit or 64-bit. Go to Settings => System => About => System Type ."
},
{
"code": null,
"e": 1378,
"s": 1192,
"text": "Find out your python version. Open Command prompt, enter python --version and remember the first two numbers. For example my version is Python 3.7.3 so I should remember the number 37 ."
},
{
"code": null,
"e": 1396,
"s": 1378,
"text": "pip install wheel"
},
{
"code": null,
"e": 1576,
"s": 1396,
"text": "Go here and download the wheel corresponding to items 1–2. For example, I have 64-bit OS and Python 3.7.3 so I need to download file Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl ."
},
{
"code": null,
"e": 1749,
"s": 1576,
"text": "pip install <path-to-Downloads>\\<filename_from_item_4> . For example in my case I enteredpip install C:\\Users\\Dalya\\Downloads\\Shapely-1.6.4.post2-cp37-cp37m-win_amd64.whl ."
},
{
"code": null,
"e": 1764,
"s": 1749,
"text": "And that’s it!"
},
{
"code": null,
"e": 1908,
"s": 1764,
"text": "Now this is really simple!For more information on why conda install shapely sometimes does not work, and why the first line is needed, go here."
},
{
"code": null,
"e": 1969,
"s": 1908,
"text": "conda config --add channels conda-forgeconda install shapely"
}
] |
base64.DecodeString() Function in Golang With Examples - GeeksforGeeks | 19 May, 2020
Go language provides inbuilt support for base64 encoding/decoding and has functions that could be used to perform operations on the given data using the base64 package. This package provides DecodeString() function which is used to decode a base64 string to its plaintext form. It supports decoding using both standard and URL compatible base64 standards.
Syntax:
func (enc *Encoding) DecodeString(s string) ([]byte, error)
The Encoding type used with the decoder has 4 variations:
StdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard.
RawStdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard, except that the padding characters are omitted.
URLEncoding: It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames.
RawURLEncoding:It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames, except that the padding characters are omitted.
Return Value: It returns the bytes represented by the given base64 string.
Below programs illustrate the DecodeString() function:
Example 1:
// Golang program to illustrate// the base64.DecodeString() Functionpackage main import ( "encoding/base64" "fmt") func main() { // taking a string givenString := "R2Vla3Nmb3JHZWVrcw==" // using the function decodedString, err := base64.StdEncoding.DecodeString(givenString) if err != nil { fmt.Println("Error Found:", err) return } fmt.Print("Decoded Bytes: ") fmt.Println(decodedString) fmt.Print("Decoded String: ") fmt.Println(string(decodedString))}
Output:
Decoded Bytes: [71 101 101 107 115 102 111 114 71 101 101 107 115]
Decoded String: GeeksforGeeks
Example 2:
// Golang program to illustrate// the base64.DecodeString() Functionpackage main import ( "encoding/base64" "fmt") func main() { // taking a string givenString := "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv" // using the function decodedString, err := base64.URLEncoding.DecodeString(givenString) if err != nil { fmt.Println("Error Found:", err) return } fmt.Print("Decoded Bytes: ") fmt.Println(decodedString) fmt.Print("Decoded String: ") fmt.Println(string(decodedString))}
Output:
Decoded Bytes: [104 116 116 112 115 58 47 47 119 119 119 46 103 101 101 107 115 102 111 114 103 101 101 107 115 46 111 114 103 47]Decoded String: https://www.geeksforgeeks.org/
Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Loops in Go Language
Anonymous function in Go Language
Structures in Golang
Strings in Golang
Time Durations in Golang
How to convert a string in uppercase in Golang?
Functions in Go Language | [
{
"code": null,
"e": 24380,
"s": 24352,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 24736,
"s": 24380,
"text": "Go language provides inbuilt support for base64 encoding/decoding and has functions that could be used to perform operations on the given data using the base64 package. This package provides DecodeString() function which is used to decode a base64 string to its plaintext form. It supports decoding using both standard and URL compatible base64 standards."
},
{
"code": null,
"e": 24744,
"s": 24736,
"text": "Syntax:"
},
{
"code": null,
"e": 24804,
"s": 24744,
"text": "func (enc *Encoding) DecodeString(s string) ([]byte, error)"
},
{
"code": null,
"e": 24862,
"s": 24804,
"text": "The Encoding type used with the decoder has 4 variations:"
},
{
"code": null,
"e": 24951,
"s": 24862,
"text": "StdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard."
},
{
"code": null,
"e": 25091,
"s": 24951,
"text": "RawStdEncoding: It is the standard encoding to be used as defined by the RFC 4648 standard, except that the padding characters are omitted."
},
{
"code": null,
"e": 25229,
"s": 25091,
"text": "URLEncoding: It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames."
},
{
"code": null,
"e": 25417,
"s": 25229,
"text": "RawURLEncoding:It is the URL encoding to be used as defined by the RFC 4648 standard. It is typically used for encoding URLs and filenames, except that the padding characters are omitted."
},
{
"code": null,
"e": 25492,
"s": 25417,
"text": "Return Value: It returns the bytes represented by the given base64 string."
},
{
"code": null,
"e": 25547,
"s": 25492,
"text": "Below programs illustrate the DecodeString() function:"
},
{
"code": null,
"e": 25558,
"s": 25547,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// the base64.DecodeString() Functionpackage main import ( \"encoding/base64\" \"fmt\") func main() { // taking a string givenString := \"R2Vla3Nmb3JHZWVrcw==\" // using the function decodedString, err := base64.StdEncoding.DecodeString(givenString) if err != nil { fmt.Println(\"Error Found:\", err) return } fmt.Print(\"Decoded Bytes: \") fmt.Println(decodedString) fmt.Print(\"Decoded String: \") fmt.Println(string(decodedString))}",
"e": 26073,
"s": 25558,
"text": null
},
{
"code": null,
"e": 26081,
"s": 26073,
"text": "Output:"
},
{
"code": null,
"e": 26179,
"s": 26081,
"text": "Decoded Bytes: [71 101 101 107 115 102 111 114 71 101 101 107 115]\nDecoded String: GeeksforGeeks\n"
},
{
"code": null,
"e": 26190,
"s": 26179,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// the base64.DecodeString() Functionpackage main import ( \"encoding/base64\" \"fmt\") func main() { // taking a string givenString := \"aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv\" // using the function decodedString, err := base64.URLEncoding.DecodeString(givenString) if err != nil { fmt.Println(\"Error Found:\", err) return } fmt.Print(\"Decoded Bytes: \") fmt.Println(decodedString) fmt.Print(\"Decoded String: \") fmt.Println(string(decodedString))}",
"e": 26725,
"s": 26190,
"text": null
},
{
"code": null,
"e": 26733,
"s": 26725,
"text": "Output:"
},
{
"code": null,
"e": 26910,
"s": 26733,
"text": "Decoded Bytes: [104 116 116 112 115 58 47 47 119 119 119 46 103 101 101 107 115 102 111 114 103 101 101 107 115 46 111 114 103 47]Decoded String: https://www.geeksforgeeks.org/"
},
{
"code": null,
"e": 26922,
"s": 26910,
"text": "Golang-Misc"
},
{
"code": null,
"e": 26934,
"s": 26922,
"text": "Go Language"
},
{
"code": null,
"e": 27032,
"s": 26934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27041,
"s": 27032,
"text": "Comments"
},
{
"code": null,
"e": 27054,
"s": 27041,
"text": "Old Comments"
},
{
"code": null,
"e": 27083,
"s": 27054,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27107,
"s": 27083,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27153,
"s": 27107,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 27174,
"s": 27153,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27208,
"s": 27174,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 27229,
"s": 27208,
"text": "Structures in Golang"
},
{
"code": null,
"e": 27247,
"s": 27229,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27272,
"s": 27247,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27320,
"s": 27272,
"text": "How to convert a string in uppercase in Golang?"
}
] |
Develop a WiFi Scanner for Android | This example demonstrate about How to develop a WiFi Scanner for Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".MainActivity">
<ListView
android:id = "@+id/wifiList"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_above = "@+id/scanBtn" />
<Button
android:id = "@+id/scanBtn"
android:layout_width = "match_parent"
android:layout_height = "50dp"
android:layout_alignParentBottom = "true"
android:layout_gravity = "bottom"
android:layout_margin = "15dp"
android:text = "Scan WiFi" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView wifiList;
private WifiManager wifiManager;
private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
WifiReceiver receiverWifi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiList = findViewById(R.id.wifiList);
Button buttonScan = findViewById(R.id.scanBtn);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
Toast.makeText(getApplicationContext(), "Turning WiFi ON...", Toast.LENGTH_LONG).show();
wifiManager.setWifiEnabled(true);
}
buttonScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
! = PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
} else {
wifiManager.startScan();
}
}
});
}
@Override
protected void onPostResume() {
super.onPostResume();
receiverWifi = new WifiReceiver(wifiManager, wifiList);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiverWifi, intentFilter);
getWifi();
}
private void getWifi() {
if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) {
Toast.makeText(MainActivity.this, "version> = marshmallow", Toast.LENGTH_SHORT).show();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
} else {
Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show();
wifiManager.startScan();
}
} else {
Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show();
wifiManager.startScan();
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiverWifi);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show();
wifiManager.startScan();
} else {
Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show();
return;
}
break;
}
}
}
Step 4 − Add the following code to src/WifiReceiver
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
class WifiReceiver extends BroadcastReceiver {
WifiManager wifiManager;
StringBuilder sb;
ListView wifiDeviceList;
public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) {
this.wifiManager = wifiManager;
this.wifiDeviceList = wifiDeviceList;
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
sb = new StringBuilder();
List<ScanResult> wifiList = wifiManager.getScanResults();
ArrayList<String> deviceList = new ArrayList<>();
for (ScanResult scanResult : wifiList) {
sb.append("\n").append(scanResult.SSID).append(" - ").append(scanResult.capabilities);
deviceList.add(scanResult.SSID + " - " + scanResult.capabilities );
}
Toast.makeText(context, sb, Toast.LENGTH_SHORT).show();
ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray());
wifiDeviceList.setAdapter(arrayAdapter);
}
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name = "android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = "com.example.myapplication.MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrate about How to develop a WiFi Scanner for Android"
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1329,
"s": 1264,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2179,
"s": 1329,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <ListView\n android:id = \"@+id/wifiList\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_above = \"@+id/scanBtn\" />\n <Button\n android:id = \"@+id/scanBtn\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"50dp\"\n android:layout_alignParentBottom = \"true\"\n android:layout_gravity = \"bottom\"\n android:layout_margin = \"15dp\"\n android:text = \"Scan WiFi\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2236,
"s": 2179,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6323,
"s": 2236,
"text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.IntentFilter;\nimport android.content.pm.PackageManager;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n private ListView wifiList;\n private WifiManager wifiManager;\n private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;\n WifiReceiver receiverWifi;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n wifiList = findViewById(R.id.wifiList);\n Button buttonScan = findViewById(R.id.scanBtn);\n wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);\n if (!wifiManager.isWifiEnabled()) {\n Toast.makeText(getApplicationContext(), \"Turning WiFi ON...\", Toast.LENGTH_LONG).show();\n wifiManager.setWifiEnabled(true);\n }\n buttonScan.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)\n ! = PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(\n MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);\n } else {\n wifiManager.startScan();\n }\n }\n });\n }\n @Override\n protected void onPostResume() {\n super.onPostResume();\n receiverWifi = new WifiReceiver(wifiManager, wifiList);\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);\n registerReceiver(receiverWifi, intentFilter);\n getWifi();\n }\n private void getWifi() {\n if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) {\n Toast.makeText(MainActivity.this, \"version> = marshmallow\", Toast.LENGTH_SHORT).show();\n if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(MainActivity.this, \"location turned off\", Toast.LENGTH_SHORT).show();\n ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);\n } else {\n Toast.makeText(MainActivity.this, \"location turned on\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n }\n } else {\n Toast.makeText(MainActivity.this, \"scanning\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n }\n }\n @Override\n protected void onPause() {\n super.onPause();\n unregisterReceiver(receiverWifi);\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:\n if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(MainActivity.this, \"permission granted\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n } else {\n Toast.makeText(MainActivity.this, \"permission not granted\", Toast.LENGTH_SHORT).show();\n return;\n }\n break;\n }\n }\n}"
},
{
"code": null,
"e": 6375,
"s": 6323,
"text": "Step 4 − Add the following code to src/WifiReceiver"
},
{
"code": null,
"e": 7858,
"s": 6375,
"text": "package com.example.myapplication;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiManager;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass WifiReceiver extends BroadcastReceiver {\n WifiManager wifiManager;\n StringBuilder sb;\n ListView wifiDeviceList;\n public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) {\n this.wifiManager = wifiManager;\n this.wifiDeviceList = wifiDeviceList;\n }\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {\n sb = new StringBuilder();\n List<ScanResult> wifiList = wifiManager.getScanResults();\n ArrayList<String> deviceList = new ArrayList<>();\n for (ScanResult scanResult : wifiList) {\n sb.append(\"\\n\").append(scanResult.SSID).append(\" - \").append(scanResult.capabilities);\n deviceList.add(scanResult.SSID + \" - \" + scanResult.capabilities );\n }\n Toast.makeText(context, sb, Toast.LENGTH_SHORT).show();\n ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray());\n wifiDeviceList.setAdapter(arrayAdapter);\n }\n }\n}"
},
{
"code": null,
"e": 7913,
"s": 7858,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 8884,
"s": 7913,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name = \"android.permission.CHANGE_WIFI_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \"com.example.myapplication.MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9233,
"s": 8884,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 9273,
"s": 9233,
"text": "Click here to download the project code"
}
] |
Convert an Integer to a Binary value in R Programming - as.binary() Function - GeeksforGeeks | 16 Jun, 2020
as.binary() function in R Language is used to convert an integer value to a binary value.
Syntax: as.binary(x)
Parameters:x: Integer value
Example 1:
# R Program to convert# an integer to binary # Loading librarylibrary(binaryLogic) # Calling as.binary() functionas.binary(1)as.binary(10)as.binary(-1)as.binary(0xAB)
Output:
[1] 1
[1] 1 0 1 0
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[1] 1 0 1 0 1 0 1 1
Example 2:
# R Program to convert# an integer to binary # Loading librarylibrary(binaryLogic) # Creating a vectorx1 <- c(1, 10, -1, 2, 5) # Calling as.binary() functionas.binary(x1)
Output:
[[1]]
[1] 1
[[2]]
[1] 1 0 1 0
[[3]]
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[[4]]
[1] 1 0
[[5]]
[1] 1 0 1
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24395,
"s": 24367,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 24485,
"s": 24395,
"text": "as.binary() function in R Language is used to convert an integer value to a binary value."
},
{
"code": null,
"e": 24506,
"s": 24485,
"text": "Syntax: as.binary(x)"
},
{
"code": null,
"e": 24534,
"s": 24506,
"text": "Parameters:x: Integer value"
},
{
"code": null,
"e": 24545,
"s": 24534,
"text": "Example 1:"
},
{
"code": "# R Program to convert# an integer to binary # Loading librarylibrary(binaryLogic) # Calling as.binary() functionas.binary(1)as.binary(10)as.binary(-1)as.binary(0xAB)",
"e": 24714,
"s": 24545,
"text": null
},
{
"code": null,
"e": 24722,
"s": 24714,
"text": "Output:"
},
{
"code": null,
"e": 24797,
"s": 24722,
"text": "[1] 1\n[1] 1 0 1 0\n[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n[1] 1 0 1 0 1 0 1 1\n"
},
{
"code": null,
"e": 24808,
"s": 24797,
"text": "Example 2:"
},
{
"code": "# R Program to convert# an integer to binary # Loading librarylibrary(binaryLogic) # Creating a vectorx1 <- c(1, 10, -1, 2, 5) # Calling as.binary() functionas.binary(x1)",
"e": 24982,
"s": 24808,
"text": null
},
{
"code": null,
"e": 24990,
"s": 24982,
"text": "Output:"
},
{
"code": null,
"e": 25098,
"s": 24990,
"text": "[[1]]\n[1] 1\n\n[[2]]\n[1] 1 0 1 0\n\n[[3]]\n [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n\n[[4]]\n[1] 1 0\n\n[[5]]\n[1] 1 0 1\n"
},
{
"code": null,
"e": 25114,
"s": 25098,
"text": "R Math-Function"
},
{
"code": null,
"e": 25125,
"s": 25114,
"text": "R Language"
},
{
"code": null,
"e": 25223,
"s": 25125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25232,
"s": 25223,
"text": "Comments"
},
{
"code": null,
"e": 25245,
"s": 25232,
"text": "Old Comments"
},
{
"code": null,
"e": 25303,
"s": 25245,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25347,
"s": 25303,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25399,
"s": 25347,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25451,
"s": 25399,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25483,
"s": 25451,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25515,
"s": 25483,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 25553,
"s": 25515,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25588,
"s": 25553,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 25646,
"s": 25588,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
DateTime.ToOADate() Method in C# | The DateTime.ToOADate() method in C# is used to convert the value of this instance to the equivalent OLE Automation date.
Following is the syntax −
public double ToOADate ();
Let us now see an example to implement the DateTime.ToOADate() method −
using System;
public class Demo {
public static void Main() {
DateTime d = new DateTime(2019, 10, 11, 9, 10, 35);
Console.WriteLine("Date = {0}", d);
double res = d.ToOADate();
Console.WriteLine("OLE Automation date = {0}", res);
}
}
This will produce the following output −
Date = 10/11/2019 9:10:35 AM
OLE Automation date = 43749.382349537
Let us now see another example to implement the DateTime.ToOADate() method −
using System;
public class Demo {
public static void Main() {
DateTime d = DateTime.Now;
Console.WriteLine("Date = {0}", d);
double res = d.ToOADate();
Console.WriteLine("OLE Automation date = {0}", res);
}
}
This will produce the following output −
Date = 10/16/2019 8:50:25 AM
OLE Automation date = 43754.3683518634 | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "The DateTime.ToOADate() method in C# is used to convert the value of this instance to the equivalent OLE Automation date."
},
{
"code": null,
"e": 1210,
"s": 1184,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1237,
"s": 1210,
"text": "public double ToOADate ();"
},
{
"code": null,
"e": 1309,
"s": 1237,
"text": "Let us now see an example to implement the DateTime.ToOADate() method −"
},
{
"code": null,
"e": 1573,
"s": 1309,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 10, 11, 9, 10, 35);\n Console.WriteLine(\"Date = {0}\", d);\n double res = d.ToOADate();\n Console.WriteLine(\"OLE Automation date = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 1614,
"s": 1573,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1681,
"s": 1614,
"text": "Date = 10/11/2019 9:10:35 AM\nOLE Automation date = 43749.382349537"
},
{
"code": null,
"e": 1758,
"s": 1681,
"text": "Let us now see another example to implement the DateTime.ToOADate() method −"
},
{
"code": null,
"e": 1997,
"s": 1758,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = DateTime.Now;\n Console.WriteLine(\"Date = {0}\", d);\n double res = d.ToOADate();\n Console.WriteLine(\"OLE Automation date = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 2038,
"s": 1997,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2106,
"s": 2038,
"text": "Date = 10/16/2019 8:50:25 AM\nOLE Automation date = 43754.3683518634"
}
] |
HTML DOM removeChild() Method | The DOM removeChild() method returns and remove the specified child node of the specified node in an HTML document.
Following is the syntax −
node.removeChild(node);
Let us see an example of removeChild() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.2rem;
}
ul{
list-style-type: none;
padding:0;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:50%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
font-weight:bold;
}
</style>
</head>
<body>
<h1>Student Subjects</h1>
<p>Hi, My favourite subjects are:</p>
<ul id="subjectList">
<li>Physics</li>
<li>Chemistry</li>
<li>Maths</li>
<li>English</li>
</ul>
<button onclick="removeSubject()" class="btn">Remove Subject</button>
<script>
function removeSubject() {
var subList = document.getElementById("subjectList");
if (subList.hasChildNodes()) {
subList.removeChild(subList.childNodes[0]);
}
}
</script>
</body>
</html>
This will produce the following output −
Click on “Remove Subject” button to remove subject from the list − | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "The DOM removeChild() method returns and remove the specified child node of the specified node in an HTML document."
},
{
"code": null,
"e": 1204,
"s": 1178,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1228,
"s": 1204,
"text": "node.removeChild(node);"
},
{
"code": null,
"e": 1276,
"s": 1228,
"text": "Let us see an example of removeChild() method −"
},
{
"code": null,
"e": 1287,
"s": 1276,
"text": " Live Demo"
},
{
"code": null,
"e": 2411,
"s": 1287,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n html{\n height:100%;\n }\n body{\n text-align:center;\n color:#fff;\n background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;\n height:100%;\n }\n p{\n font-weight:700;\n font-size:1.2rem;\n }\n ul{\n list-style-type: none;\n padding:0;\n }\n .btn{\n background:#0197F6;\n border:none;\n height:2rem;\n border-radius:2px;\n width:50%;\n margin:2rem auto;\n display:block;\n color:#fff;\n outline:none;\n cursor:pointer;\n }\n .show{\n font-size:1.5rem;\n font-weight:bold;\n }\n</style>\n</head>\n<body>\n<h1>Student Subjects</h1>\n<p>Hi, My favourite subjects are:</p>\n<ul id=\"subjectList\">\n<li>Physics</li>\n<li>Chemistry</li>\n<li>Maths</li>\n<li>English</li>\n</ul>\n<button onclick=\"removeSubject()\" class=\"btn\">Remove Subject</button>\n<script>\n function removeSubject() {\n var subList = document.getElementById(\"subjectList\");\n if (subList.hasChildNodes()) {\n subList.removeChild(subList.childNodes[0]);\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2452,
"s": 2411,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2519,
"s": 2452,
"text": "Click on “Remove Subject” button to remove subject from the list −"
}
] |
Profit and loss Problems using C | Given a certain cost price(cp) and a selling price(sp) of an unknown product or a service, our task is to find the profit earned or loss suffered using a C program where if the profit is earned should print “Profit” and it’s amount or if the loss is suffered “Loss” and its respective amount or if there is not profit no loss then print “No profit nor Loss”.
To find the profit or the loss we generally see whether the selling price(sp) or the price/amount at which a certain thing is sold or the cost price(cp) at which a certain thing is bought. If the cost price(cp) is higher than the selling price(sp) then it is believed that there is loss, and their difference will be the total loss suffered. When the selling price(sp) is higher than the cost price(cp) then it is believed that profit is earned, and their difference is the total profit.
Input − cp = 149, sp = 229
Output − Profit 80
Explanation −selling price(sp) > cost price(cp), so there is profit of sp-cp=80
Input − cp = 149, sp = 129
Output −Loss 20
Explanation −cost price(cp) > selling price(sp), so there is loss of cp-sp=20
Take the cost price and selling price as input
Take the cost price and selling price as input
Check if cost price > selling price, then it is a loss find difference and return the result.
Check if cost price > selling price, then it is a loss find difference and return the result.
Check if selling price > cost price, then it is a profit find difference and return the result.
Check if selling price > cost price, then it is a profit find difference and return the result.
And if selling price == cost price, then there is not profit nor a loss.
And if selling price == cost price, then there is not profit nor a loss.
Start
In function int Profit(int cp, int sp)
Step 1→ Return (sp - cp)
In function int Loss(int cp, int sp)
Step 1→ Return (cp - sp)
In function int main()
Step 1→ Declare and initialize cp = 5000, sp = 6700
Step 2→ If sp == cp then,
Print "No profit nor Loss"
Step 3→ Else if sp > cp
Print Profit
Step 4→ Else
Print Loss
Stop
Live Demo
#include <stdio.h>
//Function will return profit
int Profit(int cp, int sp){
return (sp - cp);
}
// Function will return Loss.
int Loss(int cp, int sp){
return (cp - sp);
}
int main(){
int cp = 5000, sp = 6700;
if (sp == cp)
printf("No profit nor Loss\n");
else if (sp > cp)
printf("%d Profit\n", Profit(cp, sp));
else
printf("%d Loss\n", Loss(cp, sp));
return 0;
}
If run the above code it will generate the following output −
1700 Profit | [
{
"code": null,
"e": 1421,
"s": 1062,
"text": "Given a certain cost price(cp) and a selling price(sp) of an unknown product or a service, our task is to find the profit earned or loss suffered using a C program where if the profit is earned should print “Profit” and it’s amount or if the loss is suffered “Loss” and its respective amount or if there is not profit no loss then print “No profit nor Loss”."
},
{
"code": null,
"e": 1909,
"s": 1421,
"text": "To find the profit or the loss we generally see whether the selling price(sp) or the price/amount at which a certain thing is sold or the cost price(cp) at which a certain thing is bought. If the cost price(cp) is higher than the selling price(sp) then it is believed that there is loss, and their difference will be the total loss suffered. When the selling price(sp) is higher than the cost price(cp) then it is believed that profit is earned, and their difference is the total profit."
},
{
"code": null,
"e": 1936,
"s": 1909,
"text": "Input − cp = 149, sp = 229"
},
{
"code": null,
"e": 1955,
"s": 1936,
"text": "Output − Profit 80"
},
{
"code": null,
"e": 2035,
"s": 1955,
"text": "Explanation −selling price(sp) > cost price(cp), so there is profit of sp-cp=80"
},
{
"code": null,
"e": 2062,
"s": 2035,
"text": "Input − cp = 149, sp = 129"
},
{
"code": null,
"e": 2078,
"s": 2062,
"text": "Output −Loss 20"
},
{
"code": null,
"e": 2156,
"s": 2078,
"text": "Explanation −cost price(cp) > selling price(sp), so there is loss of cp-sp=20"
},
{
"code": null,
"e": 2203,
"s": 2156,
"text": "Take the cost price and selling price as input"
},
{
"code": null,
"e": 2250,
"s": 2203,
"text": "Take the cost price and selling price as input"
},
{
"code": null,
"e": 2344,
"s": 2250,
"text": "Check if cost price > selling price, then it is a loss find difference and return the result."
},
{
"code": null,
"e": 2438,
"s": 2344,
"text": "Check if cost price > selling price, then it is a loss find difference and return the result."
},
{
"code": null,
"e": 2534,
"s": 2438,
"text": "Check if selling price > cost price, then it is a profit find difference and return the result."
},
{
"code": null,
"e": 2630,
"s": 2534,
"text": "Check if selling price > cost price, then it is a profit find difference and return the result."
},
{
"code": null,
"e": 2703,
"s": 2630,
"text": "And if selling price == cost price, then there is not profit nor a loss."
},
{
"code": null,
"e": 2776,
"s": 2703,
"text": "And if selling price == cost price, then there is not profit nor a loss."
},
{
"code": null,
"e": 3138,
"s": 2776,
"text": "Start\nIn function int Profit(int cp, int sp)\n Step 1→ Return (sp - cp)\nIn function int Loss(int cp, int sp)\n Step 1→ Return (cp - sp)\nIn function int main()\n Step 1→ Declare and initialize cp = 5000, sp = 6700\n Step 2→ If sp == cp then,\n Print \"No profit nor Loss\"\n Step 3→ Else if sp > cp\n Print Profit\n Step 4→ Else\n Print Loss\nStop"
},
{
"code": null,
"e": 3149,
"s": 3138,
"text": " Live Demo"
},
{
"code": null,
"e": 3554,
"s": 3149,
"text": "#include <stdio.h>\n//Function will return profit\nint Profit(int cp, int sp){\n return (sp - cp);\n}\n// Function will return Loss.\nint Loss(int cp, int sp){\n return (cp - sp);\n}\nint main(){\n int cp = 5000, sp = 6700;\n if (sp == cp)\n printf(\"No profit nor Loss\\n\");\n else if (sp > cp)\n printf(\"%d Profit\\n\", Profit(cp, sp));\n else\n printf(\"%d Loss\\n\", Loss(cp, sp));\n return 0;\n}"
},
{
"code": null,
"e": 3616,
"s": 3554,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3628,
"s": 3616,
"text": "1700 Profit"
}
] |
Find the direction from given string in C++ | Suppose we have a string which contains only L and R, this denotes left rotation and right rotation respectively, we have to find the final direction of pivot. Here directions are north(N), east(E), south(S) and west(W). We are assuming that the pivot is pointed towards north(N) in a compass.
So, if the input is like "RRLRLLR", then the output will be E, as initial direction is N, RR will point to S, then LR will point to the same N again, then LL will point to previous position N, then R will point to E. So E is the final.
To solve this, we will follow these steps −
count := 0
count := 0
direction := a blank string
direction := a blank string
for initialize i := 0, when i − length of s, update (increase i by 1), do −if s[i] is same as 'L', then −(decrease count by 1)Otherwise(increase count by 1)
for initialize i := 0, when i − length of s, update (increase i by 1), do −
if s[i] is same as 'L', then −(decrease count by 1)
if s[i] is same as 'L', then −
(decrease count by 1)
(decrease count by 1)
Otherwise(increase count by 1)
Otherwise
(increase count by 1)
(increase count by 1)
if count > 0, then −if count mod 4 is same as 0, then −direction := "N"otherwise when count mod 4 is same as 1, then −direction := "E"otherwise when count mod 4 is same as 2, then −direction := "S"otherwise when count mod 4 is same as 3, then −direction := "W"
if count > 0, then −
if count mod 4 is same as 0, then −direction := "N"
if count mod 4 is same as 0, then −
direction := "N"
direction := "N"
otherwise when count mod 4 is same as 1, then −direction := "E"
otherwise when count mod 4 is same as 1, then −
direction := "E"
direction := "E"
otherwise when count mod 4 is same as 2, then −direction := "S"
otherwise when count mod 4 is same as 2, then −
direction := "S"
direction := "S"
otherwise when count mod 4 is same as 3, then −direction := "W"
otherwise when count mod 4 is same as 3, then −
direction := "W"
direction := "W"
if count < 0, then −if count mod 4 is same as 0, then −direction := "N"otherwise when count mod 4 is same as -1, then −direction := "W"otherwise when count mod 4 is same as -2, then −direction := "S"therwise when count mod 4 is same as -3, then −direction := "E"
if count < 0, then −
if count mod 4 is same as 0, then −direction := "N"
if count mod 4 is same as 0, then −
direction := "N"
direction := "N"
otherwise when count mod 4 is same as -1, then −direction := "W"
otherwise when count mod 4 is same as -1, then −
direction := "W"
direction := "W"
otherwise when count mod 4 is same as -2, then −direction := "S"
otherwise when count mod 4 is same as -2, then −
direction := "S"
direction := "S"
therwise when count mod 4 is same as -3, then −direction := "E"
therwise when count mod 4 is same as -3, then −
direction := "E"
direction := "E"
return direction
return direction
Let us see the following implementation to get better understanding −
Live Demo
#include<bits/stdc++.h>
using namespace std;
string get_dir(string s) {
int count = 0;
string direction = "";
for (int i = 0; i < s.length(); i++){
if (s[0] == '\n')
return NULL;
if (s[i] == 'L')
count--;
else
count++;
}
if (count > 0){
if (count % 4 == 0)
direction = "N";
else if (count % 4 == 1)
direction = "E";
else if (count % 4 == 2)
direction = "S";
else if (count % 4 == 3)
direction = "W";
}
if (count < 0){
if (count % 4 == 0)
direction = "N";
else if (count % 4 == -1)
direction = "W";
else if (count % 4 == -2)
direction = "S";
else if (count % 4 == -3)
direction = "E";
}
return direction;
}
int main() {
string s = "RRLRLLR";
cout << (get_dir(s));
}
"RRLRLLR"
E | [
{
"code": null,
"e": 1356,
"s": 1062,
"text": "Suppose we have a string which contains only L and R, this denotes left rotation and right rotation respectively, we have to find the final direction of pivot. Here directions are north(N), east(E), south(S) and west(W). We are assuming that the pivot is pointed towards north(N) in a compass."
},
{
"code": null,
"e": 1592,
"s": 1356,
"text": "So, if the input is like \"RRLRLLR\", then the output will be E, as initial direction is N, RR will point to S, then LR will point to the same N again, then LL will point to previous position N, then R will point to E. So E is the final."
},
{
"code": null,
"e": 1636,
"s": 1592,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1647,
"s": 1636,
"text": "count := 0"
},
{
"code": null,
"e": 1658,
"s": 1647,
"text": "count := 0"
},
{
"code": null,
"e": 1686,
"s": 1658,
"text": "direction := a blank string"
},
{
"code": null,
"e": 1714,
"s": 1686,
"text": "direction := a blank string"
},
{
"code": null,
"e": 1871,
"s": 1714,
"text": "for initialize i := 0, when i − length of s, update (increase i by 1), do −if s[i] is same as 'L', then −(decrease count by 1)Otherwise(increase count by 1)"
},
{
"code": null,
"e": 1947,
"s": 1871,
"text": "for initialize i := 0, when i − length of s, update (increase i by 1), do −"
},
{
"code": null,
"e": 1999,
"s": 1947,
"text": "if s[i] is same as 'L', then −(decrease count by 1)"
},
{
"code": null,
"e": 2030,
"s": 1999,
"text": "if s[i] is same as 'L', then −"
},
{
"code": null,
"e": 2052,
"s": 2030,
"text": "(decrease count by 1)"
},
{
"code": null,
"e": 2074,
"s": 2052,
"text": "(decrease count by 1)"
},
{
"code": null,
"e": 2105,
"s": 2074,
"text": "Otherwise(increase count by 1)"
},
{
"code": null,
"e": 2115,
"s": 2105,
"text": "Otherwise"
},
{
"code": null,
"e": 2137,
"s": 2115,
"text": "(increase count by 1)"
},
{
"code": null,
"e": 2159,
"s": 2137,
"text": "(increase count by 1)"
},
{
"code": null,
"e": 2420,
"s": 2159,
"text": "if count > 0, then −if count mod 4 is same as 0, then −direction := \"N\"otherwise when count mod 4 is same as 1, then −direction := \"E\"otherwise when count mod 4 is same as 2, then −direction := \"S\"otherwise when count mod 4 is same as 3, then −direction := \"W\""
},
{
"code": null,
"e": 2441,
"s": 2420,
"text": "if count > 0, then −"
},
{
"code": null,
"e": 2493,
"s": 2441,
"text": "if count mod 4 is same as 0, then −direction := \"N\""
},
{
"code": null,
"e": 2529,
"s": 2493,
"text": "if count mod 4 is same as 0, then −"
},
{
"code": null,
"e": 2546,
"s": 2529,
"text": "direction := \"N\""
},
{
"code": null,
"e": 2563,
"s": 2546,
"text": "direction := \"N\""
},
{
"code": null,
"e": 2627,
"s": 2563,
"text": "otherwise when count mod 4 is same as 1, then −direction := \"E\""
},
{
"code": null,
"e": 2675,
"s": 2627,
"text": "otherwise when count mod 4 is same as 1, then −"
},
{
"code": null,
"e": 2692,
"s": 2675,
"text": "direction := \"E\""
},
{
"code": null,
"e": 2709,
"s": 2692,
"text": "direction := \"E\""
},
{
"code": null,
"e": 2773,
"s": 2709,
"text": "otherwise when count mod 4 is same as 2, then −direction := \"S\""
},
{
"code": null,
"e": 2821,
"s": 2773,
"text": "otherwise when count mod 4 is same as 2, then −"
},
{
"code": null,
"e": 2838,
"s": 2821,
"text": "direction := \"S\""
},
{
"code": null,
"e": 2855,
"s": 2838,
"text": "direction := \"S\""
},
{
"code": null,
"e": 2919,
"s": 2855,
"text": "otherwise when count mod 4 is same as 3, then −direction := \"W\""
},
{
"code": null,
"e": 2967,
"s": 2919,
"text": "otherwise when count mod 4 is same as 3, then −"
},
{
"code": null,
"e": 2984,
"s": 2967,
"text": "direction := \"W\""
},
{
"code": null,
"e": 3001,
"s": 2984,
"text": "direction := \"W\""
},
{
"code": null,
"e": 3264,
"s": 3001,
"text": "if count < 0, then −if count mod 4 is same as 0, then −direction := \"N\"otherwise when count mod 4 is same as -1, then −direction := \"W\"otherwise when count mod 4 is same as -2, then −direction := \"S\"therwise when count mod 4 is same as -3, then −direction := \"E\""
},
{
"code": null,
"e": 3285,
"s": 3264,
"text": "if count < 0, then −"
},
{
"code": null,
"e": 3337,
"s": 3285,
"text": "if count mod 4 is same as 0, then −direction := \"N\""
},
{
"code": null,
"e": 3373,
"s": 3337,
"text": "if count mod 4 is same as 0, then −"
},
{
"code": null,
"e": 3390,
"s": 3373,
"text": "direction := \"N\""
},
{
"code": null,
"e": 3407,
"s": 3390,
"text": "direction := \"N\""
},
{
"code": null,
"e": 3472,
"s": 3407,
"text": "otherwise when count mod 4 is same as -1, then −direction := \"W\""
},
{
"code": null,
"e": 3521,
"s": 3472,
"text": "otherwise when count mod 4 is same as -1, then −"
},
{
"code": null,
"e": 3538,
"s": 3521,
"text": "direction := \"W\""
},
{
"code": null,
"e": 3555,
"s": 3538,
"text": "direction := \"W\""
},
{
"code": null,
"e": 3620,
"s": 3555,
"text": "otherwise when count mod 4 is same as -2, then −direction := \"S\""
},
{
"code": null,
"e": 3669,
"s": 3620,
"text": "otherwise when count mod 4 is same as -2, then −"
},
{
"code": null,
"e": 3686,
"s": 3669,
"text": "direction := \"S\""
},
{
"code": null,
"e": 3703,
"s": 3686,
"text": "direction := \"S\""
},
{
"code": null,
"e": 3767,
"s": 3703,
"text": "therwise when count mod 4 is same as -3, then −direction := \"E\""
},
{
"code": null,
"e": 3815,
"s": 3767,
"text": "therwise when count mod 4 is same as -3, then −"
},
{
"code": null,
"e": 3832,
"s": 3815,
"text": "direction := \"E\""
},
{
"code": null,
"e": 3849,
"s": 3832,
"text": "direction := \"E\""
},
{
"code": null,
"e": 3866,
"s": 3849,
"text": "return direction"
},
{
"code": null,
"e": 3883,
"s": 3866,
"text": "return direction"
},
{
"code": null,
"e": 3953,
"s": 3883,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3964,
"s": 3953,
"text": " Live Demo"
},
{
"code": null,
"e": 4827,
"s": 3964,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nstring get_dir(string s) {\n int count = 0;\n string direction = \"\";\n for (int i = 0; i < s.length(); i++){\n if (s[0] == '\\n')\n return NULL;\n if (s[i] == 'L')\n count--;\n else\n count++;\n }\n if (count > 0){\n if (count % 4 == 0)\n direction = \"N\";\n else if (count % 4 == 1)\n direction = \"E\";\n else if (count % 4 == 2)\n direction = \"S\";\n else if (count % 4 == 3)\n direction = \"W\";\n }\n if (count < 0){\n if (count % 4 == 0)\n direction = \"N\";\n else if (count % 4 == -1)\n direction = \"W\";\n else if (count % 4 == -2)\n direction = \"S\";\n else if (count % 4 == -3)\n direction = \"E\";\n }\n return direction;\n}\nint main() {\n string s = \"RRLRLLR\";\n cout << (get_dir(s));\n}"
},
{
"code": null,
"e": 4837,
"s": 4827,
"text": "\"RRLRLLR\""
},
{
"code": null,
"e": 4839,
"s": 4837,
"text": "E"
}
] |
Python | Index of Non-Zero elements in Python list - GeeksforGeeks | 05 Sep, 2019
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let’s discuss a shorthand by which we can perform this particular task.
Method : Using enumerate() + list comprehensionThis method can be performed using combination of functionalities. In this, we use enumerate function to access index-element together and list comprehension is used for iteration and logic creation.
# Python3 code to demonstrate working of# Index of Non-Zero elements in Python list# using list comprehension + enumerate() # initialize listtest_list = [6, 7, 0, 1, 0, 2, 0, 12] # printing original listprint("The original list is : " + str(test_list)) # Index of Non-Zero elements in Python list# using list comprehension + enumerate()res = [idx for idx, val in enumerate(test_list) if val != 0] # printing resultprint("Indices of Non-Zero elements : " + str(res))
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24391,
"s": 24363,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 24674,
"s": 24391,
"text": "Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let’s discuss a shorthand by which we can perform this particular task."
},
{
"code": null,
"e": 24921,
"s": 24674,
"text": "Method : Using enumerate() + list comprehensionThis method can be performed using combination of functionalities. In this, we use enumerate function to access index-element together and list comprehension is used for iteration and logic creation."
},
{
"code": "# Python3 code to demonstrate working of# Index of Non-Zero elements in Python list# using list comprehension + enumerate() # initialize listtest_list = [6, 7, 0, 1, 0, 2, 0, 12] # printing original listprint(\"The original list is : \" + str(test_list)) # Index of Non-Zero elements in Python list# using list comprehension + enumerate()res = [idx for idx, val in enumerate(test_list) if val != 0] # printing resultprint(\"Indices of Non-Zero elements : \" + str(res))",
"e": 25391,
"s": 24921,
"text": null
},
{
"code": null,
"e": 25488,
"s": 25391,
"text": "The original list is : [6, 7, 0, 1, 0, 2, 0, 12]\nIndices of Non-Zero elements : [0, 1, 3, 5, 7]\n"
},
{
"code": null,
"e": 25509,
"s": 25488,
"text": "Python list-programs"
},
{
"code": null,
"e": 25516,
"s": 25509,
"text": "Python"
},
{
"code": null,
"e": 25614,
"s": 25516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25623,
"s": 25614,
"text": "Comments"
},
{
"code": null,
"e": 25636,
"s": 25623,
"text": "Old Comments"
},
{
"code": null,
"e": 25654,
"s": 25636,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25689,
"s": 25654,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25711,
"s": 25689,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25743,
"s": 25711,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25773,
"s": 25743,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25815,
"s": 25773,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25858,
"s": 25815,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25902,
"s": 25858,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 25927,
"s": 25902,
"text": "sum() function in Python"
}
] |
Elegant And Efficient Usage of If-Else Clauses | by Mohammed Ayar | Towards Data Science | Take a piece of writing. Remove the cohesive devices (However, Therefore...). And read it. Does it make sense anymore? NO! The same thing applies to code without if-else statements.
Conditional branching is a basic and mandatory programming concept. It flags a reasoning shift. The wise utilization of conditionals results in having a short, maintainable, and readable code.
That said, ever since I started coding, I took it upon myself to dedicate as much time as possible reading both senior and entry levels programmers’ codes. Here I lay the track I follow to demystify advanced code.
towardsdatascience.com
Surprisingly, the more I read the more I notice how great is the gulf between seasoned and beginner programmers. Seniors write code that takes your breath away. Juniors write code that makes you want to tear your hair out.
Verdict: It’s not about the syntax, it’s about how to use the syntax.
In this piece, I shall to the best of my knowledge explain how great programmers leverage the power of if-else clauses.
Remember:
It’s not about the sword it’s about the swordman.
The professor: “Hello everyone, Today we’re going to take a look at one of the important flow control tools: If-else statements. So, please pay attention to this flowchart.”
Me: “Oh, again, flowcharts. It’s time to sleep. Zzzz”.
I must confess. I am not an attentive student. I start yawning whenever professors exceed 15 min of straight speech. Explanations via flowcharts do only catalyze the process. That was a mistake that costs me so much.
Flowcharts are the simplest way to represent a workflow. I am sure that a great part of your conditional branching troubles will be resolved once you digest if-else flowchart.
Here’s what it looks like:
From the diagram, you can see that how if-else is interpreted is fairly easy. It means once an if expression evaluates as true, its body is executed and the rest of the clauses are ignored.
It is critically important that you understand fully the flowchart because missing a single detail may cost you efficient if statements. Don’t worry, we will be discussing this in detail later on in this post.
I’ve been coding for more than 5 years. During this time, I came to realize that there are two types of programmers.
Those who use verbose and loose if-else statements.
Those who use concise and clean if-else statements.
Ironically, while the ‘How’ is different, the ‘Why’ is the same. To demonstrate this, we’ll resolve the problem below using both above perspectives.
Problem:
You’ve got a bunch of credit cards. You want to classify them into “Maybe Mastercard”, “Maybe Visa” or invalid otherwise. A Visa card must have 4 as the first digit and 16 or 13 digits in total. A Mastercard must have 51, 52 ... until 55 as the first two digits and 16 digits in total.
1st group sample code:
ccn = 13fd = 4if ccn == 16 and (fd == 51 or fd == 52 or fd == 53 or fd == 54 or fd == 55): print("Maybe MASTERCARD")elif (ccn == 13 or ccn == 16) and fd == 4: print("Maybe VISA")else: print("INVALID")
Output:
>>> Maybe VISA
2nd group sample code:
ccn = 13fd = 54if ccn == 16 and 51 <= fd <= 55: print("Maybe MASTERCARD")elif ccn in [13, 16] and fd == 4: print("Maybe VISA")else: print("INVALID")
Output:
>>> Maybe VISA
You can see that while both codes do the same task, each one is written differently. The first is verbose and inelegant. The second is concise and appealing. It’s the kind of if-else statements you want to write. But how to do so?
Learn mathematical logic. A good reference is this class from StanfordMake use of arrays whenever there are multiple values to checkRead experienced programmers code
Learn mathematical logic. A good reference is this class from Stanford
Make use of arrays whenever there are multiple values to check
Read experienced programmers code
I am pretty sure that if you abide by these 3 rules. You’ll be writing better if-else statements.
Ternary Operator literally means an operator composed of three parts. These parts are:
Middle part: a condition
Left part: the expression to be executed once the condition is true
Right part: the expression to be executed otherwise
This translates to the flowchart below:
Just like standard if-else statements, you can use the ternary operator to write flat and nested expressions.
Flat
<expression1> if <condition> else <expression2>
Nested
<expression1> if <condition1> else <expression2> if <condition2> else <expression3> .... if <condition(N-1)> else <expressionN>
It saddens me to see that some programmers abuse this operator only because it is shorter than an explicit if-else statement.
The main reason for the ternary operator is to provide a concise medium for value assignment. It is, therefore, better to use the standard control flow tools when it comes to multiple branching instead of using the operator to write nested expressions.
To quote the author of Python PEP 308 conditional expression proposal:
“A Python design principle has been to prefer the status quo whenever there are doubts about which path to take.”
Have you ever wondered what is the difference between a serial if block and anif-else block? For example:
if <expression1>: statement1if <expression2>: statement2 . . .if <expressionN>: statementN
and:
if <expression1>: statement1elif <expression2>: statement2 . . .elif <expressionN>: statementN
The first time I was introduced to conditional expressions, I didn’t fully understand if-else flowchart. I, as a result, was always using serial if statements since they were always producing expected results. I was wrong!
While in a serial if block, all the conditions are tested, in an if-elseblock the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.
That said, when you’re dealing with a case that requires only one condition to be satisfied use if-else if-else statements.
Perhaps we’ve reached the most important section of this post. Nested if-else statements.
The overuse of conditional clauses leads sometimes to deeply nested if-else statements, which are frowned upon by the programming community and regarded as a poor design.
Luckily, there is a way to outmaneuver nested if-else statements. That is decision tables.
To understand how you can make good use of decision tables. We’re going to work on the following code about comparing numbers in respect to 200:
(This sample is a modified version of a code from tutorialspoint)
Output:
Value is less than 200Between 100 and 150It is 125
Oh boy, we’ve got ourselves a load of if-else statements nested on 3 levels. This is a bad code because it’s lengthy, hard to read and to maintain.
Let’s try to flatten out these nested if-else statements.
But before we do that and to maximize learning outcomes, we’re going to do analyze and jot down remarques from the code above.
The first level of if classifies numbers to greater or less than 200The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150The third level of if prints the number if it’s equal to those in the conditions
The first level of if classifies numbers to greater or less than 200
The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150
The third level of if prints the number if it’s equal to those in the conditions
Now, we’ll inject remarque n°2 and n°3 into separate functions. print_interval(val) and print_value(val). Then we’ll store the two nested if-else blocks in two dictionaries (Decision tables). The first one to do the classification as per the remarque n°2. The second one to print the number as per the remarque n°3.
With everything in place, we get the following code:
Output:
Value is less than 200Between 100 and 150It is 125
As you can see we managed to get rid of the nested if-else statements by using functions and decision tables. This has allowed us to write a better-designed code. Readable and maintainable.
Ultimately, you can see that we used a mixture of conditional statements, functions, dictionaries rather than abusing if-else . How to manipulate these, however, is up to you and to your own judgment.
In an effort to help you take your conditional branching skills to the next level, we discussed the pitfalls of if-else statements as well as how to bypass them. The information above is the fruit of 5 years of programming. Still, programming is an infinite realm. that’s why they say:
“Programming is a chess game. Easy to learn. Hard to master”. | [
{
"code": null,
"e": 354,
"s": 172,
"text": "Take a piece of writing. Remove the cohesive devices (However, Therefore...). And read it. Does it make sense anymore? NO! The same thing applies to code without if-else statements."
},
{
"code": null,
"e": 547,
"s": 354,
"text": "Conditional branching is a basic and mandatory programming concept. It flags a reasoning shift. The wise utilization of conditionals results in having a short, maintainable, and readable code."
},
{
"code": null,
"e": 761,
"s": 547,
"text": "That said, ever since I started coding, I took it upon myself to dedicate as much time as possible reading both senior and entry levels programmers’ codes. Here I lay the track I follow to demystify advanced code."
},
{
"code": null,
"e": 784,
"s": 761,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1007,
"s": 784,
"text": "Surprisingly, the more I read the more I notice how great is the gulf between seasoned and beginner programmers. Seniors write code that takes your breath away. Juniors write code that makes you want to tear your hair out."
},
{
"code": null,
"e": 1077,
"s": 1007,
"text": "Verdict: It’s not about the syntax, it’s about how to use the syntax."
},
{
"code": null,
"e": 1197,
"s": 1077,
"text": "In this piece, I shall to the best of my knowledge explain how great programmers leverage the power of if-else clauses."
},
{
"code": null,
"e": 1207,
"s": 1197,
"text": "Remember:"
},
{
"code": null,
"e": 1257,
"s": 1207,
"text": "It’s not about the sword it’s about the swordman."
},
{
"code": null,
"e": 1431,
"s": 1257,
"text": "The professor: “Hello everyone, Today we’re going to take a look at one of the important flow control tools: If-else statements. So, please pay attention to this flowchart.”"
},
{
"code": null,
"e": 1486,
"s": 1431,
"text": "Me: “Oh, again, flowcharts. It’s time to sleep. Zzzz”."
},
{
"code": null,
"e": 1703,
"s": 1486,
"text": "I must confess. I am not an attentive student. I start yawning whenever professors exceed 15 min of straight speech. Explanations via flowcharts do only catalyze the process. That was a mistake that costs me so much."
},
{
"code": null,
"e": 1879,
"s": 1703,
"text": "Flowcharts are the simplest way to represent a workflow. I am sure that a great part of your conditional branching troubles will be resolved once you digest if-else flowchart."
},
{
"code": null,
"e": 1906,
"s": 1879,
"text": "Here’s what it looks like:"
},
{
"code": null,
"e": 2096,
"s": 1906,
"text": "From the diagram, you can see that how if-else is interpreted is fairly easy. It means once an if expression evaluates as true, its body is executed and the rest of the clauses are ignored."
},
{
"code": null,
"e": 2306,
"s": 2096,
"text": "It is critically important that you understand fully the flowchart because missing a single detail may cost you efficient if statements. Don’t worry, we will be discussing this in detail later on in this post."
},
{
"code": null,
"e": 2423,
"s": 2306,
"text": "I’ve been coding for more than 5 years. During this time, I came to realize that there are two types of programmers."
},
{
"code": null,
"e": 2475,
"s": 2423,
"text": "Those who use verbose and loose if-else statements."
},
{
"code": null,
"e": 2527,
"s": 2475,
"text": "Those who use concise and clean if-else statements."
},
{
"code": null,
"e": 2676,
"s": 2527,
"text": "Ironically, while the ‘How’ is different, the ‘Why’ is the same. To demonstrate this, we’ll resolve the problem below using both above perspectives."
},
{
"code": null,
"e": 2685,
"s": 2676,
"text": "Problem:"
},
{
"code": null,
"e": 2971,
"s": 2685,
"text": "You’ve got a bunch of credit cards. You want to classify them into “Maybe Mastercard”, “Maybe Visa” or invalid otherwise. A Visa card must have 4 as the first digit and 16 or 13 digits in total. A Mastercard must have 51, 52 ... until 55 as the first two digits and 16 digits in total."
},
{
"code": null,
"e": 2994,
"s": 2971,
"text": "1st group sample code:"
},
{
"code": null,
"e": 3204,
"s": 2994,
"text": "ccn = 13fd = 4if ccn == 16 and (fd == 51 or fd == 52 or fd == 53 or fd == 54 or fd == 55): print(\"Maybe MASTERCARD\")elif (ccn == 13 or ccn == 16) and fd == 4: print(\"Maybe VISA\")else: print(\"INVALID\")"
},
{
"code": null,
"e": 3212,
"s": 3204,
"text": "Output:"
},
{
"code": null,
"e": 3227,
"s": 3212,
"text": ">>> Maybe VISA"
},
{
"code": null,
"e": 3250,
"s": 3227,
"text": "2nd group sample code:"
},
{
"code": null,
"e": 3408,
"s": 3250,
"text": "ccn = 13fd = 54if ccn == 16 and 51 <= fd <= 55: print(\"Maybe MASTERCARD\")elif ccn in [13, 16] and fd == 4: print(\"Maybe VISA\")else: print(\"INVALID\")"
},
{
"code": null,
"e": 3416,
"s": 3408,
"text": "Output:"
},
{
"code": null,
"e": 3431,
"s": 3416,
"text": ">>> Maybe VISA"
},
{
"code": null,
"e": 3662,
"s": 3431,
"text": "You can see that while both codes do the same task, each one is written differently. The first is verbose and inelegant. The second is concise and appealing. It’s the kind of if-else statements you want to write. But how to do so?"
},
{
"code": null,
"e": 3828,
"s": 3662,
"text": "Learn mathematical logic. A good reference is this class from StanfordMake use of arrays whenever there are multiple values to checkRead experienced programmers code"
},
{
"code": null,
"e": 3899,
"s": 3828,
"text": "Learn mathematical logic. A good reference is this class from Stanford"
},
{
"code": null,
"e": 3962,
"s": 3899,
"text": "Make use of arrays whenever there are multiple values to check"
},
{
"code": null,
"e": 3996,
"s": 3962,
"text": "Read experienced programmers code"
},
{
"code": null,
"e": 4094,
"s": 3996,
"text": "I am pretty sure that if you abide by these 3 rules. You’ll be writing better if-else statements."
},
{
"code": null,
"e": 4181,
"s": 4094,
"text": "Ternary Operator literally means an operator composed of three parts. These parts are:"
},
{
"code": null,
"e": 4206,
"s": 4181,
"text": "Middle part: a condition"
},
{
"code": null,
"e": 4274,
"s": 4206,
"text": "Left part: the expression to be executed once the condition is true"
},
{
"code": null,
"e": 4326,
"s": 4274,
"text": "Right part: the expression to be executed otherwise"
},
{
"code": null,
"e": 4366,
"s": 4326,
"text": "This translates to the flowchart below:"
},
{
"code": null,
"e": 4476,
"s": 4366,
"text": "Just like standard if-else statements, you can use the ternary operator to write flat and nested expressions."
},
{
"code": null,
"e": 4481,
"s": 4476,
"text": "Flat"
},
{
"code": null,
"e": 4529,
"s": 4481,
"text": "<expression1> if <condition> else <expression2>"
},
{
"code": null,
"e": 4536,
"s": 4529,
"text": "Nested"
},
{
"code": null,
"e": 4664,
"s": 4536,
"text": "<expression1> if <condition1> else <expression2> if <condition2> else <expression3> .... if <condition(N-1)> else <expressionN>"
},
{
"code": null,
"e": 4790,
"s": 4664,
"text": "It saddens me to see that some programmers abuse this operator only because it is shorter than an explicit if-else statement."
},
{
"code": null,
"e": 5043,
"s": 4790,
"text": "The main reason for the ternary operator is to provide a concise medium for value assignment. It is, therefore, better to use the standard control flow tools when it comes to multiple branching instead of using the operator to write nested expressions."
},
{
"code": null,
"e": 5114,
"s": 5043,
"text": "To quote the author of Python PEP 308 conditional expression proposal:"
},
{
"code": null,
"e": 5228,
"s": 5114,
"text": "“A Python design principle has been to prefer the status quo whenever there are doubts about which path to take.”"
},
{
"code": null,
"e": 5334,
"s": 5228,
"text": "Have you ever wondered what is the difference between a serial if block and anif-else block? For example:"
},
{
"code": null,
"e": 5450,
"s": 5334,
"text": "if <expression1>: statement1if <expression2>: statement2 . . .if <expressionN>: statementN"
},
{
"code": null,
"e": 5455,
"s": 5450,
"text": "and:"
},
{
"code": null,
"e": 5575,
"s": 5455,
"text": "if <expression1>: statement1elif <expression2>: statement2 . . .elif <expressionN>: statementN"
},
{
"code": null,
"e": 5798,
"s": 5575,
"text": "The first time I was introduced to conditional expressions, I didn’t fully understand if-else flowchart. I, as a result, was always using serial if statements since they were always producing expected results. I was wrong!"
},
{
"code": null,
"e": 6063,
"s": 5798,
"text": "While in a serial if block, all the conditions are tested, in an if-elseblock the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block."
},
{
"code": null,
"e": 6187,
"s": 6063,
"text": "That said, when you’re dealing with a case that requires only one condition to be satisfied use if-else if-else statements."
},
{
"code": null,
"e": 6277,
"s": 6187,
"text": "Perhaps we’ve reached the most important section of this post. Nested if-else statements."
},
{
"code": null,
"e": 6448,
"s": 6277,
"text": "The overuse of conditional clauses leads sometimes to deeply nested if-else statements, which are frowned upon by the programming community and regarded as a poor design."
},
{
"code": null,
"e": 6539,
"s": 6448,
"text": "Luckily, there is a way to outmaneuver nested if-else statements. That is decision tables."
},
{
"code": null,
"e": 6684,
"s": 6539,
"text": "To understand how you can make good use of decision tables. We’re going to work on the following code about comparing numbers in respect to 200:"
},
{
"code": null,
"e": 6750,
"s": 6684,
"text": "(This sample is a modified version of a code from tutorialspoint)"
},
{
"code": null,
"e": 6758,
"s": 6750,
"text": "Output:"
},
{
"code": null,
"e": 6809,
"s": 6758,
"text": "Value is less than 200Between 100 and 150It is 125"
},
{
"code": null,
"e": 6957,
"s": 6809,
"text": "Oh boy, we’ve got ourselves a load of if-else statements nested on 3 levels. This is a bad code because it’s lengthy, hard to read and to maintain."
},
{
"code": null,
"e": 7015,
"s": 6957,
"text": "Let’s try to flatten out these nested if-else statements."
},
{
"code": null,
"e": 7142,
"s": 7015,
"text": "But before we do that and to maximize learning outcomes, we’re going to do analyze and jot down remarques from the code above."
},
{
"code": null,
"e": 7394,
"s": 7142,
"text": "The first level of if classifies numbers to greater or less than 200The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150The third level of if prints the number if it’s equal to those in the conditions"
},
{
"code": null,
"e": 7463,
"s": 7394,
"text": "The first level of if classifies numbers to greater or less than 200"
},
{
"code": null,
"e": 7567,
"s": 7463,
"text": "The second level of if classifies numbers to less than 100, less than 150, greater than or equal to 150"
},
{
"code": null,
"e": 7648,
"s": 7567,
"text": "The third level of if prints the number if it’s equal to those in the conditions"
},
{
"code": null,
"e": 7964,
"s": 7648,
"text": "Now, we’ll inject remarque n°2 and n°3 into separate functions. print_interval(val) and print_value(val). Then we’ll store the two nested if-else blocks in two dictionaries (Decision tables). The first one to do the classification as per the remarque n°2. The second one to print the number as per the remarque n°3."
},
{
"code": null,
"e": 8017,
"s": 7964,
"text": "With everything in place, we get the following code:"
},
{
"code": null,
"e": 8025,
"s": 8017,
"text": "Output:"
},
{
"code": null,
"e": 8076,
"s": 8025,
"text": "Value is less than 200Between 100 and 150It is 125"
},
{
"code": null,
"e": 8266,
"s": 8076,
"text": "As you can see we managed to get rid of the nested if-else statements by using functions and decision tables. This has allowed us to write a better-designed code. Readable and maintainable."
},
{
"code": null,
"e": 8467,
"s": 8266,
"text": "Ultimately, you can see that we used a mixture of conditional statements, functions, dictionaries rather than abusing if-else . How to manipulate these, however, is up to you and to your own judgment."
},
{
"code": null,
"e": 8753,
"s": 8467,
"text": "In an effort to help you take your conditional branching skills to the next level, we discussed the pitfalls of if-else statements as well as how to bypass them. The information above is the fruit of 5 years of programming. Still, programming is an infinite realm. that’s why they say:"
}
] |
C++ Program to Perform Inorder Recursive Traversal of a Given Binary Tree | Tree traversal is a form of graph traversal. It involves checking or printing each node in the tree exactly once. The inorder traversal of a binary search tree involves visiting each of the nodes in the tree in the order (Left, Root, Right).
An example of Inorder traversal of a binary tree is as follows.
A binary tree is given as follows.
Inorder Traversal is: 1 4 5 6 8
The program to perform in-order recursive traversal is given as follows.
Live Demo
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}
In-Order traversal of the Binary Search Tree is: 1 2 3 4 5 9
In the above program, the structure node creates the node of a tree. This structure is a self referential structure as it contains pointers of struct node type. This structure is shown as follows.
struct node {
int data;
struct node *left;
struct node *right;
};
The function createNode() creates a node temp and allocates it memory using malloc. The data value val is stored in data of temp. NULL is stored in left and right pointers of temp. This is demonstrated by the following code snippet.
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
The function inorder() takes the root of the binary tree as argument and prints the elements of the tree in inorder. It is a recursive function. It is demonstrated using the following code.
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
The function insertNode() inserts the required value in the binary tree at its correct position. If the node is NULL, then createNode is called. Otherwise, the correct position for the node is found in the tree. This can be observed in the following code snippet.
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
In the main() function, the root node is first defined as NULL. Then all the nodes with the required values are inserted into the binary search tree. This is shown below.
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
Finally, the function inorder() is called using the root node of the tree and all the tree values are displayed in inorder. This is given below.
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root); | [
{
"code": null,
"e": 1304,
"s": 1062,
"text": "Tree traversal is a form of graph traversal. It involves checking or printing each node in the tree exactly once. The inorder traversal of a binary search tree involves visiting each of the nodes in the tree in the order (Left, Root, Right)."
},
{
"code": null,
"e": 1368,
"s": 1304,
"text": "An example of Inorder traversal of a binary tree is as follows."
},
{
"code": null,
"e": 1403,
"s": 1368,
"text": "A binary tree is given as follows."
},
{
"code": null,
"e": 1435,
"s": 1403,
"text": "Inorder Traversal is: 1 4 5 6 8"
},
{
"code": null,
"e": 1508,
"s": 1435,
"text": "The program to perform in-order recursive traversal is given as follows."
},
{
"code": null,
"e": 1519,
"s": 1508,
"text": " Live Demo"
},
{
"code": null,
"e": 2511,
"s": 1519,
"text": "#include<iostream>\nusing namespace std;\nstruct node {\n int data;\n struct node *left;\n struct node *right;\n};\nstruct node *createNode(int val) {\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->data = val;\n temp->left = temp->right = NULL;\n return temp;\n}\nvoid inorder(struct node *root) {\n if (root != NULL) {\n inorder(root->left);\n cout<<root->data<<\" \";\n inorder(root->right);\n }\n}\nstruct node* insertNode(struct node* node, int val) {\n if (node == NULL) return createNode(val);\n if (val < node->data)\n node->left = insertNode(node->left, val);\n else if (val > node->data)\n node->right = insertNode(node->right, val);\n return node;\n}\nint main() {\n struct node *root = NULL;\n root = insertNode(root, 4);\n insertNode(root, 5);\n insertNode(root, 2);\n insertNode(root, 9);\n insertNode(root, 1);\n insertNode(root, 3);\n cout<<\"In-Order traversal of the Binary Search Tree is: \";\n inorder(root);\n return 0;\n}"
},
{
"code": null,
"e": 2572,
"s": 2511,
"text": "In-Order traversal of the Binary Search Tree is: 1 2 3 4 5 9"
},
{
"code": null,
"e": 2769,
"s": 2572,
"text": "In the above program, the structure node creates the node of a tree. This structure is a self referential structure as it contains pointers of struct node type. This structure is shown as follows."
},
{
"code": null,
"e": 2844,
"s": 2769,
"text": "struct node {\n int data;\n struct node *left;\n struct node *right;\n};"
},
{
"code": null,
"e": 3077,
"s": 2844,
"text": "The function createNode() creates a node temp and allocates it memory using malloc. The data value val is stored in data of temp. NULL is stored in left and right pointers of temp. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 3254,
"s": 3077,
"text": "struct node *createNode(int val) {\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->data = val;\n temp->left = temp->right = NULL;\n return temp;\n}"
},
{
"code": null,
"e": 3444,
"s": 3254,
"text": "The function inorder() takes the root of the binary tree as argument and prints the elements of the tree in inorder. It is a recursive function. It is demonstrated using the following code."
},
{
"code": null,
"e": 3592,
"s": 3444,
"text": "void inorder(struct node *root) {\n if (root != NULL) {\n inorder(root->left);\n cout<<root->data<<\" \";\n inorder(root->right);\n }\n}"
},
{
"code": null,
"e": 3856,
"s": 3592,
"text": "The function insertNode() inserts the required value in the binary tree at its correct position. If the node is NULL, then createNode is called. Otherwise, the correct position for the node is found in the tree. This can be observed in the following code snippet."
},
{
"code": null,
"e": 4120,
"s": 3856,
"text": "struct node* insertNode(struct node* node, int val) {\n if (node == NULL) return createNode(val);\n if (val < node->data)\n node->left = insertNode(node->left, val);\n else if (val > node->data)\n node->right = insertNode(node->right, val);\n return node;\n}"
},
{
"code": null,
"e": 4291,
"s": 4120,
"text": "In the main() function, the root node is first defined as NULL. Then all the nodes with the required values are inserted into the binary search tree. This is shown below."
},
{
"code": null,
"e": 4450,
"s": 4291,
"text": "struct node *root = NULL;\nroot = insertNode(root, 4);\ninsertNode(root, 5);\ninsertNode(root, 2);\ninsertNode(root, 9);\ninsertNode(root, 1);\ninsertNode(root, 3);"
},
{
"code": null,
"e": 4595,
"s": 4450,
"text": "Finally, the function inorder() is called using the root node of the tree and all the tree values are displayed in inorder. This is given below."
},
{
"code": null,
"e": 4669,
"s": 4595,
"text": "cout<<\"In-Order traversal of the Binary Search Tree is: \";\ninorder(root);"
}
] |
Leaders in an array | Practice | GeeksforGeeks | Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.
Example 1:
Input:
n = 6
A[] = {16,17,4,3,5,2}
Output: 17 5 2
Explanation: The first leader is 17
as it is greater than all the elements
to its right. Similarly, the next
leader is 5. The right most element
is always a leader so it is also
included.
Example 2:
Input:
n = 5
A[] = {1,2,3,4,0}
Output: 4 0
Your Task:
You don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 <= n <= 107
0 <= Ai <= 107
0
navanee9981 day ago
//C# Solution
public int[] leaders(int[] a, int n) { //Your code here List<int> res = new List<int>(); int p = a[n-1]; res.Add(a[n-1]); for(int i = n-2; i>=0; i--) { if(a[i]>=p) { res.Add(a[i]); p = a[i]; } } res.Reverse(); return res.ToArray(); }
0
logesh7102 days ago
It will not accept (n*n) solution
static ArrayList<Integer> leaders(int arr[], int n){
ArrayList<Integer> ans=new ArrayList<>();
int leadersCount=1;
int ind=n-2;
int high=arr[n-1];
//iterate array from backwards
// higher value put it in high pointer
// decrement higher pointer
for(int i=n-2;i>=0;i--){
if(arr[i]>=high){
high=arr[i];
arr[ind--]=high;
leadersCount++;
}
}
/*
[16, 17, 4, 3, 5, 2] -- 5 and 2 will putted in same place
[16, 17, 4, 17, 5, 2] -- 17 is higher and put it higher place
[16, 17, 4, 17, 5, 2] -- decrement higher pointer
*/
//For print counters
for(int i=n-leadersCount;i<n;i++){
ans.add(arr[i]);
}
return ans;
}
+2
haarisjaved3 days ago
It's so annoying to see people spamming with their solution rather than giving a decent explanation ;))
0
amandeepnirania4 days ago
// accepted vector<int> leaders(int a[], int n){ vector<int> v; int test[n]; test[n-1] = a[n-1]; for(int i = n-2 ; i>=0 ;i--){ test[i]= max(a[i],test[i+1]); } for(int i =0 ;i<n; i++){ if(a[i]>=test[i])v.push_back(a[i]); } return v; }
0
ahmedsamir99sh1005 days ago
//this solution accepted:
class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int ans=0; vector<int> v; for(int i=n-1;i>=0;i--) { if(ans<=a[i]) { ans=a[i]; v.push_back(ans); } } reverse(v.begin(),v.end()); return v; }};
////////////////////////////////////////////////////////////////////
//this solution is right but give you TLE:
class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int sum; int cnt; int mx; vector<int> v; for(int i=0;i<n;i++) { sum=0; cnt=0; for(int j=i+1;j<n;j++) { mx=n-(i+1); if(a[i]>=a[j]) { cnt++; } } if(mx==cnt) { v.push_back(a[i]); } } v.push_back(a[n-1]); return v; }};
0
mittaliraheja025 days ago
vector<int>v; int max_from_right=a[n-1]; v.push_back(a[n-1]); for(int i=n-2;i>=0;i--){ if(a[i]>=max_from_right){ v.push_back(a[i]); max_from_right=a[i]; } } //if(v.size()==0)return v; reverse(v.begin(),v.end()); return v; }
0
amitanand26 days ago
simple sol'n
class Solution{
//Function to find the leaders in the array.
public:
vector<int> leaders(int a[], int n){
// Code here
vector<int>v;
reverse(a , a+n);
int c =0;
v.push_back(a[0]);
for(int i =1 ; i< n ; i++){
// if(*max_element(v.begin() , v.end()) <= a[i]){
// v.push_back(a[i]);
// }
if(a[i] >= v[c]){
v.push_back(a[i]);
c++;
}
}
reverse(v.begin() , v.end());
return v;
}
};
0
kuldeepahirwarmba6 days ago
it shows time limit exceed.
static ArrayList<Integer> leaders(int arr[], int n){ // Your code here boolean isCheck = false; ArrayList<Integer> result = new ArrayList<Integer>(); for(int i =0;i<n;i++) { int j = i; while(j<n) { if (arr[i]>=arr[j]) { isCheck = true; j++; }else{ isCheck = false; break; } } if(isCheck) { result.add(arr[i]); } } return result; }
+1
priyansh708901 week ago
vector<int> leaders(int a[], int n){ // Code here vector<int>ans; int max = a[n-1]; ans.push_back(max); for(int i = n-2;i>=0;i--) { if(max<=a[i]) { max = a[i]; ans.push_back(max); } } reverse(ans.begin(),ans.end()); return ans; }
0
torq12841 week ago
C++ solution
vector<int> leaders(int a[], int n){
// Code here
vector<int> v;
int i,x=0;
for(i=n-1;i>=0;i--)
{
if(x<=a[i])
{
x=a[i];
v.push_back(x);
}
}
reverse(v.begin(), v.end());
return v;
}
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": 467,
"s": 238,
"text": "Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. "
},
{
"code": null,
"e": 480,
"s": 469,
"text": "Example 1:"
},
{
"code": null,
"e": 724,
"s": 480,
"text": "Input:\nn = 6\nA[] = {16,17,4,3,5,2}\nOutput: 17 5 2\nExplanation: The first leader is 17 \nas it is greater than all the elements\nto its right. Similarly, the next \nleader is 5. The right most element \nis always a leader so it is also \nincluded.\n"
},
{
"code": null,
"e": 737,
"s": 726,
"text": "Example 2:"
},
{
"code": null,
"e": 781,
"s": 737,
"text": "Input:\nn = 5\nA[] = {1,2,3,4,0}\nOutput: 4 0\n"
},
{
"code": null,
"e": 996,
"s": 783,
"text": "Your Task:\nYou don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance."
},
{
"code": null,
"e": 1060,
"s": 998,
"text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1104,
"s": 1062,
"text": "Constraints:\n1 <= n <= 107\n0 <= Ai <= 107"
},
{
"code": null,
"e": 1106,
"s": 1104,
"text": "0"
},
{
"code": null,
"e": 1126,
"s": 1106,
"text": "navanee9981 day ago"
},
{
"code": null,
"e": 1140,
"s": 1126,
"text": "//C# Solution"
},
{
"code": null,
"e": 1583,
"s": 1140,
"text": " public int[] leaders(int[] a, int n) { //Your code here List<int> res = new List<int>(); int p = a[n-1]; res.Add(a[n-1]); for(int i = n-2; i>=0; i--) { if(a[i]>=p) { res.Add(a[i]); p = a[i]; } } res.Reverse(); return res.ToArray(); }"
},
{
"code": null,
"e": 1585,
"s": 1583,
"text": "0"
},
{
"code": null,
"e": 1605,
"s": 1585,
"text": "logesh7102 days ago"
},
{
"code": null,
"e": 1639,
"s": 1605,
"text": "It will not accept (n*n) solution"
},
{
"code": null,
"e": 2503,
"s": 1643,
"text": " static ArrayList<Integer> leaders(int arr[], int n){\n \t\n \t ArrayList<Integer> ans=new ArrayList<>();\n int leadersCount=1;\n int ind=n-2;\n int high=arr[n-1];\n \n //iterate array from backwards \n // higher value put it in high pointer\n // decrement higher pointer\n \n for(int i=n-2;i>=0;i--){\n if(arr[i]>=high){\n high=arr[i];\n arr[ind--]=high;\n leadersCount++;\n }\n }\n /*\n [16, 17, 4, 3, 5, 2] -- 5 and 2 will putted in same place\n [16, 17, 4, 17, 5, 2] -- 17 is higher and put it higher place \n [16, 17, 4, 17, 5, 2] -- decrement higher pointer\n */\n //For print counters\n for(int i=n-leadersCount;i<n;i++){\n ans.add(arr[i]);\n }\n return ans;\n }"
},
{
"code": null,
"e": 2510,
"s": 2507,
"text": "+2"
},
{
"code": null,
"e": 2532,
"s": 2510,
"text": "haarisjaved3 days ago"
},
{
"code": null,
"e": 2636,
"s": 2532,
"text": "It's so annoying to see people spamming with their solution rather than giving a decent explanation ;))"
},
{
"code": null,
"e": 2638,
"s": 2636,
"text": "0"
},
{
"code": null,
"e": 2664,
"s": 2638,
"text": "amandeepnirania4 days ago"
},
{
"code": null,
"e": 2983,
"s": 2664,
"text": "// accepted vector<int> leaders(int a[], int n){ vector<int> v; int test[n]; test[n-1] = a[n-1]; for(int i = n-2 ; i>=0 ;i--){ test[i]= max(a[i],test[i+1]); } for(int i =0 ;i<n; i++){ if(a[i]>=test[i])v.push_back(a[i]); } return v; }"
},
{
"code": null,
"e": 2985,
"s": 2983,
"text": "0"
},
{
"code": null,
"e": 3013,
"s": 2985,
"text": "ahmedsamir99sh1005 days ago"
},
{
"code": null,
"e": 3039,
"s": 3013,
"text": "//this solution accepted:"
},
{
"code": null,
"e": 3414,
"s": 3039,
"text": "class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int ans=0; vector<int> v; for(int i=n-1;i>=0;i--) { if(ans<=a[i]) { ans=a[i]; v.push_back(ans); } } reverse(v.begin(),v.end()); return v; }};"
},
{
"code": null,
"e": 3483,
"s": 3414,
"text": "////////////////////////////////////////////////////////////////////"
},
{
"code": null,
"e": 3526,
"s": 3483,
"text": "//this solution is right but give you TLE:"
},
{
"code": null,
"e": 4124,
"s": 3526,
"text": "class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int sum; int cnt; int mx; vector<int> v; for(int i=0;i<n;i++) { sum=0; cnt=0; for(int j=i+1;j<n;j++) { mx=n-(i+1); if(a[i]>=a[j]) { cnt++; } } if(mx==cnt) { v.push_back(a[i]); } } v.push_back(a[n-1]); return v; }};"
},
{
"code": null,
"e": 4126,
"s": 4124,
"text": "0"
},
{
"code": null,
"e": 4152,
"s": 4126,
"text": "mittaliraheja025 days ago"
},
{
"code": null,
"e": 4471,
"s": 4152,
"text": " vector<int>v; int max_from_right=a[n-1]; v.push_back(a[n-1]); for(int i=n-2;i>=0;i--){ if(a[i]>=max_from_right){ v.push_back(a[i]); max_from_right=a[i]; } } //if(v.size()==0)return v; reverse(v.begin(),v.end()); return v; }"
},
{
"code": null,
"e": 4473,
"s": 4471,
"text": "0"
},
{
"code": null,
"e": 4494,
"s": 4473,
"text": "amitanand26 days ago"
},
{
"code": null,
"e": 4507,
"s": 4494,
"text": "simple sol'n"
},
{
"code": null,
"e": 5077,
"s": 4507,
"text": "\nclass Solution{\n //Function to find the leaders in the array.\n public:\n vector<int> leaders(int a[], int n){\n // Code here\n vector<int>v;\n reverse(a , a+n);\n int c =0;\n v.push_back(a[0]);\n for(int i =1 ; i< n ; i++){\n // if(*max_element(v.begin() , v.end()) <= a[i]){\n // v.push_back(a[i]);\n // }\n if(a[i] >= v[c]){\n v.push_back(a[i]);\n c++;\n }\n }\n reverse(v.begin() , v.end());\n return v;\n \n }\n};"
},
{
"code": null,
"e": 5079,
"s": 5077,
"text": "0"
},
{
"code": null,
"e": 5107,
"s": 5079,
"text": "kuldeepahirwarmba6 days ago"
},
{
"code": null,
"e": 5135,
"s": 5107,
"text": "it shows time limit exceed."
},
{
"code": null,
"e": 5722,
"s": 5135,
"text": "static ArrayList<Integer> leaders(int arr[], int n){ // Your code here boolean isCheck = false; ArrayList<Integer> result = new ArrayList<Integer>(); for(int i =0;i<n;i++) { int j = i; while(j<n) { if (arr[i]>=arr[j]) { isCheck = true; j++; }else{ isCheck = false; break; } } if(isCheck) { result.add(arr[i]); } } return result; }"
},
{
"code": null,
"e": 5725,
"s": 5722,
"text": "+1"
},
{
"code": null,
"e": 5749,
"s": 5725,
"text": "priyansh708901 week ago"
},
{
"code": null,
"e": 6097,
"s": 5749,
"text": " vector<int> leaders(int a[], int n){ // Code here vector<int>ans; int max = a[n-1]; ans.push_back(max); for(int i = n-2;i>=0;i--) { if(max<=a[i]) { max = a[i]; ans.push_back(max); } } reverse(ans.begin(),ans.end()); return ans; }"
},
{
"code": null,
"e": 6099,
"s": 6097,
"text": "0"
},
{
"code": null,
"e": 6118,
"s": 6099,
"text": "torq12841 week ago"
},
{
"code": null,
"e": 6132,
"s": 6118,
"text": "C++ solution "
},
{
"code": null,
"e": 6467,
"s": 6132,
"text": "vector<int> leaders(int a[], int n){\n // Code here\n vector<int> v;\n int i,x=0;\n for(i=n-1;i>=0;i--)\n {\n if(x<=a[i])\n {\n x=a[i];\n v.push_back(x);\n }\n }\n reverse(v.begin(), v.end());\n return v;\n \n \n }"
},
{
"code": null,
"e": 6613,
"s": 6467,
"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": 6649,
"s": 6613,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6659,
"s": 6649,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6669,
"s": 6659,
"text": "\nContest\n"
},
{
"code": null,
"e": 6732,
"s": 6669,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6880,
"s": 6732,
"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": 7088,
"s": 6880,
"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": 7194,
"s": 7088,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C | Functions | Question 8 - GeeksforGeeks | 28 Jun, 2021
What is the meaning of using extern before function declaration?
For example following function sum is made extern
extern int sum(int x, int y, int z)
{
return (x + y + z);
}
(A) Function is made globally available(B) extern means nothing, sum() is same without extern keyword.(C) Function need not to be declared before its use(D) Function is made local to the file.Answer: (B)Explanation: extern keyword is used for global variables. Functions are global anyways, so adding extern doesn’t add anything.Quiz of this Question
C-Functions
Functions
C Language
C Quiz
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
Substring in C++
TCP Server-Client implementation in C
Enumeration (or enum) in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | Pointer Basics | Question 15
C | Misc | Question 7
C | File Handling | Question 1 | [
{
"code": null,
"e": 24478,
"s": 24450,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24543,
"s": 24478,
"text": "What is the meaning of using extern before function declaration?"
},
{
"code": null,
"e": 24593,
"s": 24543,
"text": "For example following function sum is made extern"
},
{
"code": null,
"e": 24657,
"s": 24593,
"text": "extern int sum(int x, int y, int z)\n{\n return (x + y + z);\n}"
},
{
"code": null,
"e": 25008,
"s": 24657,
"text": "(A) Function is made globally available(B) extern means nothing, sum() is same without extern keyword.(C) Function need not to be declared before its use(D) Function is made local to the file.Answer: (B)Explanation: extern keyword is used for global variables. Functions are global anyways, so adding extern doesn’t add anything.Quiz of this Question"
},
{
"code": null,
"e": 25020,
"s": 25008,
"text": "C-Functions"
},
{
"code": null,
"e": 25030,
"s": 25020,
"text": "Functions"
},
{
"code": null,
"e": 25041,
"s": 25030,
"text": "C Language"
},
{
"code": null,
"e": 25048,
"s": 25041,
"text": "C Quiz"
},
{
"code": null,
"e": 25058,
"s": 25048,
"text": "Functions"
},
{
"code": null,
"e": 25156,
"s": 25058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25168,
"s": 25156,
"text": "fork() in C"
},
{
"code": null,
"e": 25190,
"s": 25168,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25207,
"s": 25190,
"text": "Substring in C++"
},
{
"code": null,
"e": 25245,
"s": 25207,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25272,
"s": 25245,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 25314,
"s": 25272,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25357,
"s": 25314,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25390,
"s": 25357,
"text": "C | Pointer Basics | Question 15"
},
{
"code": null,
"e": 25412,
"s": 25390,
"text": "C | Misc | Question 7"
}
] |
Importing DynamoDB Data Using Apache Hive on Amazon EMR | by Yi Ai | Towards Data Science | This article describes one of the many ways to import data into AWS DynamoDB database. The option explained here uses Amazon EMR and Hive. Using Amazon EMR and Hive you can quickly and efficiently process large amounts of data, such as importing data from Amazon S3 into a DynamoDB table.
Every day an external datasource sends a csv file with about 1000 records to S3 bucket.A lambda function that will get triggered when an csv object is placed into an S3 bucket.Lambda function will start a EMR job with steps includes:
Every day an external datasource sends a csv file with about 1000 records to S3 bucket.
A lambda function that will get triggered when an csv object is placed into an S3 bucket.
Lambda function will start a EMR job with steps includes:
Create a Hive table that references data stored in DynamoDB.
Creating a hive table that references a location in Amazon S3.
Load data form S3 table to DynamoDB table.
The following diagram shows the architecture of the process.
Basic understanding of CloudFormation.
Basic understanding of EMR.
Setup an AWS account.
Install Serverless Framework.
Before getting started, Install the Serverless Framework. Open up a terminal and type npm install -g serverless.
There is a yml file (serverless.yml) in the project directory. Let’s start to define a set of objects in template file as below:
There are 2 S3 buckets, LogBucket is for EMR logs, S3BucketCsvimport is to store csv files.
A DynamoDB table to load csv data from S3.
Adding lambda function configuration to serverless.yml. it will be triggered by S3 new objected created event, the lambda function will then start a EMR job flow to process data importing.
We also need to create IAM role for the lambda function, so our lambda function has permission to start EMR job flow.
Let’s add a lambda function to create an AWS EMR cluster and adding the step details such as the location of the hive scripts, arguments etc. We can use the boto3 lib for EMR, in order to create a cluster and submit the job dynamically from lambda function.
Ad finally...let’s add Hive script.
We will create an external Hive table that maps to the csv data file.
Establish a mapping between Hive and the Features table in DynamoDB.
Add current date as partition and load table with csv data in S3.
Using following Hive script to write data from Amazon S3 to DynamoDB.
Note that Amazon EMR operations on a DynamoDB table count as read/write operations, and are subject to the table’s provisioned throughput settings. for more details please visit EMR document.
$sls deploy --stage dev
After script deployed, copy a csv file to S3 bucket with created_date={CURRENT_DATE}prefix, eg.
$aws s3 cp csv/contacts.csv s3://myemr.csv.import.dev/uploads/created_date=2020-02-03/contacts.csv
Then we can go to AWS EMR console and check the progress of the EMR steps.
It will take several minutes to complete all the steps and cluster will terminate automatically after running above steps.
Next We can go to AWS DynamoDB console to verify that the data has been loaded into DynamoDB:
Eventually Importing process took about 6 mins to load 1000 records total 76kb into DynamoDB table with write capacity units 10 and no auto scaling enabled.
That’s about it, Thanks for reading!
I hope you have found this article useful, You can find the complete project in my GitHub repo. | [
{
"code": null,
"e": 460,
"s": 171,
"text": "This article describes one of the many ways to import data into AWS DynamoDB database. The option explained here uses Amazon EMR and Hive. Using Amazon EMR and Hive you can quickly and efficiently process large amounts of data, such as importing data from Amazon S3 into a DynamoDB table."
},
{
"code": null,
"e": 694,
"s": 460,
"text": "Every day an external datasource sends a csv file with about 1000 records to S3 bucket.A lambda function that will get triggered when an csv object is placed into an S3 bucket.Lambda function will start a EMR job with steps includes:"
},
{
"code": null,
"e": 782,
"s": 694,
"text": "Every day an external datasource sends a csv file with about 1000 records to S3 bucket."
},
{
"code": null,
"e": 872,
"s": 782,
"text": "A lambda function that will get triggered when an csv object is placed into an S3 bucket."
},
{
"code": null,
"e": 930,
"s": 872,
"text": "Lambda function will start a EMR job with steps includes:"
},
{
"code": null,
"e": 991,
"s": 930,
"text": "Create a Hive table that references data stored in DynamoDB."
},
{
"code": null,
"e": 1054,
"s": 991,
"text": "Creating a hive table that references a location in Amazon S3."
},
{
"code": null,
"e": 1097,
"s": 1054,
"text": "Load data form S3 table to DynamoDB table."
},
{
"code": null,
"e": 1158,
"s": 1097,
"text": "The following diagram shows the architecture of the process."
},
{
"code": null,
"e": 1197,
"s": 1158,
"text": "Basic understanding of CloudFormation."
},
{
"code": null,
"e": 1225,
"s": 1197,
"text": "Basic understanding of EMR."
},
{
"code": null,
"e": 1247,
"s": 1225,
"text": "Setup an AWS account."
},
{
"code": null,
"e": 1277,
"s": 1247,
"text": "Install Serverless Framework."
},
{
"code": null,
"e": 1390,
"s": 1277,
"text": "Before getting started, Install the Serverless Framework. Open up a terminal and type npm install -g serverless."
},
{
"code": null,
"e": 1519,
"s": 1390,
"text": "There is a yml file (serverless.yml) in the project directory. Let’s start to define a set of objects in template file as below:"
},
{
"code": null,
"e": 1611,
"s": 1519,
"text": "There are 2 S3 buckets, LogBucket is for EMR logs, S3BucketCsvimport is to store csv files."
},
{
"code": null,
"e": 1654,
"s": 1611,
"text": "A DynamoDB table to load csv data from S3."
},
{
"code": null,
"e": 1843,
"s": 1654,
"text": "Adding lambda function configuration to serverless.yml. it will be triggered by S3 new objected created event, the lambda function will then start a EMR job flow to process data importing."
},
{
"code": null,
"e": 1961,
"s": 1843,
"text": "We also need to create IAM role for the lambda function, so our lambda function has permission to start EMR job flow."
},
{
"code": null,
"e": 2219,
"s": 1961,
"text": "Let’s add a lambda function to create an AWS EMR cluster and adding the step details such as the location of the hive scripts, arguments etc. We can use the boto3 lib for EMR, in order to create a cluster and submit the job dynamically from lambda function."
},
{
"code": null,
"e": 2255,
"s": 2219,
"text": "Ad finally...let’s add Hive script."
},
{
"code": null,
"e": 2325,
"s": 2255,
"text": "We will create an external Hive table that maps to the csv data file."
},
{
"code": null,
"e": 2394,
"s": 2325,
"text": "Establish a mapping between Hive and the Features table in DynamoDB."
},
{
"code": null,
"e": 2460,
"s": 2394,
"text": "Add current date as partition and load table with csv data in S3."
},
{
"code": null,
"e": 2530,
"s": 2460,
"text": "Using following Hive script to write data from Amazon S3 to DynamoDB."
},
{
"code": null,
"e": 2722,
"s": 2530,
"text": "Note that Amazon EMR operations on a DynamoDB table count as read/write operations, and are subject to the table’s provisioned throughput settings. for more details please visit EMR document."
},
{
"code": null,
"e": 2746,
"s": 2722,
"text": "$sls deploy --stage dev"
},
{
"code": null,
"e": 2842,
"s": 2746,
"text": "After script deployed, copy a csv file to S3 bucket with created_date={CURRENT_DATE}prefix, eg."
},
{
"code": null,
"e": 2941,
"s": 2842,
"text": "$aws s3 cp csv/contacts.csv s3://myemr.csv.import.dev/uploads/created_date=2020-02-03/contacts.csv"
},
{
"code": null,
"e": 3016,
"s": 2941,
"text": "Then we can go to AWS EMR console and check the progress of the EMR steps."
},
{
"code": null,
"e": 3139,
"s": 3016,
"text": "It will take several minutes to complete all the steps and cluster will terminate automatically after running above steps."
},
{
"code": null,
"e": 3233,
"s": 3139,
"text": "Next We can go to AWS DynamoDB console to verify that the data has been loaded into DynamoDB:"
},
{
"code": null,
"e": 3390,
"s": 3233,
"text": "Eventually Importing process took about 6 mins to load 1000 records total 76kb into DynamoDB table with write capacity units 10 and no auto scaling enabled."
},
{
"code": null,
"e": 3427,
"s": 3390,
"text": "That’s about it, Thanks for reading!"
}
] |
Matplotlib.axes.Axes.properties() in Python - GeeksforGeeks | 30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.properties() function in axes module of matplotlib library is used to get the dictionary of all the properties of the artist..
Syntax: Axes.properties(self)
Parameters: This method does not accepts any parameters.
Returns: This method return dictionary of all the properties of the artist.
Below examples illustrate the matplotlib.axes.Axes.properties() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt xx = np.random.rand(16, 30) fig, ax = plt.subplots() m = ax.pcolor(xx) m.set_zorder(-20) w = ax.properties()print("Display all Properties\n")for i in w: print(i, ":", w[i]) fig.suptitle('matplotlib.axes.Axes.properties()\ function Example', fontweight ="bold") plt.show()
Output:
Display all Properties
adjustable : boxagg_filter : Nonealpha : Noneanchor : Canimated : Falseaspect : autoautoscale_on : Trueautoscalex_on : Trueautoscaley_on : Trueaxes_locator : Noneaxisbelow : linechildren : [,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]clip_box : Noneclip_on : Trueclip_path : Nonecontains : Nonedata_ratio : 0.5333333333333333default_bbox_extra_artists : [,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]facecolor : (1.0, 1.0, 1.0, 1.0)fc : (1.0, 1.0, 1.0, 1.0)figure : Figure(640×480)frame_on : Truegeometry : (1, 1, 1)gid : Nonegridspec : GridSpec(1, 1)images : <a>in_layout : Truelabel :legend : Nonelegend_handles_labels : ([], [])lines : <a>navigate : Truenavigate_mode : Nonepath_effects : []picker : Noneposition : Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)rasterization_zorder : Nonerasterized : Nonerenderer_cache : Noneshared_x_axes :shared_y_axes :sketch_params : Nonesnap : Nonesubplotspec :title :transform : IdentityTransform()transformed_clip_path_and_affine : (None, None)url : Nonevisible : Truewindow_extent : TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))xaxis : XAxis(80.0, 52.8)xaxis_transform : BlendedGenericTransform(CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=30.0, y1=16.0),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))xbound : (0.0, 30.0)xgridlines : <a>xlabel :xlim : (0.0, 30.0)xmajorticklabels : <a>xminorticklabels : <a>xscale : linearxticklabels : <a>xticklines : <a>xticks : [ 0. 5. 10. 15. 20. 25. 30.]yaxis : YAxis(80.0, 52.8)yaxis_transform : BlendedGenericTransform(BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))),CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=30.0, y1=16.0),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))))ybound : (0.0, 16.0)ygridlines : <a>ylabel :ylim : (0.0, 16.0)ymajorticklabels : <a>yminorticklabels : <a>yscale : linearyticklabels : <a>yticklines : <a>yticks : [ 0. 2. 4. 6. 8. 10. 12. 14. 16.]zorder : 0
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7)geeks = np.random.randn(100) fig, ax = plt.subplots()ax.acorr(geeks, usevlines = True, normed = True, maxlags = 80, lw = 3) ax.grid(True) w = ax.properties()print("Display all Properties\n")for i in w: print(i, ":", w[i]) fig.suptitle('matplotlib.axes.Axes.properties()\function Example', fontweight ="bold") plt.show()
Output:
Display all Properties
adjustable : boxagg_filter : Nonealpha : Noneanchor : Canimated : Falseaspect : autoautoscale_on : Trueautoscalex_on : Trueautoscaley_on : Trueaxes_locator : Noneaxisbelow : linechildren : [,,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]clip_box : Noneclip_on : Trueclip_path : Nonecontains : Nonedata_ratio : 0.007741698372824119default_bbox_extra_artists : [,,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]facecolor : (1.0, 1.0, 1.0, 1.0)fc : (1.0, 1.0, 1.0, 1.0)figure : Figure(640×480)frame_on : Truegeometry : (1, 1, 1)gid : Nonegridspec : GridSpec(1, 1)images : <a>in_layout : Truelabel :legend : Nonelegend_handles_labels : ([], [])lines : <a>navigate : Truenavigate_mode : Nonepath_effects : []picker : Noneposition : Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)rasterization_zorder : Nonerasterized : Nonerenderer_cache : Noneshared_x_axes :shared_y_axes :sketch_params : Nonesnap : Nonesubplotspec :title :transform : IdentityTransform()transformed_clip_path_and_affine : (None, None)url : Nonevisible : Truewindow_extent : TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))xaxis : XAxis(80.0, 52.8)xaxis_transform : BlendedGenericTransform(CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=-88.0, y0=-0.300605326634452, x1=88.0, y1=1.061933586982593),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))xbound : (-88.0, 88.0)xgridlines : <a>xlabel :xlim : (-88.0, 88.0)xmajorticklabels : <a>xminorticklabels : <a>xscale : linearxticklabels : <a>xticklines : <a>xticks : [-100. -80. -60. -40. -20. 0. 20. 40. 60. 80. 100.]yaxis : YAxis(80.0, 52.8)yaxis_transform : BlendedGenericTransform(BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))),CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=-88.0, y0=-0.300605326634452, x1=88.0, y1=1.061933586982593),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))))ybound : (-0.300605326634452, 1.061933586982593)ygridlines : <a>ylabel :ylim : (-0.300605326634452, 1.061933586982593)ymajorticklabels : <a>yminorticklabels : <a>yscale : linearyticklabels : <a>yticklines : <a>yticks : [-0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. 1.2]zorder : 0
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24225,
"s": 24197,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 24525,
"s": 24225,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 24661,
"s": 24525,
"text": "The Axes.properties() function in axes module of matplotlib library is used to get the dictionary of all the properties of the artist.."
},
{
"code": null,
"e": 24691,
"s": 24661,
"text": "Syntax: Axes.properties(self)"
},
{
"code": null,
"e": 24748,
"s": 24691,
"text": "Parameters: This method does not accepts any parameters."
},
{
"code": null,
"e": 24824,
"s": 24748,
"text": "Returns: This method return dictionary of all the properties of the artist."
},
{
"code": null,
"e": 24917,
"s": 24824,
"text": "Below examples illustrate the matplotlib.axes.Axes.properties() function in matplotlib.axes:"
},
{
"code": null,
"e": 24928,
"s": 24917,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt xx = np.random.rand(16, 30) fig, ax = plt.subplots() m = ax.pcolor(xx) m.set_zorder(-20) w = ax.properties()print(\"Display all Properties\\n\")for i in w: print(i, \":\", w[i]) fig.suptitle('matplotlib.axes.Axes.properties()\\ function Example', fontweight =\"bold\") plt.show() ",
"e": 25318,
"s": 24928,
"text": null
},
{
"code": null,
"e": 25326,
"s": 25318,
"text": "Output:"
},
{
"code": null,
"e": 25349,
"s": 25326,
"text": "Display all Properties"
},
{
"code": null,
"e": 28551,
"s": 25349,
"text": "adjustable : boxagg_filter : Nonealpha : Noneanchor : Canimated : Falseaspect : autoautoscale_on : Trueautoscalex_on : Trueautoscaley_on : Trueaxes_locator : Noneaxisbelow : linechildren : [,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]clip_box : Noneclip_on : Trueclip_path : Nonecontains : Nonedata_ratio : 0.5333333333333333default_bbox_extra_artists : [,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]facecolor : (1.0, 1.0, 1.0, 1.0)fc : (1.0, 1.0, 1.0, 1.0)figure : Figure(640×480)frame_on : Truegeometry : (1, 1, 1)gid : Nonegridspec : GridSpec(1, 1)images : <a>in_layout : Truelabel :legend : Nonelegend_handles_labels : ([], [])lines : <a>navigate : Truenavigate_mode : Nonepath_effects : []picker : Noneposition : Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)rasterization_zorder : Nonerasterized : Nonerenderer_cache : Noneshared_x_axes :shared_y_axes :sketch_params : Nonesnap : Nonesubplotspec :title :transform : IdentityTransform()transformed_clip_path_and_affine : (None, None)url : Nonevisible : Truewindow_extent : TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))xaxis : XAxis(80.0, 52.8)xaxis_transform : BlendedGenericTransform(CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=30.0, y1=16.0),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))xbound : (0.0, 30.0)xgridlines : <a>xlabel :xlim : (0.0, 30.0)xmajorticklabels : <a>xminorticklabels : <a>xscale : linearxticklabels : <a>xticklines : <a>xticks : [ 0. 5. 10. 15. 20. 25. 30.]yaxis : YAxis(80.0, 52.8)yaxis_transform : BlendedGenericTransform(BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))),CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=30.0, y1=16.0),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))))ybound : (0.0, 16.0)ygridlines : <a>ylabel :ylim : (0.0, 16.0)ymajorticklabels : <a>yminorticklabels : <a>yscale : linearyticklabels : <a>yticklines : <a>yticks : [ 0. 2. 4. 6. 8. 10. 12. 14. 16.]zorder : 0"
},
{
"code": null,
"e": 28562,
"s": 28551,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7)geeks = np.random.randn(100) fig, ax = plt.subplots()ax.acorr(geeks, usevlines = True, normed = True, maxlags = 80, lw = 3) ax.grid(True) w = ax.properties()print(\"Display all Properties\\n\")for i in w: print(i, \":\", w[i]) fig.suptitle('matplotlib.axes.Axes.properties()\\function Example', fontweight =\"bold\") plt.show() ",
"e": 29027,
"s": 28562,
"text": null
},
{
"code": null,
"e": 29035,
"s": 29027,
"text": "Output:"
},
{
"code": null,
"e": 29058,
"s": 29035,
"text": "Display all Properties"
},
{
"code": null,
"e": 32411,
"s": 29058,
"text": "adjustable : boxagg_filter : Nonealpha : Noneanchor : Canimated : Falseaspect : autoautoscale_on : Trueautoscalex_on : Trueautoscaley_on : Trueaxes_locator : Noneaxisbelow : linechildren : [,,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]clip_box : Noneclip_on : Trueclip_path : Nonecontains : Nonedata_ratio : 0.007741698372824119default_bbox_extra_artists : [,,,,,,,, Text(0.5, 1.0, ”), Text(0.0, 1.0, ”), Text(1.0, 1.0, ”), ]facecolor : (1.0, 1.0, 1.0, 1.0)fc : (1.0, 1.0, 1.0, 1.0)figure : Figure(640×480)frame_on : Truegeometry : (1, 1, 1)gid : Nonegridspec : GridSpec(1, 1)images : <a>in_layout : Truelabel :legend : Nonelegend_handles_labels : ([], [])lines : <a>navigate : Truenavigate_mode : Nonepath_effects : []picker : Noneposition : Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)rasterization_zorder : Nonerasterized : Nonerenderer_cache : Noneshared_x_axes :shared_y_axes :sketch_params : Nonesnap : Nonesubplotspec :title :transform : IdentityTransform()transformed_clip_path_and_affine : (None, None)url : Nonevisible : Truewindow_extent : TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))xaxis : XAxis(80.0, 52.8)xaxis_transform : BlendedGenericTransform(CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=-88.0, y0=-0.300605326634452, x1=88.0, y1=1.061933586982593),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))xbound : (-88.0, 88.0)xgridlines : <a>xlabel :xlim : (-88.0, 88.0)xmajorticklabels : <a>xminorticklabels : <a>xscale : linearxticklabels : <a>xticklines : <a>xticks : [-100. -80. -60. -40. -20. 0. 20. 40. 60. 80. 100.]yaxis : YAxis(80.0, 52.8)yaxis_transform : BlendedGenericTransform(BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))),CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())),CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox(x0=-88.0, y0=-0.300605326634452, x1=88.0, y1=1.061933586982593),TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))),BboxTransformTo(TransformedBbox(Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88),BboxTransformTo(TransformedBbox(Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8),Affine2D([[100. 0. 0.][ 0. 100. 0.][ 0. 0. 1.]]))))))))ybound : (-0.300605326634452, 1.061933586982593)ygridlines : <a>ylabel :ylim : (-0.300605326634452, 1.061933586982593)ymajorticklabels : <a>yminorticklabels : <a>yscale : linearyticklabels : <a>yticklines : <a>yticks : [-0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. 1.2]zorder : 0"
},
{
"code": null,
"e": 32433,
"s": 32411,
"text": "Matplotlib axes-class"
},
{
"code": null,
"e": 32451,
"s": 32433,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 32458,
"s": 32451,
"text": "Python"
},
{
"code": null,
"e": 32556,
"s": 32458,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32565,
"s": 32556,
"text": "Comments"
},
{
"code": null,
"e": 32578,
"s": 32565,
"text": "Old Comments"
},
{
"code": null,
"e": 32596,
"s": 32578,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32631,
"s": 32596,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 32653,
"s": 32631,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32685,
"s": 32653,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32715,
"s": 32685,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 32757,
"s": 32715,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32800,
"s": 32757,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 32826,
"s": 32800,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32870,
"s": 32826,
"text": "Reading and Writing to text files in Python"
}
] |
How can we use MySQL SUM() function with HAVING clause? | By using MySQL SUM() function with the HAVING clause, it filters the result based on a specific condition given after the HAVING clause. To understand the above concept, consider an ‘employee_tbl’ table, which is having the following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, the query below will use the HAVING clause with SUM() function to get the total of daily_typing_pages which are more than 250.
mysql> Select Name, SUM(daily_typing_pages) From employee_tbl GROUP BY NAME HAVING SUM(daily_typing_pages) > 250;
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack | 270 |
| Zara | 650 |
+------+-------------------------+
2 rows in set (0.17 sec) | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "By using MySQL SUM() function with the HAVING clause, it filters the result based on a specific condition given after the HAVING clause. To understand the above concept, consider an ‘employee_tbl’ table, which is having the following records −"
},
{
"code": null,
"e": 1916,
"s": 1306,
"text": "mysql> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2048,
"s": 1916,
"text": "Now, the query below will use the HAVING clause with SUM() function to get the total of daily_typing_pages which are more than 250."
},
{
"code": null,
"e": 2397,
"s": 2048,
"text": "mysql> Select Name, SUM(daily_typing_pages) From employee_tbl GROUP BY NAME HAVING SUM(daily_typing_pages) > 250;\n+------+-------------------------+\n| name | SUM(daily_typing_pages) |\n+------+-------------------------+\n| Jack | 270 |\n| Zara | 650 |\n+------+-------------------------+\n2 rows in set (0.17 sec)"
}
] |
Solidity - Arrays | Array is a data structure, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
In Solidity, an array can be of compile-time fixed size or of dynamic size. For storage array, it can have different types of elements as well. In case of memory array, element type can not be mapping and in case it is to be used as function parameter then element type should be an ABI type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array of fixed size in Solidity, the programmer specifies the type of the elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid Solidity data type. For example, to declare a 10-element array called balance of type uint, use this statement −
uint balance[10];
To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows −
type[] arrayName;
You can initialize Solidity array elements either one by one or using a single statement as follows −
uint balance[3] = [1, 2, 3];
The number of values between braces [ ] can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
uint balance[] = [1, 2, 3];
You will create exactly the same array as you did in the previous example.
balance[2] = 5;
The above statement assigns element number 3rd in the array a value of 5.
Dynamic memory arrays are created using new keyword.
uint size = 3;
uint balance[] = new uint[](size);
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
uint salary = balance[2];
The above statement will take 3rd element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −
length − length returns the size of the array. length can be used to change the size of dynamic array be setting it.
length − length returns the size of the array. length can be used to change the size of dynamic array be setting it.
push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array.
push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array.
Try the following code to understand how the arrays works in Solidity.
pragma solidity ^0.5.0;
contract test {
function testArray() public pure{
uint len = 7;
//dynamic array
uint[] memory a = new uint[](7);
//bytes is same as byte[]
bytes memory b = new bytes(len);
assert(a.length == 7);
assert(b.length == len);
//access array variable
a[6] = 8;
//test array variable
assert(a[6] == 8);
//static array
uint[3] memory c = [uint(1) , 2, 3];
assert(c.length == 3);
}
}
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2804,
"s": 2555,
"text": "Array is a data structure, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 3084,
"s": 2804,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. "
},
{
"code": null,
"e": 3377,
"s": 3084,
"text": "In Solidity, an array can be of compile-time fixed size or of dynamic size. For storage array, it can have different types of elements as well. In case of memory array, element type can not be mapping and in case it is to be used as function parameter then element type should be an ABI type."
},
{
"code": null,
"e": 3525,
"s": 3377,
"text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element."
},
{
"code": null,
"e": 3683,
"s": 3525,
"text": "To declare an array of fixed size in Solidity, the programmer specifies the type of the elements and the number of elements required by an array as follows −"
},
{
"code": null,
"e": 3714,
"s": 3683,
"text": "type arrayName [ arraySize ];\n"
},
{
"code": null,
"e": 3954,
"s": 3714,
"text": "This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid Solidity data type. For example, to declare a 10-element array called balance of type uint, use this statement −"
},
{
"code": null,
"e": 3973,
"s": 3954,
"text": "uint balance[10];\n"
},
{
"code": null,
"e": 4085,
"s": 3973,
"text": "To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows −"
},
{
"code": null,
"e": 4104,
"s": 4085,
"text": "type[] arrayName;\n"
},
{
"code": null,
"e": 4206,
"s": 4104,
"text": "You can initialize Solidity array elements either one by one or using a single statement as follows −"
},
{
"code": null,
"e": 4236,
"s": 4206,
"text": "uint balance[3] = [1, 2, 3];\n"
},
{
"code": null,
"e": 4447,
"s": 4236,
"text": "The number of values between braces [ ] can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −"
},
{
"code": null,
"e": 4573,
"s": 4447,
"text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −"
},
{
"code": null,
"e": 4602,
"s": 4573,
"text": "uint balance[] = [1, 2, 3];\n"
},
{
"code": null,
"e": 4677,
"s": 4602,
"text": "You will create exactly the same array as you did in the previous example."
},
{
"code": null,
"e": 4694,
"s": 4677,
"text": "balance[2] = 5;\n"
},
{
"code": null,
"e": 4769,
"s": 4694,
"text": "The above statement assigns element number 3rd in the array a value of 5. "
},
{
"code": null,
"e": 4822,
"s": 4769,
"text": "Dynamic memory arrays are created using new keyword."
},
{
"code": null,
"e": 4873,
"s": 4822,
"text": "uint size = 3;\nuint balance[] = new uint[](size);\n"
},
{
"code": null,
"e": 5039,
"s": 4873,
"text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −"
},
{
"code": null,
"e": 5066,
"s": 5039,
"text": "uint salary = balance[2];\n"
},
{
"code": null,
"e": 5295,
"s": 5066,
"text": "The above statement will take 3rd element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −"
},
{
"code": null,
"e": 5412,
"s": 5295,
"text": "length − length returns the size of the array. length can be used to change the size of dynamic array be setting it."
},
{
"code": null,
"e": 5529,
"s": 5412,
"text": "length − length returns the size of the array. length can be used to change the size of dynamic array be setting it."
},
{
"code": null,
"e": 5648,
"s": 5529,
"text": "push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array."
},
{
"code": null,
"e": 5767,
"s": 5648,
"text": "push − push allows to append an element to a dynamic storage array at the end. It returns the new length of the array."
},
{
"code": null,
"e": 5838,
"s": 5767,
"text": "Try the following code to understand how the arrays works in Solidity."
},
{
"code": null,
"e": 6370,
"s": 5838,
"text": "pragma solidity ^0.5.0;\n\ncontract test {\n function testArray() public pure{\n uint len = 7; \n \n //dynamic array\n uint[] memory a = new uint[](7);\n \n //bytes is same as byte[]\n bytes memory b = new bytes(len);\n \n assert(a.length == 7);\n assert(b.length == len);\n \n //access array variable\n a[6] = 8;\n \n //test array variable\n assert(a[6] == 8);\n \n //static array\n uint[3] memory c = [uint(1) , 2, 3];\n assert(c.length == 3);\n }\n}"
},
{
"code": null,
"e": 6405,
"s": 6370,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6422,
"s": 6405,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6457,
"s": 6422,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6474,
"s": 6457,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6509,
"s": 6474,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6523,
"s": 6509,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 6530,
"s": 6523,
"text": " Print"
},
{
"code": null,
"e": 6541,
"s": 6530,
"text": " Add Notes"
}
] |
Check if all levels of two trees are anagrams or not - GeeksforGeeks | 15 Sep, 2021
Given two binary trees, we have to check if each of their levels are anagrams of each other or not. Example:
Tree 1:
Level 0 : 1
Level 1 : 3, 2
Level 2 : 5, 4
Tree 2:
Level 0 : 1
Level 1 : 2, 3
Level 2 : 4, 5
As we can clearly see all the levels of above two binary trees are anagrams of each other, hence return true.
Naive Approach: Below is the step by step explanation of the naive approach to do this:
Write a recursive program for level order traversal of a tree.Traverse each level of both the trees one by one and store the result of traversals in 2 different vectors, one for each tree.Sort both the vectors and compare them iteratively for each level, if they are same for each level then return true else return false.
Write a recursive program for level order traversal of a tree.
Traverse each level of both the trees one by one and store the result of traversals in 2 different vectors, one for each tree.
Sort both the vectors and compare them iteratively for each level, if they are same for each level then return true else return false.
Time Complexity: O(n^2), where n is the number of nodes.Efficient Approach: The idea is based on below article. Print level order traversal line by line | Set 1 We traverse both trees simultaneously level by level. We store each level both trees in vectors (or array). To check if two vectors are anagram or not, we sort both and then compare.Time Complexity: O(nlogn), where n is the number of nodes.
C++
Java
Python3
C#
/* Iterative program to check if two trees are level by level anagram. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int data;}; // Returns true if trees with root1 and root2// are level by level anagram, else returns false.bool areAnagrams(Node *root1, Node *root2){ // Base Cases if (root1 == NULL && root2 == NULL) return true; if (root1 == NULL || root2 == NULL) return false; // start level order traversal of two trees // using two queues. queue<Node *> q1, q2; q1.push(root1); q2.push(root2); while (1) { // n1 (queue size) indicates number of Nodes // at current level in first tree and n2 indicates // number of nodes in current level of second tree. int n1 = q1.size(), n2 = q2.size(); // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level vector<int> curr_level1, curr_level2; while (n1 > 0) { Node *node1 = q1.front(); q1.pop(); if (node1->left != NULL) q1.push(node1->left); if (node1->right != NULL) q1.push(node1->right); n1--; Node *node2 = q2.front(); q2.pop(); if (node2->left != NULL) q2.push(node2->left); if (node2->right != NULL) q2.push(node2->right); curr_level1.push_back(node1->data); curr_level2.push_back(node2->data); } // Check if nodes of current levels are // anagrams or not. sort(curr_level1.begin(), curr_level1.end()); sort(curr_level2.begin(), curr_level2.end()); if (curr_level1 != curr_level2) return false; } return true;} // Utility function to create a new tree NodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Constructing both the trees. struct Node* root1 = newNode(1); root1->left = newNode(3); root1->right = newNode(2); root1->right->left = newNode(5); root1->right->right = newNode(4); struct Node* root2 = newNode(1); root2->left = newNode(2); root2->right = newNode(3); root2->left->left = newNode(4); root2->left->right = newNode(5); areAnagrams(root1, root2)? cout << "Yes" : cout << "No"; return 0;}
/* Iterative program to check if two treesare level by level anagram. */import java.util.ArrayList;import java.util.Collections;import java.util.LinkedList;import java.util.Queue; public class GFG{ // A Binary Tree Node static class Node { Node left, right; int data; Node(int data){ this.data = data; left = null; right = null; } } // Returns true if trees with root1 and root2 // are level by level anagram, else returns false. static boolean areAnagrams(Node root1, Node root2) { // Base Cases if (root1 == null && root2 == null) return true; if (root1 == null || root2 == null) return false; // start level order traversal of two trees // using two queues. Queue<Node> q1 = new LinkedList<Node>(); Queue<Node> q2 = new LinkedList<Node>(); q1.add(root1); q2.add(root2); while (true) { // n1 (queue size) indicates number of // Nodes at current level in first tree // and n2 indicates number of nodes in // current level of second tree. int n1 = q1.size(), n2 = q2.size(); // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level ArrayList<Integer> curr_level1 = new ArrayList<>(); ArrayList<Integer> curr_level2 = new ArrayList<>(); while (n1 > 0) { Node node1 = q1.peek(); q1.remove(); if (node1.left != null) q1.add(node1.left); if (node1.right != null) q1.add(node1.right); n1--; Node node2 = q2.peek(); q2.remove(); if (node2.left != null) q2.add(node2.left); if (node2.right != null) q2.add(node2.right); curr_level1.add(node1.data); curr_level2.add(node2.data); } // Check if nodes of current levels are // anagrams or not. Collections.sort(curr_level1); Collections.sort(curr_level2); if (!curr_level1.equals(curr_level2)) return false; } return true; } // Driver program to test above functions public static void main(String args[]) { // Constructing both the trees. Node root1 = new Node(1); root1.left = new Node(3); root1.right = new Node(2); root1.right.left = new Node(5); root1.right.right = new Node(4); Node root2 = new Node(1); root2.left = new Node(2); root2.right = new Node(3); root2.left.left = new Node(4); root2.left.right = new Node(5); System.out.println(areAnagrams(root1, root2)? "Yes" : "No"); }}// This code is contributed by Sumit Ghosh
# Iterative program to check if two# trees are level by level anagram # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if trees with root1# and root2 are level by level# anagram, else returns false.def areAnagrams(root1, root2) : # Base Cases if (root1 == None and root2 == None) : return True if (root1 == None or root2 == None) : return False # start level order traversal of # two trees using two queues. q1 = [] q2 = [] q1.append(root1) q2.append(root2) while (1) : # n1 (queue size) indicates number # of Nodes at current level in first # tree and n2 indicates number of nodes # in current level of second tree. n1 = len(q1) n2 = len(q2) # If n1 and n2 are different if (n1 != n2): return False # If level order traversal is over if (n1 == 0): break # Dequeue all Nodes of current level # and Enqueue all Nodes of next level curr_level1 = [] curr_level2 = [] while (n1 > 0): node1 = q1[0] q1.pop(0) if (node1.left != None) : q1.append(node1.left) if (node1.right != None) : q1.append(node1.right) n1 -= 1 node2 = q2[0] q2.pop(0) if (node2.left != None) : q2.append(node2.left) if (node2.right != None) : q2.append(node2.right) curr_level1.append(node1.data) curr_level2.append(node2.data) # Check if nodes of current levels # are anagrams or not. curr_level1.sort() curr_level2.sort() if (curr_level1 != curr_level2) : return False return True # Driver Codeif __name__ == '__main__': # Constructing both the trees. root1 = newNode(1) root1.left = newNode(3) root1.right = newNode(2) root1.right.left = newNode(5) root1.right.right = newNode(4) root2 = newNode(1) root2.left = newNode(2) root2.right = newNode(3) root2.left.left = newNode(4) root2.left.right = newNode(5) if areAnagrams(root1, root2): print("Yes") else: print("No") # This code is contributed# by SHUBHAMSINGH10
/* Iterative program to check if two treesare level by level anagram. */using System;using System.Collections.Generic; class GFG{ // A Binary Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; left = null; right = null; } } // Returns true if trees with root1 // and root2 are level by level anagram, // else returns false. static Boolean areAnagrams(Node root1, Node root2) { // Base Cases if (root1 == null && root2 == null) return true; if (root1 == null || root2 == null) return false; // start level order traversal of two trees // using two queues. Queue<Node> q1 = new Queue<Node>(); Queue<Node> q2 = new Queue<Node>(); q1.Enqueue(root1); q2.Enqueue(root2); while (true) { // n1 (queue size) indicates number of // Nodes at current level in first tree // and n2 indicates number of nodes in // current level of second tree. int n1 = q1.Count, n2 = q2.Count; // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level List<int> curr_level1 = new List<int>(); List<int> curr_level2 = new List<int>(); while (n1 > 0) { Node node1 = q1.Peek(); q1.Dequeue(); if (node1.left != null) q1.Enqueue(node1.left); if (node1.right != null) q1.Enqueue(node1.right); n1--; Node node2 = q2.Peek(); q2.Dequeue(); if (node2.left != null) q2.Enqueue(node2.left); if (node2.right != null) q2.Enqueue(node2.right); curr_level1.Add(node1.data); curr_level2.Add(node2.data); } // Check if nodes of current levels are // anagrams or not. curr_level1.Sort(); curr_level2.Sort(); for(int i = 0; i < curr_level1.Count; i++) if(curr_level1[i] != curr_level2[i]) return false; } return true; } // Driver Code public static void Main(String []args) { // Constructing both the trees. Node root1 = new Node(1); root1.left = new Node(3); root1.right = new Node(2); root1.right.left = new Node(5); root1.right.right = new Node(4); Node root2 = new Node(1); root2.left = new Node(2); root2.right = new Node(3); root2.left.left = new Node(4); root2.left.right = new Node(5); Console.WriteLine(areAnagrams(root1, root2) ? "Yes" : "No"); }} // This code is contributed by Arnab Kundu
Output:
Yes
Note: In the above program we are comparing the vectors storing each level of a tree directly using not equal to function ‘ != ‘ which compares the vectors first on the basis of their size and then on the basis of their content, hence saving our work of iteratively comparing the vectors.
YouTubeGeeksforGeeks501K subscribersCheck if all levels of two trees are anagrams or not | 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 / 5:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Z9J_dMFJyCw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHUBHAMSINGH10
andrew1234
geeknobita
anagram
tree-level-order
Queue
Tree
Queue
Tree
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Construct Complete Binary Tree from its Linked List Representation
FIFO (First-In-First-Out) approach in Programming
Applications of Priority Queue
Smallest multiple of a given number made of digits 0 and 9 only
Reversing a Queue
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree) | [
{
"code": null,
"e": 24652,
"s": 24624,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 24763,
"s": 24652,
"text": "Given two binary trees, we have to check if each of their levels are anagrams of each other or not. Example: "
},
{
"code": null,
"e": 24866,
"s": 24765,
"text": "Tree 1:\nLevel 0 : 1\nLevel 1 : 3, 2\nLevel 2 : 5, 4\n\nTree 2:\nLevel 0 : 1\nLevel 1 : 2, 3\nLevel 2 : 4, 5"
},
{
"code": null,
"e": 24977,
"s": 24866,
"text": "As we can clearly see all the levels of above two binary trees are anagrams of each other, hence return true. "
},
{
"code": null,
"e": 25067,
"s": 24977,
"text": "Naive Approach: Below is the step by step explanation of the naive approach to do this: "
},
{
"code": null,
"e": 25390,
"s": 25067,
"text": "Write a recursive program for level order traversal of a tree.Traverse each level of both the trees one by one and store the result of traversals in 2 different vectors, one for each tree.Sort both the vectors and compare them iteratively for each level, if they are same for each level then return true else return false."
},
{
"code": null,
"e": 25453,
"s": 25390,
"text": "Write a recursive program for level order traversal of a tree."
},
{
"code": null,
"e": 25580,
"s": 25453,
"text": "Traverse each level of both the trees one by one and store the result of traversals in 2 different vectors, one for each tree."
},
{
"code": null,
"e": 25715,
"s": 25580,
"text": "Sort both the vectors and compare them iteratively for each level, if they are same for each level then return true else return false."
},
{
"code": null,
"e": 26119,
"s": 25715,
"text": "Time Complexity: O(n^2), where n is the number of nodes.Efficient Approach: The idea is based on below article. Print level order traversal line by line | Set 1 We traverse both trees simultaneously level by level. We store each level both trees in vectors (or array). To check if two vectors are anagram or not, we sort both and then compare.Time Complexity: O(nlogn), where n is the number of nodes. "
},
{
"code": null,
"e": 26123,
"s": 26119,
"text": "C++"
},
{
"code": null,
"e": 26128,
"s": 26123,
"text": "Java"
},
{
"code": null,
"e": 26136,
"s": 26128,
"text": "Python3"
},
{
"code": null,
"e": 26139,
"s": 26136,
"text": "C#"
},
{
"code": "/* Iterative program to check if two trees are level by level anagram. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ struct Node *left, *right; int data;}; // Returns true if trees with root1 and root2// are level by level anagram, else returns false.bool areAnagrams(Node *root1, Node *root2){ // Base Cases if (root1 == NULL && root2 == NULL) return true; if (root1 == NULL || root2 == NULL) return false; // start level order traversal of two trees // using two queues. queue<Node *> q1, q2; q1.push(root1); q2.push(root2); while (1) { // n1 (queue size) indicates number of Nodes // at current level in first tree and n2 indicates // number of nodes in current level of second tree. int n1 = q1.size(), n2 = q2.size(); // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level vector<int> curr_level1, curr_level2; while (n1 > 0) { Node *node1 = q1.front(); q1.pop(); if (node1->left != NULL) q1.push(node1->left); if (node1->right != NULL) q1.push(node1->right); n1--; Node *node2 = q2.front(); q2.pop(); if (node2->left != NULL) q2.push(node2->left); if (node2->right != NULL) q2.push(node2->right); curr_level1.push_back(node1->data); curr_level2.push_back(node2->data); } // Check if nodes of current levels are // anagrams or not. sort(curr_level1.begin(), curr_level1.end()); sort(curr_level2.begin(), curr_level2.end()); if (curr_level1 != curr_level2) return false; } return true;} // Utility function to create a new tree NodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Constructing both the trees. struct Node* root1 = newNode(1); root1->left = newNode(3); root1->right = newNode(2); root1->right->left = newNode(5); root1->right->right = newNode(4); struct Node* root2 = newNode(1); root2->left = newNode(2); root2->right = newNode(3); root2->left->left = newNode(4); root2->left->right = newNode(5); areAnagrams(root1, root2)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 28785,
"s": 26139,
"text": null
},
{
"code": "/* Iterative program to check if two treesare level by level anagram. */import java.util.ArrayList;import java.util.Collections;import java.util.LinkedList;import java.util.Queue; public class GFG{ // A Binary Tree Node static class Node { Node left, right; int data; Node(int data){ this.data = data; left = null; right = null; } } // Returns true if trees with root1 and root2 // are level by level anagram, else returns false. static boolean areAnagrams(Node root1, Node root2) { // Base Cases if (root1 == null && root2 == null) return true; if (root1 == null || root2 == null) return false; // start level order traversal of two trees // using two queues. Queue<Node> q1 = new LinkedList<Node>(); Queue<Node> q2 = new LinkedList<Node>(); q1.add(root1); q2.add(root2); while (true) { // n1 (queue size) indicates number of // Nodes at current level in first tree // and n2 indicates number of nodes in // current level of second tree. int n1 = q1.size(), n2 = q2.size(); // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level ArrayList<Integer> curr_level1 = new ArrayList<>(); ArrayList<Integer> curr_level2 = new ArrayList<>(); while (n1 > 0) { Node node1 = q1.peek(); q1.remove(); if (node1.left != null) q1.add(node1.left); if (node1.right != null) q1.add(node1.right); n1--; Node node2 = q2.peek(); q2.remove(); if (node2.left != null) q2.add(node2.left); if (node2.right != null) q2.add(node2.right); curr_level1.add(node1.data); curr_level2.add(node2.data); } // Check if nodes of current levels are // anagrams or not. Collections.sort(curr_level1); Collections.sort(curr_level2); if (!curr_level1.equals(curr_level2)) return false; } return true; } // Driver program to test above functions public static void main(String args[]) { // Constructing both the trees. Node root1 = new Node(1); root1.left = new Node(3); root1.right = new Node(2); root1.right.left = new Node(5); root1.right.right = new Node(4); Node root2 = new Node(1); root2.left = new Node(2); root2.right = new Node(3); root2.left.left = new Node(4); root2.left.right = new Node(5); System.out.println(areAnagrams(root1, root2)? \"Yes\" : \"No\"); }}// This code is contributed by Sumit Ghosh",
"e": 32147,
"s": 28785,
"text": null
},
{
"code": "# Iterative program to check if two# trees are level by level anagram # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if trees with root1# and root2 are level by level# anagram, else returns false.def areAnagrams(root1, root2) : # Base Cases if (root1 == None and root2 == None) : return True if (root1 == None or root2 == None) : return False # start level order traversal of # two trees using two queues. q1 = [] q2 = [] q1.append(root1) q2.append(root2) while (1) : # n1 (queue size) indicates number # of Nodes at current level in first # tree and n2 indicates number of nodes # in current level of second tree. n1 = len(q1) n2 = len(q2) # If n1 and n2 are different if (n1 != n2): return False # If level order traversal is over if (n1 == 0): break # Dequeue all Nodes of current level # and Enqueue all Nodes of next level curr_level1 = [] curr_level2 = [] while (n1 > 0): node1 = q1[0] q1.pop(0) if (node1.left != None) : q1.append(node1.left) if (node1.right != None) : q1.append(node1.right) n1 -= 1 node2 = q2[0] q2.pop(0) if (node2.left != None) : q2.append(node2.left) if (node2.right != None) : q2.append(node2.right) curr_level1.append(node1.data) curr_level2.append(node2.data) # Check if nodes of current levels # are anagrams or not. curr_level1.sort() curr_level2.sort() if (curr_level1 != curr_level2) : return False return True # Driver Codeif __name__ == '__main__': # Constructing both the trees. root1 = newNode(1) root1.left = newNode(3) root1.right = newNode(2) root1.right.left = newNode(5) root1.right.right = newNode(4) root2 = newNode(1) root2.left = newNode(2) root2.right = newNode(3) root2.left.left = newNode(4) root2.left.right = newNode(5) if areAnagrams(root1, root2): print(\"Yes\") else: print(\"No\") # This code is contributed# by SHUBHAMSINGH10",
"e": 34566,
"s": 32147,
"text": null
},
{
"code": "/* Iterative program to check if two treesare level by level anagram. */using System;using System.Collections.Generic; class GFG{ // A Binary Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; left = null; right = null; } } // Returns true if trees with root1 // and root2 are level by level anagram, // else returns false. static Boolean areAnagrams(Node root1, Node root2) { // Base Cases if (root1 == null && root2 == null) return true; if (root1 == null || root2 == null) return false; // start level order traversal of two trees // using two queues. Queue<Node> q1 = new Queue<Node>(); Queue<Node> q2 = new Queue<Node>(); q1.Enqueue(root1); q2.Enqueue(root2); while (true) { // n1 (queue size) indicates number of // Nodes at current level in first tree // and n2 indicates number of nodes in // current level of second tree. int n1 = q1.Count, n2 = q2.Count; // If n1 and n2 are different if (n1 != n2) return false; // If level order traversal is over if (n1 == 0) break; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level List<int> curr_level1 = new List<int>(); List<int> curr_level2 = new List<int>(); while (n1 > 0) { Node node1 = q1.Peek(); q1.Dequeue(); if (node1.left != null) q1.Enqueue(node1.left); if (node1.right != null) q1.Enqueue(node1.right); n1--; Node node2 = q2.Peek(); q2.Dequeue(); if (node2.left != null) q2.Enqueue(node2.left); if (node2.right != null) q2.Enqueue(node2.right); curr_level1.Add(node1.data); curr_level2.Add(node2.data); } // Check if nodes of current levels are // anagrams or not. curr_level1.Sort(); curr_level2.Sort(); for(int i = 0; i < curr_level1.Count; i++) if(curr_level1[i] != curr_level2[i]) return false; } return true; } // Driver Code public static void Main(String []args) { // Constructing both the trees. Node root1 = new Node(1); root1.left = new Node(3); root1.right = new Node(2); root1.right.left = new Node(5); root1.right.right = new Node(4); Node root2 = new Node(1); root2.left = new Node(2); root2.right = new Node(3); root2.left.left = new Node(4); root2.left.right = new Node(5); Console.WriteLine(areAnagrams(root1, root2) ? \"Yes\" : \"No\"); }} // This code is contributed by Arnab Kundu",
"e": 37883,
"s": 34566,
"text": null
},
{
"code": null,
"e": 37893,
"s": 37883,
"text": "Output: "
},
{
"code": null,
"e": 37897,
"s": 37893,
"text": "Yes"
},
{
"code": null,
"e": 38187,
"s": 37897,
"text": "Note: In the above program we are comparing the vectors storing each level of a tree directly using not equal to function ‘ != ‘ which compares the vectors first on the basis of their size and then on the basis of their content, hence saving our work of iteratively comparing the vectors. "
},
{
"code": null,
"e": 39038,
"s": 38187,
"text": "YouTubeGeeksforGeeks501K subscribersCheck if all levels of two trees are anagrams or not | 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 / 5:54•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Z9J_dMFJyCw\" 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": 39459,
"s": 39038,
"text": "This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39474,
"s": 39459,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 39485,
"s": 39474,
"text": "andrew1234"
},
{
"code": null,
"e": 39496,
"s": 39485,
"text": "geeknobita"
},
{
"code": null,
"e": 39504,
"s": 39496,
"text": "anagram"
},
{
"code": null,
"e": 39521,
"s": 39504,
"text": "tree-level-order"
},
{
"code": null,
"e": 39527,
"s": 39521,
"text": "Queue"
},
{
"code": null,
"e": 39532,
"s": 39527,
"text": "Tree"
},
{
"code": null,
"e": 39538,
"s": 39532,
"text": "Queue"
},
{
"code": null,
"e": 39543,
"s": 39538,
"text": "Tree"
},
{
"code": null,
"e": 39551,
"s": 39543,
"text": "anagram"
},
{
"code": null,
"e": 39649,
"s": 39551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39658,
"s": 39649,
"text": "Comments"
},
{
"code": null,
"e": 39671,
"s": 39658,
"text": "Old Comments"
},
{
"code": null,
"e": 39738,
"s": 39671,
"text": "Construct Complete Binary Tree from its Linked List Representation"
},
{
"code": null,
"e": 39788,
"s": 39738,
"text": "FIFO (First-In-First-Out) approach in Programming"
},
{
"code": null,
"e": 39819,
"s": 39788,
"text": "Applications of Priority Queue"
},
{
"code": null,
"e": 39883,
"s": 39819,
"text": "Smallest multiple of a given number made of digits 0 and 9 only"
},
{
"code": null,
"e": 39901,
"s": 39883,
"text": "Reversing a Queue"
},
{
"code": null,
"e": 39951,
"s": 39901,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 39986,
"s": 39951,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 40015,
"s": 39986,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 40056,
"s": 40015,
"text": "Inorder Tree Traversal without Recursion"
}
] |
Program to compare two fractions - GeeksforGeeks | 11 May, 2021
Given two fractions a/b and c/d, compare them and print the larger of the two.
Examples :
Input: 5/6, 11/45
Output: 5/6
Input: 4/5 and 2/3
Output: 4/5
We can simply convert the fractions into floating-point values by dividing the numerator by the denominator. Once we have the two floating-point numbers corresponding to each fraction, we can compare these numbers and determine which fraction is larger.However, the computed answer may be incorrect due to floating-point approximations and truncations during the division process. To get the most accurate answer we should avoid resorting to floating-point division.To compare two fractions we need to make their denominators the same. We can do this by cross-multiplying numerators with denominators. Let’s see how this works
We have two fractions a/b and c/d.
Let Y = (a/b - c/d)
= (ad - bc)/(bd)
Now,
if Y > 0 then a/b > c/d
if Y = 0 then a/b = c/d
if Y < o then a/b < c/d
Since bd is always positive, the sign of Y depends only on the
numerator (ad-bc). So we need to compute (ad-bc) only.
Complexity : Since we perform two multiplication and one subtraction operation, the answer is computed in constant time i.e O(1)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find max between// two Rational numbers#include <bits/stdc++.h>using namespace std; struct Fraction { int num, den;}; // Get max of the two fractionsFraction maxFraction(Fraction first, Fraction sec){ // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec;} // Driver Codeint main(){ Fraction first = { 3, 2 }; Fraction sec = { 3, 4 }; Fraction res = maxFraction(first, sec); cout << res.num << "/" << res.den; return 0;}
// Java program to find max between// two Rational numbers import java.io.*;import java.util.*; class Fraction { int num, den; //ConstructorFraction(int n,int d){ num=n; den=d;} // Get max of the two fractionsstatic Fraction maxFraction(Fraction first, Fraction sec){ // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec;} // Driver functionpublic static void main (String[] args) { Fraction first = new Fraction( 3, 2 ); Fraction sec = new Fraction( 3, 4 ); Fraction res = maxFraction(first, sec); System.out.println(res.num +"/"+ res.den); }} // This code is contributed by Gitanjali.
# Python3 program to find max# between two Rational numbers # Get max of the two fractionsdef maxFraction(first, sec): # Declare nume1 and nume2 for get the value # of first numerator and second numerator a = first[0]; b = first[1] c = sec[0]; d = sec[1] # Compute ad-bc Y = a * d - b * c return first if Y else sec # Driver Codefirst = ( 3, 2 )sec = ( 3, 4 )res = maxFraction(first, sec)print(str(res[0]) + "/" + str(res[1])) # This code is contributed by Ansu Kumari.
// C# program to find max between// two Rational numbersusing System; class Fraction { int num, den; //Constructor Fraction(int n,int d) { num=n; den=d; } // Get max of the two fractions static Fraction maxFraction(Fraction first, Fraction sec) { // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec; } // Driver function public static void Main () { Fraction first = new Fraction( 3, 2 ); Fraction sec = new Fraction( 3, 4 ); Fraction res = maxFraction(first, sec); Console.WriteLine(res.num +"/"+ res.den); }} // This code is contributed by vt_m.
<?php// PHP program to find max// between two Rational numbers // Get max of the two fractionsfunction maxFraction($first, $sec){ // Declare nume1 and nume2 // for get the value of // first numerator and second // numerator $a = $first[0]; $b = $first[1]; $c = $sec[0]; $d = $sec[1]; // Compute ad-bc $Y = $a * $d - $b * $c; return ($Y) ? $first : $sec;} // Driver Code$first = array( 3, 2 );$sec = array ( 3, 4 );$res = maxFraction($first, $sec);echo $res[0] . "/" . $res[1]; // This code is contributed// by mits.?>
// javascript program to find max// between two Rational numbers // Get max of the two fractionsfunction maxFraction(first, sec) { // Declare nume1 and nume2 for get the value // of first numerator and second numerator a = first[0]; b = first[1] c = sec[0]; d = sec[1] // Compute ad-bc Y = a * d - b * c return (Y > 0) ? first : sec; } // Driver Code first = [ 3, 2 ];sec = [ 3, 4 ];res = maxFraction(first, sec); document.write(res[0] + "/" + res[1]);
Output :
3/2
Mithun Kumar
bunnyram19
Fraction
number-theory
Mathematical
number-theory
Mathematical
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 print prime numbers from 1 to N.
Count ways to reach the n'th stair
Program to convert a given number to words
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Find first and last digits of a number | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 24795,
"s": 24716,
"text": "Given two fractions a/b and c/d, compare them and print the larger of the two."
},
{
"code": null,
"e": 24808,
"s": 24795,
"text": "Examples : "
},
{
"code": null,
"e": 24871,
"s": 24808,
"text": "Input: 5/6, 11/45\nOutput: 5/6\n\nInput: 4/5 and 2/3\nOutput: 4/5 "
},
{
"code": null,
"e": 25499,
"s": 24871,
"text": "We can simply convert the fractions into floating-point values by dividing the numerator by the denominator. Once we have the two floating-point numbers corresponding to each fraction, we can compare these numbers and determine which fraction is larger.However, the computed answer may be incorrect due to floating-point approximations and truncations during the division process. To get the most accurate answer we should avoid resorting to floating-point division.To compare two fractions we need to make their denominators the same. We can do this by cross-multiplying numerators with denominators. Let’s see how this works "
},
{
"code": null,
"e": 25775,
"s": 25499,
"text": "We have two fractions a/b and c/d.\nLet Y = (a/b - c/d) \n = (ad - bc)/(bd)\nNow,\nif Y > 0 then a/b > c/d \nif Y = 0 then a/b = c/d\nif Y < o then a/b < c/d\n\nSince bd is always positive, the sign of Y depends only on the\nnumerator (ad-bc). So we need to compute (ad-bc) only."
},
{
"code": null,
"e": 25905,
"s": 25775,
"text": "Complexity : Since we perform two multiplication and one subtraction operation, the answer is computed in constant time i.e O(1) "
},
{
"code": null,
"e": 25909,
"s": 25905,
"text": "C++"
},
{
"code": null,
"e": 25914,
"s": 25909,
"text": "Java"
},
{
"code": null,
"e": 25922,
"s": 25914,
"text": "Python3"
},
{
"code": null,
"e": 25925,
"s": 25922,
"text": "C#"
},
{
"code": null,
"e": 25929,
"s": 25925,
"text": "PHP"
},
{
"code": null,
"e": 25940,
"s": 25929,
"text": "Javascript"
},
{
"code": "// CPP program to find max between// two Rational numbers#include <bits/stdc++.h>using namespace std; struct Fraction { int num, den;}; // Get max of the two fractionsFraction maxFraction(Fraction first, Fraction sec){ // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec;} // Driver Codeint main(){ Fraction first = { 3, 2 }; Fraction sec = { 3, 4 }; Fraction res = maxFraction(first, sec); cout << res.num << \"/\" << res.den; return 0;}",
"e": 26602,
"s": 25940,
"text": null
},
{
"code": "// Java program to find max between// two Rational numbers import java.io.*;import java.util.*; class Fraction { int num, den; //ConstructorFraction(int n,int d){ num=n; den=d;} // Get max of the two fractionsstatic Fraction maxFraction(Fraction first, Fraction sec){ // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec;} // Driver functionpublic static void main (String[] args) { Fraction first = new Fraction( 3, 2 ); Fraction sec = new Fraction( 3, 4 ); Fraction res = maxFraction(first, sec); System.out.println(res.num +\"/\"+ res.den); }} // This code is contributed by Gitanjali.",
"e": 27425,
"s": 26602,
"text": null
},
{
"code": "# Python3 program to find max# between two Rational numbers # Get max of the two fractionsdef maxFraction(first, sec): # Declare nume1 and nume2 for get the value # of first numerator and second numerator a = first[0]; b = first[1] c = sec[0]; d = sec[1] # Compute ad-bc Y = a * d - b * c return first if Y else sec # Driver Codefirst = ( 3, 2 )sec = ( 3, 4 )res = maxFraction(first, sec)print(str(res[0]) + \"/\" + str(res[1])) # This code is contributed by Ansu Kumari.",
"e": 27924,
"s": 27425,
"text": null
},
{
"code": "// C# program to find max between// two Rational numbersusing System; class Fraction { int num, den; //Constructor Fraction(int n,int d) { num=n; den=d; } // Get max of the two fractions static Fraction maxFraction(Fraction first, Fraction sec) { // Declare nume1 and nume2 for get the value of // first numerator and second numerator int a = first.num; int b = first.den; int c = sec.num; int d = sec.den; // Compute ad-bc int Y = a * d - b * c; return (Y > 0) ? first : sec; } // Driver function public static void Main () { Fraction first = new Fraction( 3, 2 ); Fraction sec = new Fraction( 3, 4 ); Fraction res = maxFraction(first, sec); Console.WriteLine(res.num +\"/\"+ res.den); }} // This code is contributed by vt_m.",
"e": 28846,
"s": 27924,
"text": null
},
{
"code": "<?php// PHP program to find max// between two Rational numbers // Get max of the two fractionsfunction maxFraction($first, $sec){ // Declare nume1 and nume2 // for get the value of // first numerator and second // numerator $a = $first[0]; $b = $first[1]; $c = $sec[0]; $d = $sec[1]; // Compute ad-bc $Y = $a * $d - $b * $c; return ($Y) ? $first : $sec;} // Driver Code$first = array( 3, 2 );$sec = array ( 3, 4 );$res = maxFraction($first, $sec);echo $res[0] . \"/\" . $res[1]; // This code is contributed// by mits.?>",
"e": 29404,
"s": 28846,
"text": null
},
{
"code": "// javascript program to find max// between two Rational numbers // Get max of the two fractionsfunction maxFraction(first, sec) { // Declare nume1 and nume2 for get the value // of first numerator and second numerator a = first[0]; b = first[1] c = sec[0]; d = sec[1] // Compute ad-bc Y = a * d - b * c return (Y > 0) ? first : sec; } // Driver Code first = [ 3, 2 ];sec = [ 3, 4 ];res = maxFraction(first, sec); document.write(res[0] + \"/\" + res[1]);",
"e": 29895,
"s": 29404,
"text": null
},
{
"code": null,
"e": 29906,
"s": 29895,
"text": "Output : "
},
{
"code": null,
"e": 29910,
"s": 29906,
"text": "3/2"
},
{
"code": null,
"e": 29925,
"s": 29912,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29936,
"s": 29925,
"text": "bunnyram19"
},
{
"code": null,
"e": 29945,
"s": 29936,
"text": "Fraction"
},
{
"code": null,
"e": 29959,
"s": 29945,
"text": "number-theory"
},
{
"code": null,
"e": 29972,
"s": 29959,
"text": "Mathematical"
},
{
"code": null,
"e": 29986,
"s": 29972,
"text": "number-theory"
},
{
"code": null,
"e": 29999,
"s": 29986,
"text": "Mathematical"
},
{
"code": null,
"e": 30097,
"s": 29999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30106,
"s": 30097,
"text": "Comments"
},
{
"code": null,
"e": 30119,
"s": 30106,
"text": "Old Comments"
},
{
"code": null,
"e": 30151,
"s": 30119,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30182,
"s": 30151,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30215,
"s": 30182,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30259,
"s": 30215,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30294,
"s": 30259,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30337,
"s": 30294,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 30362,
"s": 30337,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30397,
"s": 30362,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 30429,
"s": 30397,
"text": "Check if a number is Palindrome"
}
] |
HTML5 Canvas - Composition | HTML5 canvas provides compositing attribute globalCompositeOperation which affect all the drawing operations.
We can draw new shapes behind existing shapes and mask off certain areas, clear sections from the canvas using globalCompositeOperation attribute as shown below in the example.
There are following values which can be set for globalCompositeOperation −
source-over
This is the default setting and draws new shapes on top of the existing canvas content.
source-in
The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.
source-out
The new shape is drawn where it doesn't overlap the existing canvas content.
source-atop
The new shape is only drawn where it overlaps the existing canvas content.
lighter
Where both shapes overlap the color is determined by adding color values.
xor
Shapes are made transparent where both overlap and drawn normal everywhere else.
destination-over
New shapes are drawn behind the existing canvas content.
destination-in
The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.
destination-out
The existing content is kept where it doesn't overlap the new shape.
destination-atop
The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.
darker
Where both shapes overlap the color is determined by subtracting color values.
Following is a simple example which makes use of globalCompositeOperation attribute to create all possible compositions −
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var compositeTypes = [
'source-over','source-in','source-out','source-atop',
'destination-over','destination-in','destination-out',
'destination-atop','lighter','darker','copy','xor'
];
function drawShape() {
for (i=0;i<compositeTypes.length;i++) {
var label = document.createTextNode(compositeTypes[i]);
document.getElementById('lab'+i).appendChild(label);
var ctx = document.getElementById('tut'+i).getContext('2d');
// draw rectangle
ctx.fillStyle = "#FF3366";
ctx.fillRect(15,15,70,70);
// set composite property
ctx.globalCompositeOperation = compositeTypes[i];
// draw circle
ctx.fillStyle = "#0066FF";
ctx.beginPath();
ctx.arc(75,75,35,0,Math.PI*2,true);
ctx.fill();
}
}
</script>
</head>
<body onload = "drawShape();">
<table border = "1" align = "center">
<tr>
<td><canvas id = "tut0" width = "125" height = "125"></canvas><br/>
<label id = "lab0"></label>
</td>
<td><canvas id = "tut1" width = "125" height = "125"></canvas><br/>
<label id = "lab1"></label>
</td>
<td><canvas id = "tut2" width = "125" height = "125"></canvas><br/>
<label id = "lab2"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut3" width = "125" height = "125"></canvas><br/>
<label id = "lab3"></label>
</td>
<td><canvas id = "tut4" width = "125" height = "125"></canvas><br/>
<label id = "lab4"></label>
</td>
<td><canvas id = "tut5" width = "125" height = "125"></canvas><br/>
<label id = "lab5"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut6" width = "125" height = "125"></canvas><br/>
<label id = "lab6"></label>
</td>
<td><canvas id = "tut7" width = "125" height = "125"></canvas><br/>
<label id = "lab7"></label>
</td>
<td><canvas id = "tut8" width = "125" height = "125"></canvas><br/>
<label id = "lab8"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut9" width = "125" height = "125"></canvas><br/>
<label id = "lab9"></label>
</td>
<td><canvas id = "tut10" width = "125" height = "125"></canvas><br/>
<label id = "lab10"></label>
</td>
<td><canvas id = "tut11" width = "125" height = "125"></canvas><br/>
<label id = "lab11"></label>
</td>
</tr>
</table>
</body>
</html>
The above example would produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2718,
"s": 2608,
"text": "HTML5 canvas provides compositing attribute globalCompositeOperation which affect all the drawing operations."
},
{
"code": null,
"e": 2895,
"s": 2718,
"text": "We can draw new shapes behind existing shapes and mask off certain areas, clear sections from the canvas using globalCompositeOperation attribute as shown below in the example."
},
{
"code": null,
"e": 2970,
"s": 2895,
"text": "There are following values which can be set for globalCompositeOperation −"
},
{
"code": null,
"e": 2982,
"s": 2970,
"text": "source-over"
},
{
"code": null,
"e": 3070,
"s": 2982,
"text": "This is the default setting and draws new shapes on top of the existing canvas content."
},
{
"code": null,
"e": 3080,
"s": 3070,
"text": "source-in"
},
{
"code": null,
"e": 3206,
"s": 3080,
"text": "The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent."
},
{
"code": null,
"e": 3217,
"s": 3206,
"text": "source-out"
},
{
"code": null,
"e": 3294,
"s": 3217,
"text": "The new shape is drawn where it doesn't overlap the existing canvas content."
},
{
"code": null,
"e": 3306,
"s": 3294,
"text": "source-atop"
},
{
"code": null,
"e": 3381,
"s": 3306,
"text": "The new shape is only drawn where it overlaps the existing canvas content."
},
{
"code": null,
"e": 3389,
"s": 3381,
"text": "lighter"
},
{
"code": null,
"e": 3463,
"s": 3389,
"text": "Where both shapes overlap the color is determined by adding color values."
},
{
"code": null,
"e": 3467,
"s": 3463,
"text": "xor"
},
{
"code": null,
"e": 3548,
"s": 3467,
"text": "Shapes are made transparent where both overlap and drawn normal everywhere else."
},
{
"code": null,
"e": 3565,
"s": 3548,
"text": "destination-over"
},
{
"code": null,
"e": 3622,
"s": 3565,
"text": "New shapes are drawn behind the existing canvas content."
},
{
"code": null,
"e": 3637,
"s": 3622,
"text": "destination-in"
},
{
"code": null,
"e": 3772,
"s": 3637,
"text": "The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent."
},
{
"code": null,
"e": 3788,
"s": 3772,
"text": "destination-out"
},
{
"code": null,
"e": 3857,
"s": 3788,
"text": "The existing content is kept where it doesn't overlap the new shape."
},
{
"code": null,
"e": 3874,
"s": 3857,
"text": "destination-atop"
},
{
"code": null,
"e": 3990,
"s": 3874,
"text": "The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content."
},
{
"code": null,
"e": 3997,
"s": 3990,
"text": "darker"
},
{
"code": null,
"e": 4076,
"s": 3997,
"text": "Where both shapes overlap the color is determined by subtracting color values."
},
{
"code": null,
"e": 4198,
"s": 4076,
"text": "Following is a simple example which makes use of globalCompositeOperation attribute to create all possible compositions −"
},
{
"code": null,
"e": 7411,
"s": 4198,
"text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n var compositeTypes = [\n 'source-over','source-in','source-out','source-atop',\n 'destination-over','destination-in','destination-out',\n 'destination-atop','lighter','darker','copy','xor'\n ];\n \n function drawShape() {\n for (i=0;i<compositeTypes.length;i++) {\n var label = document.createTextNode(compositeTypes[i]);\n document.getElementById('lab'+i).appendChild(label);\n var ctx = document.getElementById('tut'+i).getContext('2d');\n \n // draw rectangle\n ctx.fillStyle = \"#FF3366\";\n ctx.fillRect(15,15,70,70);\n \n // set composite property\n ctx.globalCompositeOperation = compositeTypes[i];\n \n // draw circle\n ctx.fillStyle = \"#0066FF\";\n ctx.beginPath();\n ctx.arc(75,75,35,0,Math.PI*2,true);\n ctx.fill();\n }\n }\n </script>\n </head>\n \n <body onload = \"drawShape();\">\n <table border = \"1\" align = \"center\">\n <tr>\n <td><canvas id = \"tut0\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab0\"></label>\n </td>\n \n <td><canvas id = \"tut1\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab1\"></label>\n </td>\n \n <td><canvas id = \"tut2\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab2\"></label>\n </td>\n </tr>\n \n <tr>\n <td><canvas id = \"tut3\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab3\"></label>\n </td>\n \n <td><canvas id = \"tut4\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab4\"></label>\n </td>\n \n <td><canvas id = \"tut5\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab5\"></label>\n </td>\n </tr>\n \n <tr>\n <td><canvas id = \"tut6\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab6\"></label>\n </td>\n \n <td><canvas id = \"tut7\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab7\"></label>\n </td>\n \n <td><canvas id = \"tut8\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab8\"></label>\n </td>\n </tr>\n \n <tr>\n <td><canvas id = \"tut9\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab9\"></label>\n </td>\n \n <td><canvas id = \"tut10\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab10\"></label>\n </td>\n \n <td><canvas id = \"tut11\" width = \"125\" height = \"125\"></canvas><br/>\n <label id = \"lab11\"></label>\n </td>\n </tr> \n </table>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7466,
"s": 7411,
"text": "The above example would produce the following result −"
},
{
"code": null,
"e": 7499,
"s": 7466,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7513,
"s": 7499,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7548,
"s": 7513,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7562,
"s": 7548,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7597,
"s": 7562,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7614,
"s": 7597,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7649,
"s": 7614,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7680,
"s": 7649,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7713,
"s": 7680,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7744,
"s": 7713,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7779,
"s": 7744,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7810,
"s": 7779,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7817,
"s": 7810,
"text": " Print"
},
{
"code": null,
"e": 7828,
"s": 7817,
"text": " Add Notes"
}
] |
TCL Full Form - GeeksforGeeks | 08 Nov, 2021
TCL stands for Transaction Control Languages. These commands are used for maintaining consistency of the database and for the management of transactions made by the DML commands.
A Transaction is a set of SQL statements that are executed on the data stored in DBMS. Whenever any transaction is made these transactions are temporarily happen in database.So to make the changes permanent, we use TCL commands.
The TCL commands are:
COMMITROLLBACKSAVEPOINT
COMMIT
ROLLBACK
SAVEPOINT
1. COMMIT : This command is used to save the data permanently. Whenever we perform any of the DDL command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored permanently. So in order to be at the safer side COMMIT command is used.
Syntax:
commit;
2. ROLLBACK : This command is used to get the data or restore the data to the last savepoint or last committed state. If due to some reasons the data inserted, deleted or updated is not correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to the last committed state.
Syntax:
rollback;
3. SAVEPOINT : This command is used to save the data at a particular point temporarily, so that whenever needed can be rollback to that particular point.
Syntax:
Savepoint A;
Consider the following Table Student:
UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE NAME = ‘Jolly’;
COMMIT;
ROLLBACK;
By using this command you can update the record and save it permanently by using COMMIT command.
Now after COMMIT :
If commit was not performed then the changes made by the update command can be rollback.
Now if no COMMIT is performed.
UPDATE STUDENT
SET NAME = ‘Sherlock’
WHERE STUDENT_NAME = ‘Jolly’;
After update command the table will be:
Now if ROLLBACK is performed on the above table:
rollback;
After Rollback:
If on the above table savepoint is performed:
INSERT into STUDENT
VALUES ('Jack', 95);
Commit;
UPDATE NAME
SET NAME= ‘Rossie’
WHERE marks= 70;
SAVEPOINT A;
INSERT INTO STUDENT
VALUES (‘Zack’, 76);
Savepoint B;
INSERT INTO STUDENT
VALUES (‘Bruno’, 85);
Savepoint C;
SELECT *
FROM STUDENT;
Now if we Rollback to Savepoint B:
Rollback to B;
The resulting Table will be-
Now if we Rollback to Savepoint A:
Rollback to A;
The resulting Table will be-
So It was all about TCL commands in SQL (transaction control language) with examples.
adnanirshad158
ruhelaa48
Picked
DBMS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Interview Questions
Data Preprocessing in Data Mining
SQL | GROUP BY
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL? | [
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 24220,
"s": 24040,
"text": "TCL stands for Transaction Control Languages. These commands are used for maintaining consistency of the database and for the management of transactions made by the DML commands. "
},
{
"code": null,
"e": 24450,
"s": 24220,
"text": "A Transaction is a set of SQL statements that are executed on the data stored in DBMS. Whenever any transaction is made these transactions are temporarily happen in database.So to make the changes permanent, we use TCL commands. "
},
{
"code": null,
"e": 24474,
"s": 24450,
"text": "The TCL commands are: "
},
{
"code": null,
"e": 24498,
"s": 24474,
"text": "COMMITROLLBACKSAVEPOINT"
},
{
"code": null,
"e": 24505,
"s": 24498,
"text": "COMMIT"
},
{
"code": null,
"e": 24514,
"s": 24505,
"text": "ROLLBACK"
},
{
"code": null,
"e": 24524,
"s": 24514,
"text": "SAVEPOINT"
},
{
"code": null,
"e": 24784,
"s": 24524,
"text": "1. COMMIT : This command is used to save the data permanently. Whenever we perform any of the DDL command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored permanently. So in order to be at the safer side COMMIT command is used. "
},
{
"code": null,
"e": 24794,
"s": 24784,
"text": "Syntax: "
},
{
"code": null,
"e": 24803,
"s": 24794,
"text": "commit; "
},
{
"code": null,
"e": 25114,
"s": 24803,
"text": "2. ROLLBACK : This command is used to get the data or restore the data to the last savepoint or last committed state. If due to some reasons the data inserted, deleted or updated is not correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to the last committed state. "
},
{
"code": null,
"e": 25124,
"s": 25114,
"text": "Syntax: "
},
{
"code": null,
"e": 25134,
"s": 25124,
"text": "rollback;"
},
{
"code": null,
"e": 25289,
"s": 25134,
"text": "3. SAVEPOINT : This command is used to save the data at a particular point temporarily, so that whenever needed can be rollback to that particular point. "
},
{
"code": null,
"e": 25299,
"s": 25289,
"text": "Syntax: "
},
{
"code": null,
"e": 25313,
"s": 25299,
"text": "Savepoint A; "
},
{
"code": null,
"e": 25352,
"s": 25313,
"text": "Consider the following Table Student: "
},
{
"code": null,
"e": 25433,
"s": 25352,
"text": "UPDATE STUDENT \nSET NAME = ‘Sherlock’ \nWHERE NAME = ‘Jolly’;\n\nCOMMIT;\nROLLBACK; "
},
{
"code": null,
"e": 25531,
"s": 25433,
"text": "By using this command you can update the record and save it permanently by using COMMIT command. "
},
{
"code": null,
"e": 25551,
"s": 25531,
"text": "Now after COMMIT : "
},
{
"code": null,
"e": 25641,
"s": 25551,
"text": "If commit was not performed then the changes made by the update command can be rollback. "
},
{
"code": null,
"e": 25674,
"s": 25641,
"text": "Now if no COMMIT is performed. "
},
{
"code": null,
"e": 25744,
"s": 25674,
"text": "UPDATE STUDENT \nSET NAME = ‘Sherlock’ \nWHERE STUDENT_NAME = ‘Jolly’; "
},
{
"code": null,
"e": 25785,
"s": 25744,
"text": "After update command the table will be: "
},
{
"code": null,
"e": 25836,
"s": 25785,
"text": "Now if ROLLBACK is performed on the above table: "
},
{
"code": null,
"e": 25847,
"s": 25836,
"text": "rollback; "
},
{
"code": null,
"e": 25864,
"s": 25847,
"text": "After Rollback: "
},
{
"code": null,
"e": 25911,
"s": 25864,
"text": "If on the above table savepoint is performed: "
},
{
"code": null,
"e": 26168,
"s": 25911,
"text": "INSERT into STUDENT \nVALUES ('Jack', 95);\n\nCommit;\n\nUPDATE NAME \nSET NAME= ‘Rossie’ \nWHERE marks= 70;\n\nSAVEPOINT A;\n\nINSERT INTO STUDENT \nVALUES (‘Zack’, 76);\n\nSavepoint B;\n\nINSERT INTO STUDENT \nVALUES (‘Bruno’, 85);\n\nSavepoint C;\n\nSELECT * \nFROM STUDENT; "
},
{
"code": null,
"e": 26205,
"s": 26168,
"text": "Now if we Rollback to Savepoint B: "
},
{
"code": null,
"e": 26221,
"s": 26205,
"text": "Rollback to B; "
},
{
"code": null,
"e": 26251,
"s": 26221,
"text": "The resulting Table will be- "
},
{
"code": null,
"e": 26288,
"s": 26251,
"text": "Now if we Rollback to Savepoint A: "
},
{
"code": null,
"e": 26304,
"s": 26288,
"text": "Rollback to A; "
},
{
"code": null,
"e": 26334,
"s": 26304,
"text": "The resulting Table will be- "
},
{
"code": null,
"e": 26420,
"s": 26334,
"text": "So It was all about TCL commands in SQL (transaction control language) with examples."
},
{
"code": null,
"e": 26435,
"s": 26420,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26445,
"s": 26435,
"text": "ruhelaa48"
},
{
"code": null,
"e": 26452,
"s": 26445,
"text": "Picked"
},
{
"code": null,
"e": 26457,
"s": 26452,
"text": "DBMS"
},
{
"code": null,
"e": 26461,
"s": 26457,
"text": "SQL"
},
{
"code": null,
"e": 26477,
"s": 26461,
"text": "Write From Home"
},
{
"code": null,
"e": 26482,
"s": 26477,
"text": "DBMS"
},
{
"code": null,
"e": 26486,
"s": 26482,
"text": "SQL"
},
{
"code": null,
"e": 26584,
"s": 26486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26595,
"s": 26584,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26648,
"s": 26595,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26672,
"s": 26648,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26706,
"s": 26672,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 26721,
"s": 26706,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 26765,
"s": 26721,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 26786,
"s": 26765,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26797,
"s": 26786,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26821,
"s": 26797,
"text": "SQL Interview Questions"
}
] |
Implement Gradient Descent in Python | by Rohan Joseph | Towards Data Science | It is an optimization algorithm to find the minimum of a function. We start with a random point on the function and move in the negative direction of the gradient of the function to reach the local/global minima.
Question : Find the local minima of the function y=(x+5)2 starting from the point x=3
Solution : We know the answer just by looking at the graph. y = (x+5)2 reaches it’s minimum value when x = -5 (i.e when x=-5, y=0). Hence x=-5 is the local and global minima of the function.
Now, let’s see how to obtain the same numerically using gradient descent.
Step 1 : Initialize x =3. Then, find the gradient of the function, dy/dx = 2*(x+5).
Step 2 : Move in the direction of the negative of the gradient (Why?). But wait, how much to move? For that, we require a learning rate. Let us assume the learning rate → 0.01
Step 3 : Let’s perform 2 iterations of gradient descent
Step 4 : We can observe that the X value is slowly decreasing and should converge to -5 (the local minima). However, how many iterations should we perform?
Let us set a precision variable in our algorithm which calculates the difference between two consecutive “x” values . If the difference between x values from 2 consecutive iterations is lesser than the precision we set, stop the algorithm !
Step 1 : Initialize parameters
cur_x = 3 # The algorithm starts at x=3rate = 0.01 # Learning rateprecision = 0.000001 #This tells us when to stop the algorithmprevious_step_size = 1 #max_iters = 10000 # maximum number of iterationsiters = 0 #iteration counterdf = lambda x: 2*(x+5) #Gradient of our function
Step 2 : Run a loop to perform gradient descent :
i. Stop loop when difference between x values from 2 consecutive iterations is less than 0.000001 or when number of iterations exceeds 10,000
while previous_step_size > precision and iters < max_iters: prev_x = cur_x #Store current x value in prev_x cur_x = cur_x - rate * df(prev_x) #Grad descent previous_step_size = abs(cur_x - prev_x) #Change in x iters = iters+1 #iteration count print("Iteration",iters,"\nX value is",cur_x) #Print iterations print("The local minimum occurs at", cur_x)
Output : From the output below, we can observe the x values for the first 10 iterations- which can be cross checked with our calculation above. The algorithm runs for 595 iterations before it terminates. The code and solution is embedded below for reference.
Connect on LinkedIn.
cur_x = 3 # The algorithm starts at x=3
rate = 0.01 # Learning rate
precision = 0.000001 #This tells us when to stop the algorithm
previous_step_size = 1 #
max_iters = 10000 # maximum number of iterations
iters = 0 #iteration counter
df = lambda x: 2*(x+5) #Gradient of our function
while previous_step_size > precision and iters < max_iters:
prev_x = cur_x #Store current x value in prev_x
cur_x = cur_x - rate * df(prev_x) #Grad descent
previous_step_size = abs(cur_x - prev_x) #Change in x
iters = iters+1 #iteration count
print("Iteration",iters,"\nX value is",cur_x) #Print iterations
print("The local minimum occurs at", cur_x)
Iteration 1
X value is 2.84
Iteration 2
X value is 2.6832
Iteration 3
X value is 2.529536
Iteration 4
X value is 2.37894528
Iteration 5
X value is 2.2313663744
Iteration 6
X value is 2.0867390469119997
Iteration 7
X value is 1.9450042659737599
Iteration 8
X value is 1.8061041806542846
Iteration 9
X value is 1.669982097041199
Iteration 10
X value is 1.5365824551003748
Iteration 11
X value is 1.4058508059983674
Iteration 12
X value is 1.2777337898784
Iteration 13
X value is 1.152179114080832
Iteration 14
X value is 1.0291355317992152
Iteration 15
X value is 0.9085528211632309
Iteration 16
X value is 0.7903817647399662
Iteration 17
X value is 0.6745741294451669
Iteration 18
X value is 0.5610826468562635
Iteration 19
X value is 0.44986099391913825
Iteration 20
X value is 0.3408637740407555
Iteration 21
X value is 0.23404649855994042
Iteration 22
X value is 0.1293655685887416
Iteration 23
X value is 0.026778257216966764
Iteration 24
X value is -0.07375730792737258
Iteration 25
X value is -0.1722821617688251
Iteration 26
X value is -0.2688365185334486
Iteration 27
X value is -0.36345978816277963
Iteration 28
X value is -0.45619059239952403
Iteration 29
X value is -0.5470667805515336
Iteration 30
X value is -0.6361254449405029
Iteration 31
X value is -0.7234029360416929
Iteration 32
X value is -0.8089348773208591
Iteration 33
X value is -0.8927561797744419
Iteration 34
X value is -0.9749010561789531
Iteration 35
X value is -1.055403035055374
Iteration 36
X value is -1.1342949743542665
Iteration 37
X value is -1.2116090748671813
Iteration 38
X value is -1.2873768933698377
Iteration 39
X value is -1.361629355502441
Iteration 40
X value is -1.4343967683923922
Iteration 41
X value is -1.5057088330245443
Iteration 42
X value is -1.5755946563640535
Iteration 43
X value is -1.6440827632367725
Iteration 44
X value is -1.711201107972037
Iteration 45
X value is -1.7769770858125964
Iteration 46
X value is -1.8414375440963444
Iteration 47
X value is -1.9046087932144176
Iteration 48
X value is -1.9665166173501292
Iteration 49
X value is -2.0271862850031264
Iteration 50
X value is -2.0866425593030637
Iteration 51
X value is -2.1449097081170025
Iteration 52
X value is -2.2020115139546625
Iteration 53
X value is -2.257971283675569
Iteration 54
X value is -2.312811858002058
Iteration 55
X value is -2.3665556208420164
Iteration 56
X value is -2.419224508425176
Iteration 57
X value is -2.4708400182566725
Iteration 58
X value is -2.521423217891539
Iteration 59
X value is -2.570994753533708
Iteration 60
X value is -2.619574858463034
Iteration 61
X value is -2.667183361293773
Iteration 62
X value is -2.713839694067898
Iteration 63
X value is -2.75956290018654
Iteration 64
X value is -2.804371642182809
Iteration 65
X value is -2.8482842093391527
Iteration 66
X value is -2.8913185251523696
Iteration 67
X value is -2.9334921546493224
Iteration 68
X value is -2.974822311556336
Iteration 69
X value is -3.015325865325209
Iteration 70
X value is -3.055019348018705
Iteration 71
X value is -3.093918961058331
Iteration 72
X value is -3.1320405818371646
Iteration 73
X value is -3.1693997702004215
Iteration 74
X value is -3.206011774796413
Iteration 75
X value is -3.2418915393004846
Iteration 76
X value is -3.277053708514475
Iteration 77
X value is -3.3115126343441856
Iteration 78
X value is -3.345282381657302
Iteration 79
X value is -3.378376734024156
Iteration 80
X value is -3.4108091993436727
Iteration 81
X value is -3.4425930153567994
Iteration 82
X value is -3.4737411550496633
Iteration 83
X value is -3.50426633194867
Iteration 84
X value is -3.534181005309697
Iteration 85
X value is -3.563497385203503
Iteration 86
X value is -3.5922274374994325
Iteration 87
X value is -3.620382888749444
Iteration 88
X value is -3.6479752309744553
Iteration 89
X value is -3.675015726354966
Iteration 90
X value is -3.7015154118278666
Iteration 91
X value is -3.7274851035913095
Iteration 92
X value is -3.7529354015194833
Iteration 93
X value is -3.7778766934890937
Iteration 94
X value is -3.8023191596193118
Iteration 95
X value is -3.8262727764269258
Iteration 96
X value is -3.8497473208983872
Iteration 97
X value is -3.8727523744804193
Iteration 98
X value is -3.895297326990811
Iteration 99
X value is -3.917391380450995
Iteration 100
X value is -3.939043552841975
Iteration 101
X value is -3.9602626817851356
Iteration 102
X value is -3.981057428149433
Iteration 103
X value is -4.001436279586445
Iteration 104
X value is -4.021407553994716
Iteration 105
X value is -4.040979402914822
Iteration 106
X value is -4.060159814856525
Iteration 107
X value is -4.078956618559395
Iteration 108
X value is -4.097377486188207
Iteration 109
X value is -4.115429936464443
Iteration 110
X value is -4.133121337735154
Iteration 111
X value is -4.150458910980451
Iteration 112
X value is -4.167449732760842
Iteration 113
X value is -4.1841007381056246
Iteration 114
X value is -4.200418723343512
Iteration 115
X value is -4.216410348876642
Iteration 116
X value is -4.2320821418991095
Iteration 117
X value is -4.247440499061128
Iteration 118
X value is -4.262491689079905
Iteration 119
X value is -4.277241855298307
Iteration 120
X value is -4.291697018192341
Iteration 121
X value is -4.305863077828494
Iteration 122
X value is -4.319745816271924
Iteration 123
X value is -4.333350899946486
Iteration 124
X value is -4.3466838819475555
Iteration 125
X value is -4.359750204308605
Iteration 126
X value is -4.372555200222433
Iteration 127
X value is -4.385104096217984
Iteration 128
X value is -4.3974020142936245
Iteration 129
X value is -4.409453974007752
Iteration 130
X value is -4.421264894527597
Iteration 131
X value is -4.432839596637045
Iteration 132
X value is -4.444182804704305
Iteration 133
X value is -4.4552991486102185
Iteration 134
X value is -4.466193165638014
Iteration 135
X value is -4.4768693023252535
Iteration 136
X value is -4.487331916278748
Iteration 137
X value is -4.497585277953173
Iteration 138
X value is -4.50763357239411
Iteration 139
X value is -4.517480900946228
Iteration 140
X value is -4.527131282927304
Iteration 141
X value is -4.536588657268758
Iteration 142
X value is -4.545856884123382
Iteration 143
X value is -4.5549397464409145
Iteration 144
X value is -4.563840951512097
Iteration 145
X value is -4.572564132481855
Iteration 146
X value is -4.581112849832218
Iteration 147
X value is -4.589490592835574
Iteration 148
X value is -4.597700780978863
Iteration 149
X value is -4.605746765359285
Iteration 150
X value is -4.6136318300521
Iteration 151
X value is -4.621359193451058
Iteration 152
X value is -4.628932009582036
Iteration 153
X value is -4.636353369390395
Iteration 154
X value is -4.643626302002588
Iteration 155
X value is -4.650753775962536
Iteration 156
X value is -4.657738700443285
Iteration 157
X value is -4.664583926434419
Iteration 158
X value is -4.671292247905731
Iteration 159
X value is -4.6778664029476165
Iteration 160
X value is -4.684309074888664
Iteration 161
X value is -4.6906228933908904
Iteration 162
X value is -4.696810435523073
Iteration 163
X value is -4.702874226812612
Iteration 164
X value is -4.708816742276359
Iteration 165
X value is -4.714640407430832
Iteration 166
X value is -4.720347599282215
Iteration 167
X value is -4.725940647296571
Iteration 168
X value is -4.731421834350639
Iteration 169
X value is -4.736793397663627
Iteration 170
X value is -4.742057529710355
Iteration 171
X value is -4.747216379116147
Iteration 172
X value is -4.752272051533824
Iteration 173
X value is -4.757226610503148
Iteration 174
X value is -4.762082078293084
Iteration 175
X value is -4.766840436727223
Iteration 176
X value is -4.771503627992678
Iteration 177
X value is -4.776073555432824
Iteration 178
X value is -4.780552084324168
Iteration 179
X value is -4.784941042637685
Iteration 180
X value is -4.7892422217849315
Iteration 181
X value is -4.793457377349233
Iteration 182
X value is -4.7975882298022485
Iteration 183
X value is -4.801636465206204
Iteration 184
X value is -4.805603735902079
Iteration 185
X value is -4.809491661184038
Iteration 186
X value is -4.813301827960357
Iteration 187
X value is -4.81703579140115
Iteration 188
X value is -4.820695075573127
Iteration 189
X value is -4.824281174061665
Iteration 190
X value is -4.827795550580431
Iteration 191
X value is -4.831239639568823
Iteration 192
X value is -4.834614846777447
Iteration 193
X value is -4.837922549841898
Iteration 194
X value is -4.84116409884506
Iteration 195
X value is -4.844340816868159
Iteration 196
X value is -4.847454000530796
Iteration 197
X value is -4.85050492052018
Iteration 198
X value is -4.853494822109776
Iteration 199
X value is -4.85642492566758
Iteration 200
X value is -4.859296427154229
Iteration 201
X value is -4.862110498611145
Iteration 202
X value is -4.864868288638922
Iteration 203
X value is -4.867570922866143
Iteration 204
X value is -4.87021950440882
Iteration 205
X value is -4.872815114320644
Iteration 206
X value is -4.875358812034231
Iteration 207
X value is -4.877851635793546
Iteration 208
X value is -4.880294603077676
Iteration 209
X value is -4.882688711016122
Iteration 210
X value is -4.8850349367958
Iteration 211
X value is -4.887334238059884
Iteration 212
X value is -4.8895875532986866
Iteration 213
X value is -4.891795802232712
Iteration 214
X value is -4.893959886188058
Iteration 215
X value is -4.896080688464297
Iteration 216
X value is -4.898159074695011
Iteration 217
X value is -4.9001958932011105
Iteration 218
X value is -4.902191975337089
Iteration 219
X value is -4.904148135830347
Iteration 220
X value is -4.90606517311374
Iteration 221
X value is -4.907943869651465
Iteration 222
X value is -4.909784992258436
Iteration 223
X value is -4.911589292413267
Iteration 224
X value is -4.913357506565002
Iteration 225
X value is -4.915090356433702
Iteration 226
X value is -4.9167885493050285
Iteration 227
X value is -4.918452778318928
Iteration 228
X value is -4.920083722752549
Iteration 229
X value is -4.921682048297498
Iteration 230
X value is -4.923248407331548
Iteration 231
X value is -4.9247834391849175
Iteration 232
X value is -4.926287770401219
Iteration 233
X value is -4.927762014993195
Iteration 234
X value is -4.929206774693331
Iteration 235
X value is -4.930622639199464
Iteration 236
X value is -4.932010186415474
Iteration 237
X value is -4.933369982687164
Iteration 238
X value is -4.934702583033421
Iteration 239
X value is -4.936008531372753
Iteration 240
X value is -4.937288360745298
Iteration 241
X value is -4.938542593530392
Iteration 242
X value is -4.939771741659784
Iteration 243
X value is -4.940976306826588
Iteration 244
X value is -4.942156780690056
Iteration 245
X value is -4.943313645076255
Iteration 246
X value is -4.94444737217473
Iteration 247
X value is -4.945558424731236
Iteration 248
X value is -4.946647256236611
Iteration 249
X value is -4.947714311111879
Iteration 250
X value is -4.9487600248896415
Iteration 251
X value is -4.949784824391848
Iteration 252
X value is -4.950789127904011
Iteration 253
X value is -4.951773345345931
Iteration 254
X value is -4.952737878439012
Iteration 255
X value is -4.953683120870232
Iteration 256
X value is -4.954609458452827
Iteration 257
X value is -4.955517269283771
Iteration 258
X value is -4.956406923898095
Iteration 259
X value is -4.957278785420133
Iteration 260
X value is -4.958133209711731
Iteration 261
X value is -4.958970545517496
Iteration 262
X value is -4.959791134607146
Iteration 263
X value is -4.960595311915003
Iteration 264
X value is -4.9613834056767026
Iteration 265
X value is -4.962155737563169
Iteration 266
X value is -4.962912622811905
Iteration 267
X value is -4.963654370355667
Iteration 268
X value is -4.964381282948554
Iteration 269
X value is -4.965093657289583
Iteration 270
X value is -4.965791784143791
Iteration 271
X value is -4.966475948460915
Iteration 272
X value is -4.967146429491697
Iteration 273
X value is -4.967803500901863
Iteration 274
X value is -4.968447430883826
Iteration 275
X value is -4.969078482266149
Iteration 276
X value is -4.969696912620826
Iteration 277
X value is -4.970302974368409
Iteration 278
X value is -4.970896914881041
Iteration 279
X value is -4.97147897658342
Iteration 280
X value is -4.972049397051752
Iteration 281
X value is -4.972608409110717
Iteration 282
X value is -4.973156240928502
Iteration 283
X value is -4.973693116109932
Iteration 284
X value is -4.974219253787734
Iteration 285
X value is -4.974734868711979
Iteration 286
X value is -4.975240171337739
Iteration 287
X value is -4.975735367910985
Iteration 288
X value is -4.976220660552765
Iteration 289
X value is -4.976696247341709
Iteration 290
X value is -4.977162322394875
Iteration 291
X value is -4.977619075946977
Iteration 292
X value is -4.978066694428038
Iteration 293
X value is -4.978505360539477
Iteration 294
X value is -4.978935253328687
Iteration 295
X value is -4.979356548262113
Iteration 296
X value is -4.979769417296871
Iteration 297
X value is -4.980174028950934
Iteration 298
X value is -4.980570548371915
Iteration 299
X value is -4.980959137404477
Iteration 300
X value is -4.981339954656387
Iteration 301
X value is -4.981713155563259
Iteration 302
X value is -4.982078892451994
Iteration 303
X value is -4.9824373146029535
Iteration 304
X value is -4.982788568310895
Iteration 305
X value is -4.983132796944677
Iteration 306
X value is -4.983470141005784
Iteration 307
X value is -4.983800738185668
Iteration 308
X value is -4.984124723421955
Iteration 309
X value is -4.984442228953515
Iteration 310
X value is -4.984753384374445
Iteration 311
X value is -4.985058316686956
Iteration 312
X value is -4.9853571503532175
Iteration 313
X value is -4.985650007346153
Iteration 314
X value is -4.9859370071992295
Iteration 315
X value is -4.986218267055245
Iteration 316
X value is -4.98649390171414
Iteration 317
X value is -4.986764023679857
Iteration 318
X value is -4.98702874320626
Iteration 319
X value is -4.987288168342134
Iteration 320
X value is -4.987542404975292
Iteration 321
X value is -4.987791556875786
Iteration 322
X value is -4.98803572573827
Iteration 323
X value is -4.988275011223505
Iteration 324
X value is -4.988509510999035
Iteration 325
X value is -4.988739320779054
Iteration 326
X value is -4.988964534363473
Iteration 327
X value is -4.989185243676204
Iteration 328
X value is -4.98940153880268
Iteration 329
X value is -4.989613508026626
Iteration 330
X value is -4.989821237866094
Iteration 331
X value is -4.990024813108772
Iteration 332
X value is -4.9902243168465965
Iteration 333
X value is -4.990419830509665
Iteration 334
X value is -4.990611433899471
Iteration 335
X value is -4.990799205221482
Iteration 336
X value is -4.990983221117052
Iteration 337
X value is -4.991163556694711
Iteration 338
X value is -4.991340285560817
Iteration 339
X value is -4.9915134798496
Iteration 340
X value is -4.991683210252608
Iteration 341
X value is -4.991849546047556
Iteration 342
X value is -4.992012555126605
Iteration 343
X value is -4.992172304024073
Iteration 344
X value is -4.992328857943591
Iteration 345
X value is -4.99248228078472
Iteration 346
X value is -4.992632635169025
Iteration 347
X value is -4.9927799824656445
Iteration 348
X value is -4.992924382816332
Iteration 349
X value is -4.993065895160005
Iteration 350
X value is -4.993204577256805
Iteration 351
X value is -4.993340485711669
Iteration 352
X value is -4.993473675997436
Iteration 353
X value is -4.993604202477487
Iteration 354
X value is -4.993732118427937
Iteration 355
X value is -4.993857476059379
Iteration 356
X value is -4.993980326538191
Iteration 357
X value is -4.9941007200074266
Iteration 358
X value is -4.994218705607278
Iteration 359
X value is -4.994334331495133
Iteration 360
X value is -4.994447644865231
Iteration 361
X value is -4.994558691967926
Iteration 362
X value is -4.994667518128567
Iteration 363
X value is -4.994774167765996
Iteration 364
X value is -4.9948786844106765
Iteration 365
X value is -4.994981110722463
Iteration 366
X value is -4.995081488508014
Iteration 367
X value is -4.995179858737854
Iteration 368
X value is -4.995276261563097
Iteration 369
X value is -4.995370736331835
Iteration 370
X value is -4.9954633216051985
Iteration 371
X value is -4.995554055173095
Iteration 372
X value is -4.995642974069633
Iteration 373
X value is -4.99573011458824
Iteration 374
X value is -4.995815512296476
Iteration 375
X value is -4.995899202050547
Iteration 376
X value is -4.995981218009535
Iteration 377
X value is -4.996061593649345
Iteration 378
X value is -4.996140361776358
Iteration 379
X value is -4.996217554540831
Iteration 380
X value is -4.996293203450014
Iteration 381
X value is -4.996367339381013
Iteration 382
X value is -4.996439992593393
Iteration 383
X value is -4.996511192741525
Iteration 384
X value is -4.996580968886694
Iteration 385
X value is -4.99664934950896
Iteration 386
X value is -4.9967163625187805
Iteration 387
X value is -4.996782035268405
Iteration 388
X value is -4.996846394563037
Iteration 389
X value is -4.996909466671776
Iteration 390
X value is -4.996971277338341
Iteration 391
X value is -4.997031851791574
Iteration 392
X value is -4.997091214755742
Iteration 393
X value is -4.997149390460628
Iteration 394
X value is -4.997206402651415
Iteration 395
X value is -4.997262274598387
Iteration 396
X value is -4.997317029106419
Iteration 397
X value is -4.997370688524291
Iteration 398
X value is -4.997423274753805
Iteration 399
X value is -4.997474809258729
Iteration 400
X value is -4.997525313073554
Iteration 401
X value is -4.997574806812083
Iteration 402
X value is -4.997623310675841
Iteration 403
X value is -4.997670844462324
Iteration 404
X value is -4.997717427573078
Iteration 405
X value is -4.997763079021617
Iteration 406
X value is -4.997807817441185
Iteration 407
X value is -4.997851661092361
Iteration 408
X value is -4.997894627870514
Iteration 409
X value is -4.997936735313104
Iteration 410
X value is -4.9979780006068415
Iteration 411
X value is -4.998018440594705
Iteration 412
X value is -4.998058071782811
Iteration 413
X value is -4.998096910347155
Iteration 414
X value is -4.998134972140212
Iteration 415
X value is -4.998172272697408
Iteration 416
X value is -4.9982088272434595
Iteration 417
X value is -4.998244650698591
Iteration 418
X value is -4.998279757684619
Iteration 419
X value is -4.998314162530927
Iteration 420
X value is -4.998347879280309
Iteration 421
X value is -4.998380921694703
Iteration 422
X value is -4.998413303260809
Iteration 423
X value is -4.998445037195593
Iteration 424
X value is -4.998476136451681
Iteration 425
X value is -4.998506613722648
Iteration 426
X value is -4.998536481448195
Iteration 427
X value is -4.998565751819231
Iteration 428
X value is -4.998594436782846
Iteration 429
X value is -4.998622548047189
Iteration 430
X value is -4.998650097086245
Iteration 431
X value is -4.9986770951445205
Iteration 432
X value is -4.99870355324163
Iteration 433
X value is -4.998729482176797
Iteration 434
X value is -4.998754892533261
Iteration 435
X value is -4.998779794682596
Iteration 436
X value is -4.998804198788944
Iteration 437
X value is -4.998828114813166
Iteration 438
X value is -4.998851552516903
Iteration 439
X value is -4.998874521466565
Iteration 440
X value is -4.998897031037234
Iteration 441
X value is -4.998919090416489
Iteration 442
X value is -4.99894070860816
Iteration 443
X value is -4.998961894435997
Iteration 444
X value is -4.998982656547277
Iteration 445
X value is -4.999003003416331
Iteration 446
X value is -4.999022943348004
Iteration 447
X value is -4.999042484481044
Iteration 448
X value is -4.999061634791423
Iteration 449
X value is -4.999080402095594
Iteration 450
X value is -4.999098794053682
Iteration 451
X value is -4.999116818172609
Iteration 452
X value is -4.999134481809157
Iteration 453
X value is -4.999151792172974
Iteration 454
X value is -4.999168756329515
Iteration 455
X value is -4.999185381202924
Iteration 456
X value is -4.999201673578866
Iteration 457
X value is -4.999217640107289
Iteration 458
X value is -4.999233287305143
Iteration 459
X value is -4.9992486215590395
Iteration 460
X value is -4.999263649127859
Iteration 461
X value is -4.999278376145302
Iteration 462
X value is -4.999292808622396
Iteration 463
X value is -4.999306952449948
Iteration 464
X value is -4.999320813400949
Iteration 465
X value is -4.99933439713293
Iteration 466
X value is -4.999347709190272
Iteration 467
X value is -4.9993607550064665
Iteration 468
X value is -4.999373539906337
Iteration 469
X value is -4.99938606910821
Iteration 470
X value is -4.9993983477260455
Iteration 471
X value is -4.999410380771525
Iteration 472
X value is -4.999422173156094
Iteration 473
X value is -4.9994337296929725
Iteration 474
X value is -4.999445055099113
Iteration 475
X value is -4.999456153997131
Iteration 476
X value is -4.999467030917188
Iteration 477
X value is -4.9994776902988445
Iteration 478
X value is -4.999488136492867
Iteration 479
X value is -4.99949837376301
Iteration 480
X value is -4.99950840628775
Iteration 481
X value is -4.999518238161995
Iteration 482
X value is -4.999527873398756
Iteration 483
X value is -4.99953731593078
Iteration 484
X value is -4.999546569612165
Iteration 485
X value is -4.999555638219921
Iteration 486
X value is -4.999564525455523
Iteration 487
X value is -4.999573234946412
Iteration 488
X value is -4.9995817702474845
Iteration 489
X value is -4.999590134842535
Iteration 490
X value is -4.999598332145684
Iteration 491
X value is -4.99960636550277
Iteration 492
X value is -4.999614238192715
Iteration 493
X value is -4.999621953428861
Iteration 494
X value is -4.999629514360284
Iteration 495
X value is -4.999636924073078
Iteration 496
X value is -4.999644185591617
Iteration 497
X value is -4.999651301879784
Iteration 498
X value is -4.999658275842188
Iteration 499
X value is -4.999665110325345
Iteration 500
X value is -4.999671808118838
Iteration 501
X value is -4.9996783719564615
Iteration 502
X value is -4.999684804517332
Iteration 503
X value is -4.999691108426985
Iteration 504
X value is -4.999697286258446
Iteration 505
X value is -4.9997033405332765
Iteration 506
X value is -4.999709273722611
Iteration 507
X value is -4.999715088248159
Iteration 508
X value is -4.999720786483196
Iteration 509
X value is -4.999726370753532
Iteration 510
X value is -4.999731843338461
Iteration 511
X value is -4.999737206471692
Iteration 512
X value is -4.999742462342258
Iteration 513
X value is -4.999747613095413
Iteration 514
X value is -4.999752660833504
Iteration 515
X value is -4.999757607616834
Iteration 516
X value is -4.999762455464498
Iteration 517
X value is -4.999767206355208
Iteration 518
X value is -4.999771862228104
Iteration 519
X value is -4.999776424983542
Iteration 520
X value is -4.9997808964838715
Iteration 521
X value is -4.999785278554194
Iteration 522
X value is -4.9997895729831106
Iteration 523
X value is -4.999793781523448
Iteration 524
X value is -4.999797905892979
Iteration 525
X value is -4.999801947775119
Iteration 526
X value is -4.999805908819617
Iteration 527
X value is -4.999809790643225
Iteration 528
X value is -4.99981359483036
Iteration 529
X value is -4.999817322933753
Iteration 530
X value is -4.999820976475077
Iteration 531
X value is -4.999824556945576
Iteration 532
X value is -4.999828065806665
Iteration 533
X value is -4.9998315044905315
Iteration 534
X value is -4.999834874400721
Iteration 535
X value is -4.999838176912706
Iteration 536
X value is -4.999841413374452
Iteration 537
X value is -4.999844585106963
Iteration 538
X value is -4.999847693404824
Iteration 539
X value is -4.999850739536727
Iteration 540
X value is -4.999853724745993
Iteration 541
X value is -4.999856650251073
Iteration 542
X value is -4.999859517246051
Iteration 543
X value is -4.99986232690113
Iteration 544
X value is -4.999865080363108
Iteration 545
X value is -4.999867778755846
Iteration 546
X value is -4.999870423180729
Iteration 547
X value is -4.999873014717115
Iteration 548
X value is -4.999875554422772
Iteration 549
X value is -4.999878043334316
Iteration 550
X value is -4.99988048246763
Iteration 551
X value is -4.999882872818278
Iteration 552
X value is -4.999885215361912
Iteration 553
X value is -4.999887511054674
Iteration 554
X value is -4.999889760833581
Iteration 555
X value is -4.999891965616909
Iteration 556
X value is -4.999894126304571
Iteration 557
X value is -4.999896243778479
Iteration 558
X value is -4.999898318902909
Iteration 559
X value is -4.999900352524851
Iteration 560
X value is -4.9999023454743545
Iteration 561
X value is -4.999904298564868
Iteration 562
X value is -4.9999062125935705
Iteration 563
X value is -4.999908088341699
Iteration 564
X value is -4.9999099265748645
Iteration 565
X value is -4.999911728043367
Iteration 566
X value is -4.9999134934825
Iteration 567
X value is -4.99991522361285
Iteration 568
X value is -4.999916919140593
Iteration 569
X value is -4.999918580757781
Iteration 570
X value is -4.999920209142625
Iteration 571
X value is -4.999921804959773
Iteration 572
X value is -4.9999233688605775
Iteration 573
X value is -4.999924901483366
Iteration 574
X value is -4.999926403453699
Iteration 575
X value is -4.999927875384625
Iteration 576
X value is -4.999929317876933
Iteration 577
X value is -4.999930731519394
Iteration 578
X value is -4.999932116889006
Iteration 579
X value is -4.999933474551226
Iteration 580
X value is -4.999934805060202
Iteration 581
X value is -4.999936108958998
Iteration 582
X value is -4.999937386779818
Iteration 583
X value is -4.999938639044221
Iteration 584
X value is -4.999939866263337
Iteration 585
X value is -4.99994106893807
Iteration 586
X value is -4.999942247559309
Iteration 587
X value is -4.999943402608123
Iteration 588
X value is -4.9999445345559606
Iteration 589
X value is -4.999945643864842
Iteration 590
X value is -4.999946730987545
Iteration 591
X value is -4.999947796367794
Iteration 592
X value is -4.999948840440438
Iteration 593
X value is -4.999949863631629
Iteration 594
X value is -4.999950866358997
Iteration 595
X value is -4.9999518490318176
The local minimum occurs at -4.9999518490318176 | [
{
"code": null,
"e": 384,
"s": 171,
"text": "It is an optimization algorithm to find the minimum of a function. We start with a random point on the function and move in the negative direction of the gradient of the function to reach the local/global minima."
},
{
"code": null,
"e": 470,
"s": 384,
"text": "Question : Find the local minima of the function y=(x+5)2 starting from the point x=3"
},
{
"code": null,
"e": 661,
"s": 470,
"text": "Solution : We know the answer just by looking at the graph. y = (x+5)2 reaches it’s minimum value when x = -5 (i.e when x=-5, y=0). Hence x=-5 is the local and global minima of the function."
},
{
"code": null,
"e": 735,
"s": 661,
"text": "Now, let’s see how to obtain the same numerically using gradient descent."
},
{
"code": null,
"e": 819,
"s": 735,
"text": "Step 1 : Initialize x =3. Then, find the gradient of the function, dy/dx = 2*(x+5)."
},
{
"code": null,
"e": 995,
"s": 819,
"text": "Step 2 : Move in the direction of the negative of the gradient (Why?). But wait, how much to move? For that, we require a learning rate. Let us assume the learning rate → 0.01"
},
{
"code": null,
"e": 1051,
"s": 995,
"text": "Step 3 : Let’s perform 2 iterations of gradient descent"
},
{
"code": null,
"e": 1207,
"s": 1051,
"text": "Step 4 : We can observe that the X value is slowly decreasing and should converge to -5 (the local minima). However, how many iterations should we perform?"
},
{
"code": null,
"e": 1448,
"s": 1207,
"text": "Let us set a precision variable in our algorithm which calculates the difference between two consecutive “x” values . If the difference between x values from 2 consecutive iterations is lesser than the precision we set, stop the algorithm !"
},
{
"code": null,
"e": 1479,
"s": 1448,
"text": "Step 1 : Initialize parameters"
},
{
"code": null,
"e": 1757,
"s": 1479,
"text": "cur_x = 3 # The algorithm starts at x=3rate = 0.01 # Learning rateprecision = 0.000001 #This tells us when to stop the algorithmprevious_step_size = 1 #max_iters = 10000 # maximum number of iterationsiters = 0 #iteration counterdf = lambda x: 2*(x+5) #Gradient of our function "
},
{
"code": null,
"e": 1807,
"s": 1757,
"text": "Step 2 : Run a loop to perform gradient descent :"
},
{
"code": null,
"e": 1949,
"s": 1807,
"text": "i. Stop loop when difference between x values from 2 consecutive iterations is less than 0.000001 or when number of iterations exceeds 10,000"
},
{
"code": null,
"e": 2318,
"s": 1949,
"text": "while previous_step_size > precision and iters < max_iters: prev_x = cur_x #Store current x value in prev_x cur_x = cur_x - rate * df(prev_x) #Grad descent previous_step_size = abs(cur_x - prev_x) #Change in x iters = iters+1 #iteration count print(\"Iteration\",iters,\"\\nX value is\",cur_x) #Print iterations print(\"The local minimum occurs at\", cur_x)"
},
{
"code": null,
"e": 2577,
"s": 2318,
"text": "Output : From the output below, we can observe the x values for the first 10 iterations- which can be cross checked with our calculation above. The algorithm runs for 595 iterations before it terminates. The code and solution is embedded below for reference."
},
{
"code": null,
"e": 2598,
"s": 2577,
"text": "Connect on LinkedIn."
},
{
"code": null,
"e": 2882,
"s": 2598,
"text": "cur_x = 3 # The algorithm starts at x=3\nrate = 0.01 # Learning rate\nprecision = 0.000001 #This tells us when to stop the algorithm\nprevious_step_size = 1 #\nmax_iters = 10000 # maximum number of iterations\niters = 0 #iteration counter\ndf = lambda x: 2*(x+5) #Gradient of our function\n"
},
{
"code": null,
"e": 3259,
"s": 2882,
"text": "while previous_step_size > precision and iters < max_iters:\n prev_x = cur_x #Store current x value in prev_x\n cur_x = cur_x - rate * df(prev_x) #Grad descent\n previous_step_size = abs(cur_x - prev_x) #Change in x\n iters = iters+1 #iteration count\n print(\"Iteration\",iters,\"\\nX value is\",cur_x) #Print iterations\n \nprint(\"The local minimum occurs at\", cur_x)\n"
}
] |
Check if removing an edge can divide a Binary Tree in two halves - GeeksforGeeks | 10 May, 2021
Given a Binary Tree, find if there exists an edge whose removal creates two trees of equal size.
Examples:
Input : root of following tree
5
/ \
1 6
/ / \
3 7 4
Output : true
Removing edge 5-6 creates two trees of equal size
Input : root of following tree
5
/ \
1 6
/ \
7 4
/ \ \
3 2 8
Output : false
There is no edge whose removal creates two trees
of equal size.
Source- Kshitij IIT KGP
Method 1 (Simple) First count number of nodes in whole tree. Let count of all nodes be n. Now traverse tree and for every node, find size of subtree rooted with this node. Let the subtree size be s. If n-s is equal to s, then return true, else false.
C++
Java
Python3
C#
Javascript
// C++ program to check if there exist an edge whose// removal creates two trees of same size#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* left, *right;}; // utility function to create a new nodestruct Node* newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp;}; // To calculate size of tree with given rootint count(Node* root){ if (root==NULL) return 0; return count(root->left) + count(root->right) + 1;} // This function returns true if there is an edge// whose removal can divide the tree in two halves// n is size of treebool checkRec(Node* root, int n){ // Base cases if (root ==NULL) return false; // Check for root if (count(root) == n-count(root)) return true; // Check for rest of the nodes return checkRec(root->left, n) || checkRec(root->right, n);} // This function mainly uses checkRec()bool check(Node *root){ // Count total nodes in given tree int n = count(root); // Now recursively check all nodes return checkRec(root, n);} // Driver codeint main(){ struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf("YES") : printf("NO"); return 0;}
// Java program to check if there exist an edge whose// removal creates two trees of same size class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; // To calculate size of tree with given root int count(Node node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns true if there is an edge // whose removal can divide the tree in two halves // n is size of tree boolean checkRec(Node node, int n) { // Base cases if (node == null) return false; // Check for root if (count(node) == n - count(node)) return true; // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n); } // This function mainly uses checkRec() boolean check(Node node) { // Count total nodes in given tree int n = count(node); // Now recursively check all nodes return checkRec(node, n); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if(tree.check(tree.root)==true) System.out.println("YES"); else System.out.println("NO"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Python3 program to check if there# exist an edge whose removal creates# two trees of same size # utility function to create a new nodeclass newNode: def __init__(self, x): self.data = x self.left = self.right = None # To calculate size of tree# with given rootdef count(root): if (root == None): return 0 return (count(root.left) + count(root.right) + 1) # This function returns true if there# is an edge whose removal can divide# the tree in two halves n is size of treedef checkRec(root, n): # Base cases if (root == None): return False # Check for root if (count(root) == n - count(root)): return True # Check for rest of the nodes return (checkRec(root.left, n) or checkRec(root.right, n)) # This function mainly uses checkRec()def check(root): # Count total nodes in given tree n = count(root) # Now recursively check all nodes return checkRec(root, n) # Driver codeif __name__ == '__main__': root = newNode(5) root.left = newNode(1) root.right = newNode(6) root.left.left = newNode(3) root.right.left = newNode(7) root.right.right = newNode(4) if check(root): print("YES") else: print("NO") # This code is contributed by PranchalK
// C# program to check if there exist// an edge whose removal creates two// trees of same sizeusing System; public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; // To calculate size of tree with given rootpublic virtual int count(Node node){ if (node == null) { return 0; } return count(node.left) + count(node.right) + 1;} // This function returns true if there// is an edge whose removal can divide// the tree in two halves n is size of treepublic virtual bool checkRec(Node node, int n){ // Base cases if (node == null) { return false; } // Check for root if (count(node) == n - count(node)) { return true; } // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n);} // This function mainly uses checkRec()public virtual bool check(Node node){ // Count total nodes in given tree int n = count(node); // Now recursively check all nodes return checkRec(node, n);} // Driver codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); }}} // This code is contributed by Shrikant13
<script> // Javascript program to check if// there exist an edge whose// removal creates two trees of same size class Node { constructor(key) { this.key=key; this.left=this.right=null; } } // To calculate size of tree // with given root function count(node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns true // if there is an edge // whose removal can divide the // tree in two halves // n is size of tree function checkRec(node,n) { // Base cases if (node == null) return false; // Check for root if (count(node) == n - count(node)) return true; // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n); } // This function mainly uses checkRec() function check(node) { // Count total nodes in given tree let n = count(node); // Now recursively check all nodes return checkRec(node, n); } // Driver code let root = new Node(5); root.left = new Node(1); root.right = new Node(6); root.left.left = new Node(3); root.right.left = new Node(7); root.right.right = new Node(4); if(check(root)==true) document.write("YES"); else document.write("NO"); // This code is contributed by unknown2108 </script>
Output :
YES
Time complexity of above solution is O(n2) where n is number of nodes in given Binary Tree.
Method 2 (Efficient) We can find the solution in O(n) time. The idea is to traverse tree in bottom up manner and while traversing keep updating size and keep checking if there is a node that follows the required property.
Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to check if there exist an edge whose// removal creates two trees of same size#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* left, *right;}; // utility function to create a new nodestruct Node* newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp;}; // To calculate size of tree with given rootint count(Node* root){ if (root==NULL) return 0; return count(root->left) + count(root->right) + 1;} // This function returns size of tree rooted with given// root. It also set "res" as true if there is an edge// whose removal divides tree in two halves.// n is size of treeint checkRec(Node* root, int n, bool &res){ // Base case if (root == NULL) return 0; // Compute sizes of left and right children int c = checkRec(root->left, n, res) + 1 + checkRec(root->right, n, res); // If required property is true for current node // set "res" as true if (c == n-c) res = true; // Return size return c;} // This function mainly uses checkRec()bool check(Node *root){ // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes bool res = false; checkRec(root, n, res); return res;} // Driver codeint main(){ struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf("YES") : printf("NO"); return 0;}
// Java program to check if there exist an edge whose// removal creates two trees of same size class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class Res{ boolean res = false;} class BinaryTree{ Node root; // To calculate size of tree with given root int count(Node node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set "res" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree int checkRec(Node root, int n, Res res) { // Base case if (root == null) return 0; // Compute sizes of left and right children int c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set "res" as true if (c == n - c) res.res = true; // Return size return c; } // This function mainly uses checkRec() boolean check(Node root) { // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes Res res = new Res(); checkRec(root, n, res); return res.res; } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) System.out.println("YES"); else System.out.println("NO"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Python3 program to check if there exist# an edge whose removal creates two trees# of same sizeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None # To calculate size of tree with# given rootdef count(node): if (node == None): return 0 return (count(node.left) + count(node.right) + 1) # This function returns size of tree rooted# with given root. It also set "res" as true# if there is an edge whose removal divides# tree in two halves.n is size of treedef checkRec(root, n): global res # Base case if (root == None): return 0 # Compute sizes of left and right children c = (checkRec(root.left, n) + 1 + checkRec(root.right, n)) # If required property is true for # current node set "res" as true if (c == n - c): res = True # Return size return c # This function mainly uses checkRec()def check(root): # Count total nodes in given tree n = count(root) # Initialize result and recursively # check all nodes # bool res = false; checkRec(root, n) # Driver codeif __name__ == '__main__': res = False root = Node(5) root.left = Node(1) root.right = Node(6) root.left.left = Node(3) root.right.left = Node(7) root.right.right = Node(4) check(root) if res: print("YES") else: print("NO") # This code is contributed by mohit kumar 29
// C# program to check if there exist an edge whose// removal creates two trees of same sizeusing System; public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} public class Res{ public bool res = false;} public class BinaryTree{ public Node root; // To calculate size of tree with given root public virtual int count(Node node) { if (node == null) { return 0; } return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set "res" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree public virtual int checkRec(Node root, int n, Res res) { // Base case if (root == null) { return 0; } // Compute sizes of left and right children int c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set "res" as true if (c == n - c) { res.res = true; } // Return size return c; } // This function mainly uses checkRec() public virtual bool check(Node root) { // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes Res res = new Res(); checkRec(root, n, res); return res.res; } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } }} // This code is contributed by Shrikant13
<script>// javascript program to check if there exist an edge whose// removal creates two trees of same size class Node { constructor(key) { this.key = key; this.left = this.right = null; }} class Res {constructor(){ this.res = false; }} var root; // To calculate size of tree with given root function count( node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set "res" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree function checkRec( root , n, res) { // Base case if (root == null) return 0; // Compute sizes of left and right children var c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set "res" as true if (c == n - c) res.res = true; // Return size return c; } // This function mainly uses checkRec() function check( root) { // Count total nodes in given tree var n = count(root); // Initialize result and recursively check all nodes res = new Res(); checkRec(root, n, res); return res.res; } // Driver code root = new Node(5); root.left = new Node(1); root.right = new Node(6); root.left.left = new Node(3); root.right.left = new Node(7); root.right.right = new Node(4); if (check(root) == true) document.write("YES"); else document.write("NO"); // This code contributed by umadevi9616</script>
Output :
YES
This article is contributed by Asaad Akram. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
PranchalKatiyar
mohit kumar 29
unknown2108
umadevi9616
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
Insertion in a Binary Tree in level order
AVL Tree | Set 2 (Deletion) | [
{
"code": null,
"e": 24935,
"s": 24907,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 25032,
"s": 24935,
"text": "Given a Binary Tree, find if there exists an edge whose removal creates two trees of equal size."
},
{
"code": null,
"e": 25044,
"s": 25032,
"text": "Examples: "
},
{
"code": null,
"e": 25458,
"s": 25044,
"text": "Input : root of following tree\n 5\n / \\\n 1 6 \n / / \\\n 3 7 4\nOutput : true\nRemoving edge 5-6 creates two trees of equal size\n\n\nInput : root of following tree\n 5\n / \\\n 1 6 \n / \\\n 7 4\n / \\ \\\n 3 2 8\nOutput : false\nThere is no edge whose removal creates two trees\nof equal size."
},
{
"code": null,
"e": 25484,
"s": 25458,
"text": "Source- Kshitij IIT KGP "
},
{
"code": null,
"e": 25735,
"s": 25484,
"text": "Method 1 (Simple) First count number of nodes in whole tree. Let count of all nodes be n. Now traverse tree and for every node, find size of subtree rooted with this node. Let the subtree size be s. If n-s is equal to s, then return true, else false."
},
{
"code": null,
"e": 25739,
"s": 25735,
"text": "C++"
},
{
"code": null,
"e": 25744,
"s": 25739,
"text": "Java"
},
{
"code": null,
"e": 25752,
"s": 25744,
"text": "Python3"
},
{
"code": null,
"e": 25755,
"s": 25752,
"text": "C#"
},
{
"code": null,
"e": 25766,
"s": 25755,
"text": "Javascript"
},
{
"code": "// C++ program to check if there exist an edge whose// removal creates two trees of same size#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* left, *right;}; // utility function to create a new nodestruct Node* newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp;}; // To calculate size of tree with given rootint count(Node* root){ if (root==NULL) return 0; return count(root->left) + count(root->right) + 1;} // This function returns true if there is an edge// whose removal can divide the tree in two halves// n is size of treebool checkRec(Node* root, int n){ // Base cases if (root ==NULL) return false; // Check for root if (count(root) == n-count(root)) return true; // Check for rest of the nodes return checkRec(root->left, n) || checkRec(root->right, n);} // This function mainly uses checkRec()bool check(Node *root){ // Count total nodes in given tree int n = count(root); // Now recursively check all nodes return checkRec(root, n);} // Driver codeint main(){ struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf(\"YES\") : printf(\"NO\"); return 0;}",
"e": 27172,
"s": 25766,
"text": null
},
{
"code": "// Java program to check if there exist an edge whose// removal creates two trees of same size class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; // To calculate size of tree with given root int count(Node node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns true if there is an edge // whose removal can divide the tree in two halves // n is size of tree boolean checkRec(Node node, int n) { // Base cases if (node == null) return false; // Check for root if (count(node) == n - count(node)) return true; // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n); } // This function mainly uses checkRec() boolean check(Node node) { // Count total nodes in given tree int n = count(node); // Now recursively check all nodes return checkRec(node, n); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if(tree.check(tree.root)==true) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 28856,
"s": 27172,
"text": null
},
{
"code": "# Python3 program to check if there# exist an edge whose removal creates# two trees of same size # utility function to create a new nodeclass newNode: def __init__(self, x): self.data = x self.left = self.right = None # To calculate size of tree# with given rootdef count(root): if (root == None): return 0 return (count(root.left) + count(root.right) + 1) # This function returns true if there# is an edge whose removal can divide# the tree in two halves n is size of treedef checkRec(root, n): # Base cases if (root == None): return False # Check for root if (count(root) == n - count(root)): return True # Check for rest of the nodes return (checkRec(root.left, n) or checkRec(root.right, n)) # This function mainly uses checkRec()def check(root): # Count total nodes in given tree n = count(root) # Now recursively check all nodes return checkRec(root, n) # Driver codeif __name__ == '__main__': root = newNode(5) root.left = newNode(1) root.right = newNode(6) root.left.left = newNode(3) root.right.left = newNode(7) root.right.right = newNode(4) if check(root): print(\"YES\") else: print(\"NO\") # This code is contributed by PranchalK",
"e": 30151,
"s": 28856,
"text": null
},
{
"code": "// C# program to check if there exist// an edge whose removal creates two// trees of same sizeusing System; public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; // To calculate size of tree with given rootpublic virtual int count(Node node){ if (node == null) { return 0; } return count(node.left) + count(node.right) + 1;} // This function returns true if there// is an edge whose removal can divide// the tree in two halves n is size of treepublic virtual bool checkRec(Node node, int n){ // Base cases if (node == null) { return false; } // Check for root if (count(node) == n - count(node)) { return true; } // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n);} // This function mainly uses checkRec()public virtual bool check(Node node){ // Count total nodes in given tree int n = count(node); // Now recursively check all nodes return checkRec(node, n);} // Driver codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); }}} // This code is contributed by Shrikant13",
"e": 31741,
"s": 30151,
"text": null
},
{
"code": "<script> // Javascript program to check if// there exist an edge whose// removal creates two trees of same size class Node { constructor(key) { this.key=key; this.left=this.right=null; } } // To calculate size of tree // with given root function count(node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns true // if there is an edge // whose removal can divide the // tree in two halves // n is size of tree function checkRec(node,n) { // Base cases if (node == null) return false; // Check for root if (count(node) == n - count(node)) return true; // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n); } // This function mainly uses checkRec() function check(node) { // Count total nodes in given tree let n = count(node); // Now recursively check all nodes return checkRec(node, n); } // Driver code let root = new Node(5); root.left = new Node(1); root.right = new Node(6); root.left.left = new Node(3); root.right.left = new Node(7); root.right.right = new Node(4); if(check(root)==true) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by unknown2108 </script>",
"e": 33271,
"s": 31741,
"text": null
},
{
"code": null,
"e": 33280,
"s": 33271,
"text": "Output :"
},
{
"code": null,
"e": 33284,
"s": 33280,
"text": "YES"
},
{
"code": null,
"e": 33376,
"s": 33284,
"text": "Time complexity of above solution is O(n2) where n is number of nodes in given Binary Tree."
},
{
"code": null,
"e": 33598,
"s": 33376,
"text": "Method 2 (Efficient) We can find the solution in O(n) time. The idea is to traverse tree in bottom up manner and while traversing keep updating size and keep checking if there is a node that follows the required property."
},
{
"code": null,
"e": 33642,
"s": 33598,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 33646,
"s": 33642,
"text": "C++"
},
{
"code": null,
"e": 33651,
"s": 33646,
"text": "Java"
},
{
"code": null,
"e": 33659,
"s": 33651,
"text": "Python3"
},
{
"code": null,
"e": 33662,
"s": 33659,
"text": "C#"
},
{
"code": null,
"e": 33673,
"s": 33662,
"text": "Javascript"
},
{
"code": "// C++ program to check if there exist an edge whose// removal creates two trees of same size#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* left, *right;}; // utility function to create a new nodestruct Node* newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp;}; // To calculate size of tree with given rootint count(Node* root){ if (root==NULL) return 0; return count(root->left) + count(root->right) + 1;} // This function returns size of tree rooted with given// root. It also set \"res\" as true if there is an edge// whose removal divides tree in two halves.// n is size of treeint checkRec(Node* root, int n, bool &res){ // Base case if (root == NULL) return 0; // Compute sizes of left and right children int c = checkRec(root->left, n, res) + 1 + checkRec(root->right, n, res); // If required property is true for current node // set \"res\" as true if (c == n-c) res = true; // Return size return c;} // This function mainly uses checkRec()bool check(Node *root){ // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes bool res = false; checkRec(root, n, res); return res;} // Driver codeint main(){ struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf(\"YES\") : printf(\"NO\"); return 0;}",
"e": 35287,
"s": 33673,
"text": null
},
{
"code": "// Java program to check if there exist an edge whose// removal creates two trees of same size class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class Res{ boolean res = false;} class BinaryTree{ Node root; // To calculate size of tree with given root int count(Node node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set \"res\" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree int checkRec(Node root, int n, Res res) { // Base case if (root == null) return 0; // Compute sizes of left and right children int c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set \"res\" as true if (c == n - c) res.res = true; // Return size return c; } // This function mainly uses checkRec() boolean check(Node root) { // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes Res res = new Res(); checkRec(root, n, res); return res.res; } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 37244,
"s": 35287,
"text": null
},
{
"code": "# Python3 program to check if there exist# an edge whose removal creates two trees# of same sizeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None # To calculate size of tree with# given rootdef count(node): if (node == None): return 0 return (count(node.left) + count(node.right) + 1) # This function returns size of tree rooted# with given root. It also set \"res\" as true# if there is an edge whose removal divides# tree in two halves.n is size of treedef checkRec(root, n): global res # Base case if (root == None): return 0 # Compute sizes of left and right children c = (checkRec(root.left, n) + 1 + checkRec(root.right, n)) # If required property is true for # current node set \"res\" as true if (c == n - c): res = True # Return size return c # This function mainly uses checkRec()def check(root): # Count total nodes in given tree n = count(root) # Initialize result and recursively # check all nodes # bool res = false; checkRec(root, n) # Driver codeif __name__ == '__main__': res = False root = Node(5) root.left = Node(1) root.right = Node(6) root.left.left = Node(3) root.right.left = Node(7) root.right.right = Node(4) check(root) if res: print(\"YES\") else: print(\"NO\") # This code is contributed by mohit kumar 29",
"e": 38715,
"s": 37244,
"text": null
},
{
"code": "// C# program to check if there exist an edge whose// removal creates two trees of same sizeusing System; public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} public class Res{ public bool res = false;} public class BinaryTree{ public Node root; // To calculate size of tree with given root public virtual int count(Node node) { if (node == null) { return 0; } return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set \"res\" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree public virtual int checkRec(Node root, int n, Res res) { // Base case if (root == null) { return 0; } // Compute sizes of left and right children int c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set \"res\" as true if (c == n - c) { res.res = true; } // Return size return c; } // This function mainly uses checkRec() public virtual bool check(Node root) { // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes Res res = new Res(); checkRec(root, n, res); return res.res; } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(1); tree.root.right = new Node(6); tree.root.left.left = new Node(3); tree.root.right.left = new Node(7); tree.root.right.right = new Node(4); if (tree.check(tree.root) == true) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); } }} // This code is contributed by Shrikant13",
"e": 40818,
"s": 38715,
"text": null
},
{
"code": "<script>// javascript program to check if there exist an edge whose// removal creates two trees of same size class Node { constructor(key) { this.key = key; this.left = this.right = null; }} class Res {constructor(){ this.res = false; }} var root; // To calculate size of tree with given root function count( node) { if (node == null) return 0; return count(node.left) + count(node.right) + 1; } // This function returns size of tree rooted with given // root. It also set \"res\" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree function checkRec( root , n, res) { // Base case if (root == null) return 0; // Compute sizes of left and right children var c = checkRec(root.left, n, res) + 1 + checkRec(root.right, n, res); // If required property is true for current node // set \"res\" as true if (c == n - c) res.res = true; // Return size return c; } // This function mainly uses checkRec() function check( root) { // Count total nodes in given tree var n = count(root); // Initialize result and recursively check all nodes res = new Res(); checkRec(root, n, res); return res.res; } // Driver code root = new Node(5); root.left = new Node(1); root.right = new Node(6); root.left.left = new Node(3); root.right.left = new Node(7); root.right.right = new Node(4); if (check(root) == true) document.write(\"YES\"); else document.write(\"NO\"); // This code contributed by umadevi9616</script>",
"e": 42576,
"s": 40818,
"text": null
},
{
"code": null,
"e": 42585,
"s": 42576,
"text": "Output :"
},
{
"code": null,
"e": 42589,
"s": 42585,
"text": "YES"
},
{
"code": null,
"e": 42760,
"s": 42591,
"text": "This article is contributed by Asaad Akram. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 42772,
"s": 42760,
"text": "shrikanth13"
},
{
"code": null,
"e": 42788,
"s": 42772,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 42803,
"s": 42788,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 42815,
"s": 42803,
"text": "unknown2108"
},
{
"code": null,
"e": 42827,
"s": 42815,
"text": "umadevi9616"
},
{
"code": null,
"e": 42832,
"s": 42827,
"text": "Tree"
},
{
"code": null,
"e": 42837,
"s": 42832,
"text": "Tree"
},
{
"code": null,
"e": 42935,
"s": 42837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42944,
"s": 42935,
"text": "Comments"
},
{
"code": null,
"e": 42957,
"s": 42944,
"text": "Old Comments"
},
{
"code": null,
"e": 42971,
"s": 42957,
"text": "Decision Tree"
},
{
"code": null,
"e": 43031,
"s": 42971,
"text": "Inorder Tree Traversal without recursion and without stack!"
},
{
"code": null,
"e": 43089,
"s": 43031,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 43172,
"s": 43089,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 43208,
"s": 43172,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 43256,
"s": 43208,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 43291,
"s": 43256,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 43318,
"s": 43291,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 43360,
"s": 43318,
"text": "Insertion in a Binary Tree in level order"
}
] |
How does garbage collection work in Python? | Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.
An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python
class Point:
def __init__( self, x=0, y=0):
self.x = x self.y = y def __del__(self):
class_name = self.__class__.__name__ print class_name, "destroyed"
pt1 = Point()
pt2 = pt1 pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection."
},
{
"code": null,
"e": 1511,
"s": 1303,
"text": "Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes."
},
{
"code": null,
"e": 1848,
"s": 1511,
"text": "An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically."
},
{
"code": null,
"e": 2096,
"s": 1848,
"text": "a = 40 # Create object <40>\nb = a # Increase ref. count of <40>\nc = [b] # Increase ref. count of <40>\ndel a # Decrease ref. count of <40>\nb = 100 # Decrease ref. count of <40>\nc[0] = -1 # Decrease ref. count of <40>"
},
{
"code": null,
"e": 2427,
"s": 2096,
"text": "You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance."
},
{
"code": null,
"e": 2522,
"s": 2427,
"text": "This __del__() destructor prints the class name of an instance that is about to be destroyed −"
},
{
"code": null,
"e": 2845,
"s": 2522,
"text": "#!/usr/bin/python\nclass Point:\n def __init__( self, x=0, y=0):\n self.x = x self.y = y def __del__(self):\n class_name = self.__class__.__name__ print class_name, \"destroyed\"\n pt1 = Point()\npt2 = pt1 pt3 = pt1\nprint id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts\ndel pt1\ndel pt2\ndel pt3"
},
{
"code": null,
"e": 2909,
"s": 2845,
"text": "When the above code is executed, it produces following result −"
},
{
"code": null,
"e": 2958,
"s": 2909,
"text": "3083401324 3083401324 3083401324\nPoint destroyed"
}
] |
Python IMDbPY – Getting rating of the series - GeeksforGeeks | 10 May, 2020
In this article we will see how we can get the rating of the series, rating in IMDb is given from 10 points the rating is based on the viewer experience, the higher the rating means views are highly satisfied or in other words they like the movie.
In order to get this we have to do the following –
1. Get the series details with the help of get_movie method2. As this object will act as dictionary therefore we have to filter the object3. Get the main data of object with the help of data method which will return dictionary4. Get the rating details from the dictionary
Below is the implementation
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # idcode = "6468322" # getting informationseries = ia.get_movie(code) # getting rating of the seriesrating = series.data['rating'] # printing the object i.e nameprint(series) # print the ratingprint(rating)
Output :
Money Heist
8.5
Another example
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # idcode = "6077448" # getting informationseries = ia.get_movie(code) # getting rating of the seriesrating = series.data['rating'] # printing the object i.e nameprint(series) # print the ratingprint(rating)
Output :
Sacred Games
8.7
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1 | [
{
"code": null,
"e": 24083,
"s": 24055,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24331,
"s": 24083,
"text": "In this article we will see how we can get the rating of the series, rating in IMDb is given from 10 points the rating is based on the viewer experience, the higher the rating means views are highly satisfied or in other words they like the movie."
},
{
"code": null,
"e": 24382,
"s": 24331,
"text": "In order to get this we have to do the following –"
},
{
"code": null,
"e": 24654,
"s": 24382,
"text": "1. Get the series details with the help of get_movie method2. As this object will act as dictionary therefore we have to filter the object3. Get the main data of object with the help of data method which will return dictionary4. Get the rating details from the dictionary"
},
{
"code": null,
"e": 24682,
"s": 24654,
"text": "Below is the implementation"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # idcode = \"6468322\" # getting informationseries = ia.get_movie(code) # getting rating of the seriesrating = series.data['rating'] # printing the object i.e nameprint(series) # print the ratingprint(rating)",
"e": 24973,
"s": 24682,
"text": null
},
{
"code": null,
"e": 24982,
"s": 24973,
"text": "Output :"
},
{
"code": null,
"e": 24998,
"s": 24982,
"text": "Money Heist\n8.5"
},
{
"code": null,
"e": 25014,
"s": 24998,
"text": "Another example"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # idcode = \"6077448\" # getting informationseries = ia.get_movie(code) # getting rating of the seriesrating = series.data['rating'] # printing the object i.e nameprint(series) # print the ratingprint(rating)",
"e": 25305,
"s": 25014,
"text": null
},
{
"code": null,
"e": 25314,
"s": 25305,
"text": "Output :"
},
{
"code": null,
"e": 25331,
"s": 25314,
"text": "Sacred Games\n8.7"
},
{
"code": null,
"e": 25352,
"s": 25331,
"text": "Python IMDbPY-module"
},
{
"code": null,
"e": 25359,
"s": 25352,
"text": "Python"
},
{
"code": null,
"e": 25457,
"s": 25359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25466,
"s": 25457,
"text": "Comments"
},
{
"code": null,
"e": 25479,
"s": 25466,
"text": "Old Comments"
},
{
"code": null,
"e": 25497,
"s": 25479,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25519,
"s": 25497,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25551,
"s": 25519,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25593,
"s": 25551,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25619,
"s": 25593,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25644,
"s": 25619,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25681,
"s": 25644,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25737,
"s": 25681,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25766,
"s": 25737,
"text": "*args and **kwargs in Python"
}
] |
How to create a collapsible section with CSS and JavaScript? | To create a collapsible section with CSS and JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.collapse {
background-color: rgb(83, 186, 255);
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 18px;
}
.active, .collapse:hover {
background-color: rgb(34, 85, 160);
}
.content {
padding: 0 18px;
display: none;
overflow: hidden;
background-color: #b6fdff;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Collapsible Example</h1>
<h2>Click on the below collapsible to show the contents</h2>
<button type="button" class="collapse">Open Collapsible</button>
<div class="content">
<h3>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Optio, ducimus!
</h3>
</div>
<script>
var collapse = document.querySelector(".collapse");
var i;
collapse.addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Open Collapsible” − | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To create a collapsible section with CSS and JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1155,
"s": 1144,
"text": " Live Demo"
},
{
"code": null,
"e": 2489,
"s": 1155,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .collapse {\n background-color: rgb(83, 186, 255);\n color: white;\n cursor: pointer;\n padding: 18px;\n width: 100%;\n border: none;\n text-align: left;\n outline: none;\n font-size: 18px;\n }\n .active, .collapse:hover {\n background-color: rgb(34, 85, 160);\n }\n .content {\n padding: 0 18px;\n display: none;\n overflow: hidden;\n background-color: #b6fdff;\n font-size: 18px;\n }\n</style>\n</head>\n<body>\n<h1>Collapsible Example</h1>\n<h2>Click on the below collapsible to show the contents</h2>\n<button type=\"button\" class=\"collapse\">Open Collapsible</button>\n<div class=\"content\">\n<h3>\nLorem ipsum dolor, sit amet consectetur adipisicing elit. Optio, ducimus!\n</h3>\n</div>\n<script>\n var collapse = document.querySelector(\".collapse\");\n var i;\n collapse.addEventListener(\"click\", function() {\n this.classList.toggle(\"active\");\n var content = this.nextElementSibling;\n if (content.style.display === \"block\") {\n content.style.display = \"none\";\n } else {\n content.style.display = \"block\";\n }\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2540,
"s": 2489,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2577,
"s": 2540,
"text": "On clicking the “Open Collapsible” −"
}
] |
Path iterator() method in Java with Examples | 30 Jul, 2019
The iterator() method of java.nio.file.Path used to returns an iterator of the name elements which construct this path.The first element of this iterator contains the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element of this iterator is the name of the file or directory denoted by this path. The root component is not returned by the iterator.
Syntax:
default Iterator<Path> iterator()
Parameters: This method accepts nothing.It is parameter less method.
Return value: This method returns an iterator over the name elements of this path.
Below programs illustrate iterator() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.iterator() method import java.nio.file.Path;import java.nio.file.Paths;import java.util.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("D:\\eclipse\\p2" + "\\org\\eclipse\\equinox\\p2\\core" + "\\cache\\binary"); // Creating an iterator Iterator<Path> elements = path.iterator(); // Displaying the values System.out.println("The iterator values are: "); while (elements.hasNext()) { System.out.println(elements.next()); } }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.iterator() method import java.nio.file.Path;import java.nio.file.Paths;import java.util.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("D:\\Workspace" + "\\nEclipseWork" + "\\GFG\\bin\\defaultpackage"); System.out.println("Original Path:" + path); // Creating an iterator Iterator<Path> elements = path.iterator(); // Displaying the values System.out.println("The iterator values are: "); while (elements.hasNext()) { System.out.println(elements.next()); } }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#iterator()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "The iterator() method of java.nio.file.Path used to returns an iterator of the name elements which construct this path.The first element of this iterator contains the name element that is closest to the root in the directory hierarchy, the second element is the next closest, and so on. The last element of this iterator is the name of the file or directory denoted by this path. The root component is not returned by the iterator."
},
{
"code": null,
"e": 468,
"s": 460,
"text": "Syntax:"
},
{
"code": null,
"e": 503,
"s": 468,
"text": "default Iterator<Path> iterator()\n"
},
{
"code": null,
"e": 572,
"s": 503,
"text": "Parameters: This method accepts nothing.It is parameter less method."
},
{
"code": null,
"e": 655,
"s": 572,
"text": "Return value: This method returns an iterator over the name elements of this path."
},
{
"code": null,
"e": 710,
"s": 655,
"text": "Below programs illustrate iterator() method:Program 1:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.iterator() method import java.nio.file.Path;import java.nio.file.Paths;import java.util.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"D:\\\\eclipse\\\\p2\" + \"\\\\org\\\\eclipse\\\\equinox\\\\p2\\\\core\" + \"\\\\cache\\\\binary\"); // Creating an iterator Iterator<Path> elements = path.iterator(); // Displaying the values System.out.println(\"The iterator values are: \"); while (elements.hasNext()) { System.out.println(elements.next()); } }}",
"e": 1402,
"s": 710,
"text": null
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.iterator() method import java.nio.file.Path;import java.nio.file.Paths;import java.util.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"D:\\\\Workspace\" + \"\\\\nEclipseWork\" + \"\\\\GFG\\\\bin\\\\defaultpackage\"); System.out.println(\"Original Path:\" + path); // Creating an iterator Iterator<Path> elements = path.iterator(); // Displaying the values System.out.println(\"The iterator values are: \"); while (elements.hasNext()) { System.out.println(elements.next()); } }}",
"e": 2175,
"s": 1413,
"text": null
},
{
"code": null,
"e": 2265,
"s": 2175,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#iterator()"
},
{
"code": null,
"e": 2280,
"s": 2265,
"text": "Java-Functions"
},
{
"code": null,
"e": 2290,
"s": 2280,
"text": "Java-Path"
},
{
"code": null,
"e": 2312,
"s": 2290,
"text": "java.nio.file package"
},
{
"code": null,
"e": 2317,
"s": 2312,
"text": "Java"
},
{
"code": null,
"e": 2322,
"s": 2317,
"text": "Java"
}
] |
Nested switch statement in C++ | 01 Dec, 2018
Switch-case statements:
These are a substitute for long if statements that compare a variable to several integral values
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if
// n doesn't match any cases
}
Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
Syntax:
switch(n)
{
// code to be executed if n = 1;
case 1:
// Nested switch
switch(num)
{
// code to be executed if num = 10
case 10:
statement 1;
break;
// code to be executed if num = 20
case 20:
statement 2;
break;
// code to be executed if num = 30
case 30:
statement 3;
break;
// code to be executed if n
// doesn't match any cases
default:
}
break;
// code to be executed if n = 2;
case 2:
statement 2;
break;
// code to be executed if n = 3;
case 3:
statement 3;
break;
// code to be executed if n doesn't match any cases
default:
}
Example:
// Following is a simple program to demonstrate// syntax of Nested Switch Statements. #include <iostream>using namespace std; int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: cout << "Choice is 2"; break; // If y == 3 case 3: cout << "Choice is 3"; break; } break; // If x == 4 case 4: cout << "Choice is 4"; break; // If x == 5 case 5: cout << "Choice is 5"; break; default: cout << "Choice is other than 1, 2 3, 4, or 5"; break; } return 0;}
Choice is 2
CPP-Control-Flow
cpp-switch
C++
C++ Programs
School Programming
Technical Scripter
CPP-Control-Flow
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Dec, 2018"
},
{
"code": null,
"e": 78,
"s": 54,
"text": "Switch-case statements:"
},
{
"code": null,
"e": 175,
"s": 78,
"text": "These are a substitute for long if statements that compare a variable to several integral values"
},
{
"code": null,
"e": 339,
"s": 175,
"text": "The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression."
},
{
"code": null,
"e": 421,
"s": 339,
"text": "Switch is a control statement that allows a value to change control of execution."
},
{
"code": null,
"e": 429,
"s": 421,
"text": "Syntax:"
},
{
"code": null,
"e": 627,
"s": 429,
"text": "switch (n)\n{\n case 1: // code to be executed if n = 1;\n break;\n case 2: // code to be executed if n = 2;\n break;\n default: // code to be executed if \n // n doesn't match any cases\n}"
},
{
"code": null,
"e": 652,
"s": 627,
"text": "Nested-Switch Statement:"
},
{
"code": null,
"e": 742,
"s": 652,
"text": "Nested-Switch statements refers to Switch statements inside of another Switch Statements."
},
{
"code": null,
"e": 750,
"s": 742,
"text": "Syntax:"
},
{
"code": null,
"e": 1459,
"s": 750,
"text": "switch(n)\n{\n // code to be executed if n = 1;\n case 1: \n \n // Nested switch\n switch(num) \n {\n // code to be executed if num = 10\n case 10: \n statement 1;\n break;\n \n // code to be executed if num = 20\n case 20: \n statement 2;\n break;\n \n // code to be executed if num = 30\n case 30: \n statement 3;\n break;\n \n // code to be executed if n \n // doesn't match any cases\n default: \n }\n \n \n break;\n \n // code to be executed if n = 2;\n case 2:\n statement 2;\n break;\n \n // code to be executed if n = 3;\n case 3: \n statement 3;\n break;\n \n // code to be executed if n doesn't match any cases\n default: \n}\n"
},
{
"code": null,
"e": 1468,
"s": 1459,
"text": "Example:"
},
{
"code": "// Following is a simple program to demonstrate// syntax of Nested Switch Statements. #include <iostream>using namespace std; int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: cout << \"Choice is 2\"; break; // If y == 3 case 3: cout << \"Choice is 3\"; break; } break; // If x == 4 case 4: cout << \"Choice is 4\"; break; // If x == 5 case 5: cout << \"Choice is 5\"; break; default: cout << \"Choice is other than 1, 2 3, 4, or 5\"; break; } return 0;}",
"e": 2192,
"s": 1468,
"text": null
},
{
"code": null,
"e": 2205,
"s": 2192,
"text": "Choice is 2\n"
},
{
"code": null,
"e": 2222,
"s": 2205,
"text": "CPP-Control-Flow"
},
{
"code": null,
"e": 2233,
"s": 2222,
"text": "cpp-switch"
},
{
"code": null,
"e": 2237,
"s": 2233,
"text": "C++"
},
{
"code": null,
"e": 2250,
"s": 2237,
"text": "C++ Programs"
},
{
"code": null,
"e": 2269,
"s": 2250,
"text": "School Programming"
},
{
"code": null,
"e": 2288,
"s": 2269,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2305,
"s": 2288,
"text": "CPP-Control-Flow"
},
{
"code": null,
"e": 2309,
"s": 2305,
"text": "CPP"
},
{
"code": null,
"e": 2407,
"s": 2309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2431,
"s": 2407,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2451,
"s": 2431,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2484,
"s": 2451,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2528,
"s": 2484,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2553,
"s": 2528,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2588,
"s": 2553,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2622,
"s": 2588,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2666,
"s": 2622,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2725,
"s": 2666,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Introduction to Scala | 24 Sep, 2021
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides the Javascript runtimes. Scala is highly influenced by Java and some other programming languages like Lisp, Haskell, Pizza, etc.
Evolution of Scala:Scala was designed by the Martin Odersky, professor of programming methods at École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland and a German computer scientist. Martin Odersky is also the co-creator of javac (Java Compiler), Generic Java, and EPFL’s Funnel programming language. He started to design the Scala in 2001. Scala was first released publicly in 2004 on the Java platform as its first version. In June 2004, Scala was modified for the .Net Framework. Soon it was followed by second version i.e. (v2.0) in 2006. At JavaOne conference in 2012, Scala was awarded as the winner of the ScriptBowl contest. From June 2012, Scala doesn’t provide any support for .Net Framework. The latest version of scala is 2.12.6 which released on 27-Apr-2018.
Scala has many reasons for being popular among programmers. Few of the reasons are :
Easy to Start: Scala is a high level language so it is closer to other popular programming languages like Java, C, C++. Thus it becomes very easy to learn Scala for anyone. For Java programmers, Scala is more easy to learn.
Contains best Features: Scala contains the features of different languages like C, C++, Java, etc. which makes the it more useful, scalable and productive.
Close integration with Java: The source code of the Scala is designed in such a way that its compiler can interpret the Java classes. Also, Its compiler can utilize the frameworks, Java Libraries, and tools etc. After compilation, Scala programs can run on JVM.
Web – Based & Desktop Application Development: For the web applications it provides the support by compiling to JavaScript. Similarly for desktop applications, it can be compiled to JVM bytecode.
Used by Big Companies: Most of the popular companies like Apple, Twitter, Walmart, Google etc. move their most of codes to Scala from some other languages. reason being it is highly scalable and can be used in backend operations.
Note: People always thinks that Scala is a extension of Java. But it is not true. It is just completely interoperable with Java. Scala programs get converted into .class file which contains Java Byte Code after the successful compilation and then can run on JVM(Java Virtual Machine).
Finding a Compiler: There are various online IDEs such as GeeksforGeeks IDE, Scala Fiddle IDE, etc. which can be used to run Scala programs without installing.
Programming in Scala: Since the Scala is a lot similar to other widely used languages syntactically, it is easier to code and learn in Scala. Programs can be written in Scala in any of the widely used text editors like Notepad++, gedit, etc. or on any of the text-editors. After writing the program, save the file with the extension .sc or .scala.
For Windows & Linux: Before installing the Scala on Windows or Linux, you must have Java Development Kit(JDK) 1.8 or greater installed on your system. Because Scala always runs on Java 1.8 or above. In this article, we will discuss how to run the Scala programs on online IDE’s.
Example : A simple program to print Hello Geeks! using object-oriented approach.
Scala
// Scala program to print Hello, Geeks!// by using object-oriented approach // creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, Geeks! println("Hello, Geeks!")}}
Output:
Hello, Geeks!
Comments: Comments are used for explaining the code and are used in a similar manner as in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines.
Single line Comments: Syntax:
// Single line comment
Multi line comments:Syntax:
/* Multi-line comments
syntax */
object Geeks: object is the keyword which is used to create the objects. Here “Geeks” is the name of the object.def main(args: Array[String]): def is the keyword in Scala which is used to define the function and “main” is the name of Main Method. args: Array[String] are used for the command line arguments.println(“Hello, Geeks!”): println is a method in Scala which is used to display the string on console.
Note: There is also functional approach that can be used in Scala programs. Some Online IDE doesn’t provide support for it. We will discuss it in upcoming articles.
There are many features which makes it different from other languages.
Object- Oriented: Every value in Scala is an object so it is a purely object-oriented programming language. The behavior and type of objects are depicted by the classes and traits in Scala.
Functional: It is also a functional programming language as every function is a value and every value is an object. It provides the support for the high-order functions, nested functions, anonymous functions, etc.
Statically Typed: The process of verifying and enforcing the constraints of types is done at compile time in Scala. Unlike other statically typed programming languages like C++, C, etc., Scala doesn’t expect the redundant type information from the user. In most cases, the user has no need to specify a type.
Extensible: New language constructs can be added to Scala in form of libraries. Scala is designed to interpolate with the JRE(Java Runtime Environment).
Concurrent & Synchronize Processing: Scala allows the user to write the codes in an immutable manner that makes it easy to apply the parallelism(Synchronize) and concurrency.
Run on JVM & Can Execute Java Code: Java and Scala have a common runtime environment. So the user can easily move from Java to Scala. The Scala compiler compiles the program into .class file, containing the Bytecode that can be executed by JVM. All the classes of Java SDK can be used by Scala. With the help of Scala user can customize the Java classes.
Advantages:
Scala’s complex features provided the better coding and efficiency in performance.
Tuples, macros, and functions are the advancements in Scala.
It incorporates the object-oriented and functional programming which in turn make it a powerful language.
It is highly scalable and thus provides a better support for backend operations.
It reduces the risk associated with the thread-safety which is higher in Java.
Due to the functional approach, generally, a user ends up with fewer lines of codes and bugs which result in higher productivity and quality.
Due to lazy computation, Scala computes the expressions only when they are required in the program.
There are no static methods and variables in Scala. It uses the singleton object(class with one object in the source file).
It also provides the Traits concept. Traits are the collection of abstract and non-abstract methods which can be compiled into Java interfaces.
Disadvantages:
Sometimes, two approaches make the Scala hard to understand.
There is a limited number of Scala developers available in comparison to Java developers.
It has no true-tail recursive optimization as it runs on JVM.
It always revolves around the object-oriented concept because every function is value and every value is an object in Scala.
Applications:
It is mostly used in data analysis with the spark.
Used to develop the web-applications and API.
It provide the facility to develop the frameworks and libraries.
Preferred to use in backend operations to improve the productivity of developers.
Parallel batch processing can be done using Scala.
surinderdawra388
sweetyty
Scala-Basics
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | map() method
Scala | flatMap Method
String concatenation in Scala
Scala | reduce() Function
Type Casting in Scala
Scala List filter() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example
How to Install Scala with VSCode? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 696,
"s": 52,
"text": "Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides the Javascript runtimes. Scala is highly influenced by Java and some other programming languages like Lisp, Haskell, Pizza, etc."
},
{
"code": null,
"e": 1481,
"s": 696,
"text": "Evolution of Scala:Scala was designed by the Martin Odersky, professor of programming methods at École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland and a German computer scientist. Martin Odersky is also the co-creator of javac (Java Compiler), Generic Java, and EPFL’s Funnel programming language. He started to design the Scala in 2001. Scala was first released publicly in 2004 on the Java platform as its first version. In June 2004, Scala was modified for the .Net Framework. Soon it was followed by second version i.e. (v2.0) in 2006. At JavaOne conference in 2012, Scala was awarded as the winner of the ScriptBowl contest. From June 2012, Scala doesn’t provide any support for .Net Framework. The latest version of scala is 2.12.6 which released on 27-Apr-2018."
},
{
"code": null,
"e": 1568,
"s": 1481,
"text": "Scala has many reasons for being popular among programmers. Few of the reasons are : "
},
{
"code": null,
"e": 1792,
"s": 1568,
"text": "Easy to Start: Scala is a high level language so it is closer to other popular programming languages like Java, C, C++. Thus it becomes very easy to learn Scala for anyone. For Java programmers, Scala is more easy to learn."
},
{
"code": null,
"e": 1948,
"s": 1792,
"text": "Contains best Features: Scala contains the features of different languages like C, C++, Java, etc. which makes the it more useful, scalable and productive."
},
{
"code": null,
"e": 2210,
"s": 1948,
"text": "Close integration with Java: The source code of the Scala is designed in such a way that its compiler can interpret the Java classes. Also, Its compiler can utilize the frameworks, Java Libraries, and tools etc. After compilation, Scala programs can run on JVM."
},
{
"code": null,
"e": 2406,
"s": 2210,
"text": "Web – Based & Desktop Application Development: For the web applications it provides the support by compiling to JavaScript. Similarly for desktop applications, it can be compiled to JVM bytecode."
},
{
"code": null,
"e": 2636,
"s": 2406,
"text": "Used by Big Companies: Most of the popular companies like Apple, Twitter, Walmart, Google etc. move their most of codes to Scala from some other languages. reason being it is highly scalable and can be used in backend operations."
},
{
"code": null,
"e": 2922,
"s": 2636,
"text": "Note: People always thinks that Scala is a extension of Java. But it is not true. It is just completely interoperable with Java. Scala programs get converted into .class file which contains Java Byte Code after the successful compilation and then can run on JVM(Java Virtual Machine). "
},
{
"code": null,
"e": 3082,
"s": 2922,
"text": "Finding a Compiler: There are various online IDEs such as GeeksforGeeks IDE, Scala Fiddle IDE, etc. which can be used to run Scala programs without installing."
},
{
"code": null,
"e": 3431,
"s": 3082,
"text": "Programming in Scala: Since the Scala is a lot similar to other widely used languages syntactically, it is easier to code and learn in Scala. Programs can be written in Scala in any of the widely used text editors like Notepad++, gedit, etc. or on any of the text-editors. After writing the program, save the file with the extension .sc or .scala. "
},
{
"code": null,
"e": 3711,
"s": 3431,
"text": "For Windows & Linux: Before installing the Scala on Windows or Linux, you must have Java Development Kit(JDK) 1.8 or greater installed on your system. Because Scala always runs on Java 1.8 or above. In this article, we will discuss how to run the Scala programs on online IDE’s. "
},
{
"code": null,
"e": 3792,
"s": 3711,
"text": "Example : A simple program to print Hello Geeks! using object-oriented approach."
},
{
"code": null,
"e": 3798,
"s": 3792,
"text": "Scala"
},
{
"code": "// Scala program to print Hello, Geeks!// by using object-oriented approach // creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, Geeks! println(\"Hello, Geeks!\")}}",
"e": 4014,
"s": 3798,
"text": null
},
{
"code": null,
"e": 4023,
"s": 4014,
"text": "Output: "
},
{
"code": null,
"e": 4037,
"s": 4023,
"text": "Hello, Geeks!"
},
{
"code": null,
"e": 4261,
"s": 4037,
"text": "Comments: Comments are used for explaining the code and are used in a similar manner as in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines. "
},
{
"code": null,
"e": 4291,
"s": 4261,
"text": "Single line Comments: Syntax:"
},
{
"code": null,
"e": 4314,
"s": 4291,
"text": "// Single line comment"
},
{
"code": null,
"e": 4343,
"s": 4314,
"text": "Multi line comments:Syntax: "
},
{
"code": null,
"e": 4379,
"s": 4343,
"text": "/* Multi-line comments\n syntax */"
},
{
"code": null,
"e": 4789,
"s": 4379,
"text": "object Geeks: object is the keyword which is used to create the objects. Here “Geeks” is the name of the object.def main(args: Array[String]): def is the keyword in Scala which is used to define the function and “main” is the name of Main Method. args: Array[String] are used for the command line arguments.println(“Hello, Geeks!”): println is a method in Scala which is used to display the string on console."
},
{
"code": null,
"e": 4954,
"s": 4789,
"text": "Note: There is also functional approach that can be used in Scala programs. Some Online IDE doesn’t provide support for it. We will discuss it in upcoming articles."
},
{
"code": null,
"e": 5026,
"s": 4954,
"text": "There are many features which makes it different from other languages. "
},
{
"code": null,
"e": 5216,
"s": 5026,
"text": "Object- Oriented: Every value in Scala is an object so it is a purely object-oriented programming language. The behavior and type of objects are depicted by the classes and traits in Scala."
},
{
"code": null,
"e": 5430,
"s": 5216,
"text": "Functional: It is also a functional programming language as every function is a value and every value is an object. It provides the support for the high-order functions, nested functions, anonymous functions, etc."
},
{
"code": null,
"e": 5739,
"s": 5430,
"text": "Statically Typed: The process of verifying and enforcing the constraints of types is done at compile time in Scala. Unlike other statically typed programming languages like C++, C, etc., Scala doesn’t expect the redundant type information from the user. In most cases, the user has no need to specify a type."
},
{
"code": null,
"e": 5892,
"s": 5739,
"text": "Extensible: New language constructs can be added to Scala in form of libraries. Scala is designed to interpolate with the JRE(Java Runtime Environment)."
},
{
"code": null,
"e": 6067,
"s": 5892,
"text": "Concurrent & Synchronize Processing: Scala allows the user to write the codes in an immutable manner that makes it easy to apply the parallelism(Synchronize) and concurrency."
},
{
"code": null,
"e": 6422,
"s": 6067,
"text": "Run on JVM & Can Execute Java Code: Java and Scala have a common runtime environment. So the user can easily move from Java to Scala. The Scala compiler compiles the program into .class file, containing the Bytecode that can be executed by JVM. All the classes of Java SDK can be used by Scala. With the help of Scala user can customize the Java classes."
},
{
"code": null,
"e": 6436,
"s": 6422,
"text": "Advantages: "
},
{
"code": null,
"e": 6519,
"s": 6436,
"text": "Scala’s complex features provided the better coding and efficiency in performance."
},
{
"code": null,
"e": 6580,
"s": 6519,
"text": "Tuples, macros, and functions are the advancements in Scala."
},
{
"code": null,
"e": 6686,
"s": 6580,
"text": "It incorporates the object-oriented and functional programming which in turn make it a powerful language."
},
{
"code": null,
"e": 6767,
"s": 6686,
"text": "It is highly scalable and thus provides a better support for backend operations."
},
{
"code": null,
"e": 6846,
"s": 6767,
"text": "It reduces the risk associated with the thread-safety which is higher in Java."
},
{
"code": null,
"e": 6988,
"s": 6846,
"text": "Due to the functional approach, generally, a user ends up with fewer lines of codes and bugs which result in higher productivity and quality."
},
{
"code": null,
"e": 7088,
"s": 6988,
"text": "Due to lazy computation, Scala computes the expressions only when they are required in the program."
},
{
"code": null,
"e": 7212,
"s": 7088,
"text": "There are no static methods and variables in Scala. It uses the singleton object(class with one object in the source file)."
},
{
"code": null,
"e": 7356,
"s": 7212,
"text": "It also provides the Traits concept. Traits are the collection of abstract and non-abstract methods which can be compiled into Java interfaces."
},
{
"code": null,
"e": 7373,
"s": 7356,
"text": "Disadvantages: "
},
{
"code": null,
"e": 7434,
"s": 7373,
"text": "Sometimes, two approaches make the Scala hard to understand."
},
{
"code": null,
"e": 7524,
"s": 7434,
"text": "There is a limited number of Scala developers available in comparison to Java developers."
},
{
"code": null,
"e": 7586,
"s": 7524,
"text": "It has no true-tail recursive optimization as it runs on JVM."
},
{
"code": null,
"e": 7711,
"s": 7586,
"text": "It always revolves around the object-oriented concept because every function is value and every value is an object in Scala."
},
{
"code": null,
"e": 7726,
"s": 7711,
"text": "Applications: "
},
{
"code": null,
"e": 7777,
"s": 7726,
"text": "It is mostly used in data analysis with the spark."
},
{
"code": null,
"e": 7823,
"s": 7777,
"text": "Used to develop the web-applications and API."
},
{
"code": null,
"e": 7888,
"s": 7823,
"text": "It provide the facility to develop the frameworks and libraries."
},
{
"code": null,
"e": 7970,
"s": 7888,
"text": "Preferred to use in backend operations to improve the productivity of developers."
},
{
"code": null,
"e": 8021,
"s": 7970,
"text": "Parallel batch processing can be done using Scala."
},
{
"code": null,
"e": 8040,
"s": 8023,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8049,
"s": 8040,
"text": "sweetyty"
},
{
"code": null,
"e": 8062,
"s": 8049,
"text": "Scala-Basics"
},
{
"code": null,
"e": 8068,
"s": 8062,
"text": "Scala"
},
{
"code": null,
"e": 8166,
"s": 8068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8184,
"s": 8166,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 8205,
"s": 8184,
"text": "Scala | map() method"
},
{
"code": null,
"e": 8228,
"s": 8205,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 8258,
"s": 8228,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 8284,
"s": 8258,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 8306,
"s": 8284,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 8346,
"s": 8306,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 8399,
"s": 8346,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 8444,
"s": 8399,
"text": "Scala String substring() method with example"
}
] |
PHP & AJAX | AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
For complete learning on AJAX, please refer to AJAX Tutorial.
To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command.
NOTE − We are assuming you have sufficient privilege to perform following MySQL operations.
CREATE TABLE `ajax_example` (
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(1) NOT NULL,
`wpm` int(11) NOT NULL,
PRIMARY KEY (`name`)
)
Now dump the following data into this table using the following SQL statements.
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);
Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name = 'myForm'>
Max Age: <input type = 'text' id = 'age' /> <br />
Max WPM: <input type = 'text' id = 'wpm' />
<br />
Sex: <select id = 'sex'>
<option value = "m">m</option>
<option value = "f">f</option>
</select>
<input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
</body>
</html>
NOTE − The way of passing variables in the Query is according to HTTP standard and the have formA.
URL?variable1=value1;&variable2=value2;
Now the above code will give you a screen as given below
NOTE − This is dummy screen and would not work.
So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into "ajax-example.php" file.
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications. | [
{
"code": null,
"e": 3080,
"s": 2891,
"text": "AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script."
},
{
"code": null,
"e": 3269,
"s": 3080,
"text": "AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script."
},
{
"code": null,
"e": 3482,
"s": 3269,
"text": "Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server."
},
{
"code": null,
"e": 3695,
"s": 3482,
"text": "Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server."
},
{
"code": null,
"e": 3925,
"s": 3695,
"text": "With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server."
},
{
"code": null,
"e": 4155,
"s": 3925,
"text": "With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server."
},
{
"code": null,
"e": 4217,
"s": 4155,
"text": "For complete learning on AJAX, please refer to AJAX Tutorial."
},
{
"code": null,
"e": 4487,
"s": 4217,
"text": "To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on \"ajax.html\". But before we proceed, lets do ground work. Create a table using the following command."
},
{
"code": null,
"e": 4579,
"s": 4487,
"text": "NOTE − We are assuming you have sufficient privilege to perform following MySQL operations."
},
{
"code": null,
"e": 4754,
"s": 4579,
"text": "CREATE TABLE `ajax_example` (\n `name` varchar(50) NOT NULL,\n `age` int(11) NOT NULL,\n `sex` varchar(1) NOT NULL,\n `wpm` int(11) NOT NULL,\n PRIMARY KEY (`name`)\n) \n"
},
{
"code": null,
"e": 4834,
"s": 4754,
"text": "Now dump the following data into this table using the following SQL statements."
},
{
"code": null,
"e": 5182,
"s": 4834,
"text": "INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);\nINSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);\nINSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);\nINSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);\nINSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);\nINSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);\n"
},
{
"code": null,
"e": 5273,
"s": 5182,
"text": "Now lets have our client side HTML file which is ajax.html and it will have following code"
},
{
"code": null,
"e": 7778,
"s": 5273,
"text": "<html>\n <body>\n \n <script language = \"javascript\" type = \"text/javascript\">\n <!--\n //Browser Support Code\n function ajaxFunction(){\n var ajaxRequest; // The variable that makes Ajax possible!\n \n try {\n // Opera 8.0+, Firefox, Safari\n ajaxRequest = new XMLHttpRequest();\n }catch (e) {\n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n }catch (e) {\n try{\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }catch (e){\n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n \n // Create a function that will receive data \n // sent from the server and will update\n // div section in the same page.\n\t\t\t\t\t\n ajaxRequest.onreadystatechange = function(){\n if(ajaxRequest.readyState == 4){\n var ajaxDisplay = document.getElementById('ajaxDiv');\n ajaxDisplay.innerHTML = ajaxRequest.responseText;\n }\n }\n \n // Now get the value from user and pass it to\n // server script.\n\t\t\t\t\t\n var age = document.getElementById('age').value;\n var wpm = document.getElementById('wpm').value;\n var sex = document.getElementById('sex').value;\n var queryString = \"?age=\" + age ;\n \n queryString += \"&wpm=\" + wpm + \"&sex=\" + sex;\n ajaxRequest.open(\"GET\", \"ajax-example.php\" + queryString, true);\n ajaxRequest.send(null); \n }\n //-->\n </script>\n\t\t\n <form name = 'myForm'>\n Max Age: <input type = 'text' id = 'age' /> <br />\n Max WPM: <input type = 'text' id = 'wpm' />\n <br />\n \n Sex: <select id = 'sex'>\n <option value = \"m\">m</option>\n <option value = \"f\">f</option>\n </select>\n\t\t\t\n <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>\n\t\t\t\n </form>\n \n <div id = 'ajaxDiv'>Your result will display here</div>\n </body>\n</html>"
},
{
"code": null,
"e": 7877,
"s": 7778,
"text": "NOTE − The way of passing variables in the Query is according to HTTP standard and the have formA."
},
{
"code": null,
"e": 7918,
"s": 7877,
"text": "URL?variable1=value1;&variable2=value2;\n"
},
{
"code": null,
"e": 7975,
"s": 7918,
"text": "Now the above code will give you a screen as given below"
},
{
"code": null,
"e": 8023,
"s": 7975,
"text": "NOTE − This is dummy screen and would not work."
},
{
"code": null,
"e": 8250,
"s": 8023,
"text": "So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into \"ajax-example.php\" file."
},
{
"code": null,
"e": 9858,
"s": 8250,
"text": "<?php\n \n $dbhost = \"localhost\";\n $dbuser = \"dbusername\";\n $dbpass = \"dbpassword\";\n $dbname = \"dbname\";\n \n //Connect to MySQL Server\n mysql_connect($dbhost, $dbuser, $dbpass);\n \n //Select Database\n mysql_select_db($dbname) or die(mysql_error());\n \n // Retrieve data from Query String\n $age = $_GET['age'];\n $sex = $_GET['sex'];\n $wpm = $_GET['wpm'];\n \n // Escape User Input to help prevent SQL Injection\n $age = mysql_real_escape_string($age);\n $sex = mysql_real_escape_string($sex);\n $wpm = mysql_real_escape_string($wpm);\n \n //build query\n $query = \"SELECT * FROM ajax_example WHERE sex = '$sex'\";\n \n if(is_numeric($age))\n $query .= \" AND age <= $age\";\n \n if(is_numeric($wpm))\n $query .= \" AND wpm <= $wpm\";\n \n //Execute query\n $qry_result = mysql_query($query) or die(mysql_error());\n \n //Build Result String\n $display_string = \"<table>\";\n $display_string .= \"<tr>\";\n $display_string .= \"<th>Name</th>\";\n $display_string .= \"<th>Age</th>\";\n $display_string .= \"<th>Sex</th>\";\n $display_string .= \"<th>WPM</th>\";\n $display_string .= \"</tr>\";\n \n // Insert a new row in the table for each person returned\n while($row = mysql_fetch_array($qry_result)) {\n $display_string .= \"<tr>\";\n $display_string .= \"<td>$row[name]</td>\";\n $display_string .= \"<td>$row[age]</td>\";\n $display_string .= \"<td>$row[sex]</td>\";\n $display_string .= \"<td>$row[wpm]</td>\";\n $display_string .= \"</tr>\";\n }\n echo \"Query: \" . $query . \"<br />\";\n \n $display_string .= \"</table>\";\n echo $display_string;\n?>"
},
{
"code": null,
"e": 9957,
"s": 9858,
"text": "Now try by entering a valid value in \"Max Age\" or any other box and then click Query MySQL button."
}
] |
How to append a string in PHP ? | 02 Jun, 2020
We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP:
Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to append a string str1 with another string str2.
Syntax:
$x .= $y
Example :
PHP
<?php// PHP program to append a string // function to append a string function append_string ($str1, $str2) { // Using Concatenation assignment // operator (.=) $str1 .=$str2; // Returning the result return $str1;} // Given string$str1 = "Geeks"; $str2 = "for"; $str3 = "Geeks"; // function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3); // Printing the resultecho $str; ?>
GeeksforGeeks
Using Concatenation Operator(“.”): The Concatenation operator is used to append a string str1 with another string str2 by concatenation of str1 and str2.
Syntax:
$x . $y
Example :
PHP
<?php// PHP program to append a string // Function to append a string function append_string ($str1, $str2){ // Using Concatenation assignment // operator (.) $str = $str1 . $str2; // Returning the result return $str;} // Given string$str1 = "Geeks"; $str2 = "for"; $str3 = "Geeks"; // Function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3); // Printing the resultecho $str; ?>
GeeksforGeeks
PHP-Misc
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to Insert Form Data into Database using PHP ?
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to execute PHP code using command line ?
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "We have given two strings and the task is to append a string str1 with another string str2 in PHP. There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP:"
},
{
"code": null,
"e": 388,
"s": 244,
"text": "Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to append a string str1 with another string str2."
},
{
"code": null,
"e": 396,
"s": 388,
"text": "Syntax:"
},
{
"code": null,
"e": 406,
"s": 396,
"text": "$x .= $y\n"
},
{
"code": null,
"e": 416,
"s": 406,
"text": "Example :"
},
{
"code": null,
"e": 420,
"s": 416,
"text": "PHP"
},
{
"code": "<?php// PHP program to append a string // function to append a string function append_string ($str1, $str2) { // Using Concatenation assignment // operator (.=) $str1 .=$str2; // Returning the result return $str1;} // Given string$str1 = \"Geeks\"; $str2 = \"for\"; $str3 = \"Geeks\"; // function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3); // Printing the resultecho $str; ?>",
"e": 862,
"s": 420,
"text": null
},
{
"code": null,
"e": 876,
"s": 862,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1030,
"s": 876,
"text": "Using Concatenation Operator(“.”): The Concatenation operator is used to append a string str1 with another string str2 by concatenation of str1 and str2."
},
{
"code": null,
"e": 1038,
"s": 1030,
"text": "Syntax:"
},
{
"code": null,
"e": 1047,
"s": 1038,
"text": "$x . $y\n"
},
{
"code": null,
"e": 1057,
"s": 1047,
"text": "Example :"
},
{
"code": null,
"e": 1061,
"s": 1057,
"text": "PHP"
},
{
"code": "<?php// PHP program to append a string // Function to append a string function append_string ($str1, $str2){ // Using Concatenation assignment // operator (.) $str = $str1 . $str2; // Returning the result return $str;} // Given string$str1 = \"Geeks\"; $str2 = \"for\"; $str3 = \"Geeks\"; // Function calling$str = append_string ($str1, $str2);$str = append_string ($str, $str3); // Printing the resultecho $str; ?>",
"e": 1507,
"s": 1061,
"text": null
},
{
"code": null,
"e": 1521,
"s": 1507,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1530,
"s": 1521,
"text": "PHP-Misc"
},
{
"code": null,
"e": 1541,
"s": 1530,
"text": "PHP-string"
},
{
"code": null,
"e": 1545,
"s": 1541,
"text": "PHP"
},
{
"code": null,
"e": 1558,
"s": 1545,
"text": "PHP Programs"
},
{
"code": null,
"e": 1575,
"s": 1558,
"text": "Web Technologies"
},
{
"code": null,
"e": 1602,
"s": 1575,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1606,
"s": 1602,
"text": "PHP"
},
{
"code": null,
"e": 1704,
"s": 1606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1749,
"s": 1704,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 1773,
"s": 1749,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 1823,
"s": 1773,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1875,
"s": 1823,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 1915,
"s": 1875,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1960,
"s": 1915,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2012,
"s": 1960,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2062,
"s": 2012,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2102,
"s": 2062,
"text": "How to convert array to string in PHP ?"
}
] |
C# | How to change Foreground Color of Text in Console | 28 Jan, 2019
Given the normal Console in C#, the default color of the text foreground is “Black”. The task is to change this color to some other color.
Approach: This can be done using the ForegroundColor property in the Console class of the System package in C#.
Program 1: Changing the Console Foreground Color to Blue.
// C# program to illustrate the // ForegroundColor propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Foreground color Console.WriteLine("Default Foreground Color: {0}", Console.ForegroundColor); // Set the Foreground color to blue Console.ForegroundColor = ConsoleColor.Blue; // Display current Foreground color Console.WriteLine("Changed Foreground Color: {0}", Console.ForegroundColor); }}}
Output:
Program 2: The list of available colors in which the ForegroundColor can be changed are
// C# program to get the// list of available colorsusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the list of available colors // that can be changed ConsoleColor[] consoleColors = (ConsoleColor[])ConsoleColor .GetValues(typeof(ConsoleColor)); // Display the list // of available console colors Console.WriteLine("List of available " + "Console Colors:"); foreach(var color in consoleColors) Console.WriteLine(color); }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Given the normal Console in C#, the default color of the text foreground is “Black”. The task is to change this color to some other color."
},
{
"code": null,
"e": 279,
"s": 167,
"text": "Approach: This can be done using the ForegroundColor property in the Console class of the System package in C#."
},
{
"code": null,
"e": 337,
"s": 279,
"text": "Program 1: Changing the Console Foreground Color to Blue."
},
{
"code": "// C# program to illustrate the // ForegroundColor propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Foreground color Console.WriteLine(\"Default Foreground Color: {0}\", Console.ForegroundColor); // Set the Foreground color to blue Console.ForegroundColor = ConsoleColor.Blue; // Display current Foreground color Console.WriteLine(\"Changed Foreground Color: {0}\", Console.ForegroundColor); }}}",
"e": 1020,
"s": 337,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1020,
"text": "Output:"
},
{
"code": null,
"e": 1116,
"s": 1028,
"text": "Program 2: The list of available colors in which the ForegroundColor can be changed are"
},
{
"code": "// C# program to get the// list of available colorsusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the list of available colors // that can be changed ConsoleColor[] consoleColors = (ConsoleColor[])ConsoleColor .GetValues(typeof(ConsoleColor)); // Display the list // of available console colors Console.WriteLine(\"List of available \" + \"Console Colors:\"); foreach(var color in consoleColors) Console.WriteLine(color); }}}",
"e": 1806,
"s": 1116,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1806,
"text": "Output:"
},
{
"code": null,
"e": 1835,
"s": 1814,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 1838,
"s": 1835,
"text": "C#"
}
] |
Lodash _.uniqBy() Method | 11 Feb, 2021
The _.uniqBy method is similar to _.uniq except that it accepts iteratee which is invoked for each element in an array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array.Syntax:
_.uniqBy([array], [iteratee=_.identity])
Parameters: This method accepts two parameters as mentioned above and described below:
[arrays]: This parameter holds the arrays to inspect.
[iteratee=_.identity](Function): This parameter holds the iteratee invoked per element.
Return Value: This method is used to return the new duplicate free array.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array let y = ([2.4, 1.6, 2.2, 1.3]); // Use of _.uniqBy() // method let gfg = _.uniqBy(y, Math.floor); // Printing the output console.log(gfg);
Output:
[2.4, 1.6 ]
Example 2:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array let y = ( [{'x': 2 }, { 'x': 2 }, { 'x': 1 }]); // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y, 'x'); // Printing the output console.log(gfg);
Output:
[ { 'x': 2 }, { 'x': 1 } ]
Example 3:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array let y = (['aee', 'bee', 'bee', 'cee', 'eee', 'dee', 'gee', 'dee']); // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y); // Printing the output console.log(gfg);
Output:
['aee', 'bee', 'cee', 'eee', 'dee', 'gee']
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
manishkumar142
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "The _.uniqBy method is similar to _.uniq except that it accepts iteratee which is invoked for each element in an array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array.Syntax:"
},
{
"code": null,
"e": 333,
"s": 292,
"text": "_.uniqBy([array], [iteratee=_.identity])"
},
{
"code": null,
"e": 421,
"s": 333,
"text": "Parameters: This method accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 475,
"s": 421,
"text": "[arrays]: This parameter holds the arrays to inspect."
},
{
"code": null,
"e": 563,
"s": 475,
"text": "[iteratee=_.identity](Function): This parameter holds the iteratee invoked per element."
},
{
"code": null,
"e": 733,
"s": 563,
"text": "Return Value: This method is used to return the new duplicate free array.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. "
},
{
"code": null,
"e": 744,
"s": 733,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array let y = ([2.4, 1.6, 2.2, 1.3]); // Use of _.uniqBy() // method let gfg = _.uniqBy(y, Math.floor); // Printing the output console.log(gfg);",
"e": 979,
"s": 744,
"text": null
},
{
"code": null,
"e": 989,
"s": 979,
"text": "Output: "
},
{
"code": null,
"e": 1001,
"s": 989,
"text": "[2.4, 1.6 ]"
},
{
"code": null,
"e": 1014,
"s": 1001,
"text": "Example 2: "
},
{
"code": null,
"e": 1025,
"s": 1014,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array let y = ( [{'x': 2 }, { 'x': 2 }, { 'x': 1 }]); // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y, 'x'); // Printing the output console.log(gfg);",
"e": 1306,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1306,
"text": "Output: "
},
{
"code": null,
"e": 1343,
"s": 1316,
"text": "[ { 'x': 2 }, { 'x': 1 } ]"
},
{
"code": null,
"e": 1356,
"s": 1343,
"text": "Example 3: "
},
{
"code": null,
"e": 1367,
"s": 1356,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array let y = (['aee', 'bee', 'bee', 'cee', 'eee', 'dee', 'gee', 'dee']); // Use of _.uniqBy() // method// The `_.property` iteratee shorthand.let gfg = _.uniqBy(y); // Printing the output console.log(gfg);",
"e": 1665,
"s": 1367,
"text": null
},
{
"code": null,
"e": 1675,
"s": 1665,
"text": "Output: "
},
{
"code": null,
"e": 1718,
"s": 1675,
"text": "['aee', 'bee', 'cee', 'eee', 'dee', 'gee']"
},
{
"code": null,
"e": 1826,
"s": 1718,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. "
},
{
"code": null,
"e": 1841,
"s": 1826,
"text": "manishkumar142"
},
{
"code": null,
"e": 1859,
"s": 1841,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1870,
"s": 1859,
"text": "JavaScript"
},
{
"code": null,
"e": 1887,
"s": 1870,
"text": "Web Technologies"
},
{
"code": null,
"e": 1985,
"s": 1887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2046,
"s": 1985,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2118,
"s": 2046,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2158,
"s": 2118,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2199,
"s": 2158,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2245,
"s": 2199,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2278,
"s": 2245,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2340,
"s": 2278,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2401,
"s": 2340,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2451,
"s": 2401,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
GATE | GATE CS 1999 | Question 40 | 30 Sep, 2020
A grammar that is both left and right recursive for a non-terminal is(A) Ambiguous(B) Unambiguous(C) Information is not sufficient to decide whether it is ambiguous or Unambiguous.(D) None of the aboveAnswer: (C)Explanation: Suppose we have grammar like this :
S → n
B → BbB
Here we see that grammar is left as well as right recursive but still it is unambiguous grammar because A is useless production but it is still part of grammar.So we can say that a grammar having both left as well as right recursion may or may not be ambiguous .
Lets understand with another example as we have grammar like this A→AA using this grammar we can not produce any string in finite steps as language of this grammar is empty set {}.Hence, we finally get conclusion as if grammar is having both left as well as right recursion, then grammar may or may not be ambiguous.
Option (C) is correct.Quiz of this Question
ApurvaRaj
GATE CS 1999
GATE-GATE CS 1999
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-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "A grammar that is both left and right recursive for a non-terminal is(A) Ambiguous(B) Unambiguous(C) Information is not sufficient to decide whether it is ambiguous or Unambiguous.(D) None of the aboveAnswer: (C)Explanation: Suppose we have grammar like this :"
},
{
"code": null,
"e": 304,
"s": 289,
"text": "S → n\nB → BbB "
},
{
"code": null,
"e": 567,
"s": 304,
"text": "Here we see that grammar is left as well as right recursive but still it is unambiguous grammar because A is useless production but it is still part of grammar.So we can say that a grammar having both left as well as right recursion may or may not be ambiguous ."
},
{
"code": null,
"e": 884,
"s": 567,
"text": "Lets understand with another example as we have grammar like this A→AA using this grammar we can not produce any string in finite steps as language of this grammar is empty set {}.Hence, we finally get conclusion as if grammar is having both left as well as right recursion, then grammar may or may not be ambiguous."
},
{
"code": null,
"e": 928,
"s": 884,
"text": "Option (C) is correct.Quiz of this Question"
},
{
"code": null,
"e": 938,
"s": 928,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 951,
"s": 938,
"text": "GATE CS 1999"
},
{
"code": null,
"e": 969,
"s": 951,
"text": "GATE-GATE CS 1999"
},
{
"code": null,
"e": 974,
"s": 969,
"text": "GATE"
},
{
"code": null,
"e": 1072,
"s": 974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1114,
"s": 1072,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1176,
"s": 1114,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1210,
"s": 1176,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1252,
"s": 1210,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1294,
"s": 1252,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1336,
"s": 1294,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1370,
"s": 1336,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1404,
"s": 1370,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1446,
"s": 1404,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
}
] |
Python - Filter Rows Based on Column Values with query function in Pandas? | To filter rows based on column values, we can use the query() function. In the function, set the condition through which you want to filter records. At first, import the required library −
import pandas as pd
Following is our data with Team Records −
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]
Create a DataFrame from above and add columns as well −
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])
Use query() to filter records with “Rank” equal to 5 −
dataFrame.query("Rank == 5"))
Following is the complete code −
import pandas as pd
# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]
# Creating a DataFrame and add columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])
print"DataFrame...\n",dataFrame
# using query to filter rows
print"\nFetch Team with Rank 5..\n",dataFrame.query("Rank == 5")
This will produce the following output −
DataFrame...
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
4 South Africa 5 50
5 Bangladesh 6 40
Fetch Team with Rank 5..
Country Rank Points
4 South Africa 5 50
Let us see another example. Here, we have a different condition to filter rows −
import pandas as pd
# data in the form of list of team rankings
Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]
# Creating a DataFrame and add columns
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])
print"DataFrame...\n",dataFrame
# using query to filter rows
print"\nFetch Team with points above 70 and Rank less than 3..\n"
print(dataFrame.query("Points > 70 and Rank <3"))
This will produce the following output −
DataFrame...
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
4 South Africa 5 50
5 Bangladesh 6 40
Fetch Team with points above 70 and Rank less than 3..
Country Rank Points
0 India 1 100
1 Australia 2 85 | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "To filter rows based on column values, we can use the query() function. In the function, set the condition through which you want to filter records. At first, import the required library −"
},
{
"code": null,
"e": 1271,
"s": 1251,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1313,
"s": 1271,
"text": "Following is our data with Team Records −"
},
{
"code": null,
"e": 1450,
"s": 1313,
"text": "Team = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]"
},
{
"code": null,
"e": 1506,
"s": 1450,
"text": "Create a DataFrame from above and add columns as well −"
},
{
"code": null,
"e": 1577,
"s": 1506,
"text": "dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])\n"
},
{
"code": null,
"e": 1632,
"s": 1577,
"text": "Use query() to filter records with “Rank” equal to 5 −"
},
{
"code": null,
"e": 1662,
"s": 1632,
"text": "dataFrame.query(\"Rank == 5\"))"
},
{
"code": null,
"e": 1695,
"s": 1662,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2135,
"s": 1695,
"text": "import pandas as pd\n\n# data in the form of list of team rankings\nTeam = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]\n\n# Creating a DataFrame and add columns\ndataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])\n\nprint\"DataFrame...\\n\",dataFrame\n\n# using query to filter rows\nprint\"\\nFetch Team with Rank 5..\\n\",dataFrame.query(\"Rank == 5\")"
},
{
"code": null,
"e": 2176,
"s": 2135,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2503,
"s": 2176,
"text": "DataFrame...\n Country Rank Points\n0 India 1 100\n1 Australia 2 85\n2 England 3 75\n3 New Zealand 4 65\n4 South Africa 5 50\n5 Bangladesh 6 40\n\nFetch Team with Rank 5..\n Country Rank Points\n4 South Africa 5 50"
},
{
"code": null,
"e": 2584,
"s": 2503,
"text": "Let us see another example. Here, we have a different condition to filter rows −"
},
{
"code": null,
"e": 3075,
"s": 2584,
"text": "import pandas as pd\n\n# data in the form of list of team rankings\nTeam = [['India', 1, 100],['Australia', 2, 85],['England', 3, 75],['New Zealand', 4 , 65],['South Africa', 5, 50],['Bangladesh', 6, 40]]\n\n# Creating a DataFrame and add columns\ndataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])\n\nprint\"DataFrame...\\n\",dataFrame\n\n# using query to filter rows\nprint\"\\nFetch Team with points above 70 and Rank less than 3..\\n\"\nprint(dataFrame.query(\"Points > 70 and Rank <3\"))"
},
{
"code": null,
"e": 3116,
"s": 3075,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3497,
"s": 3116,
"text": "DataFrame...\n Country Rank Points\n0 India 1 100\n1 Australia 2 85\n2 England 3 75\n3 New Zealand 4 65\n4 South Africa 5 50\n5 Bangladesh 6 40\n\nFetch Team with points above 70 and Rank less than 3..\n\n Country Rank Points\n0 India 1 100\n1 Australia 2 85"
}
] |
How to create your own VS Code server | by Dimitris Poulopoulos | Towards Data Science | Visual Studio Code is a free, lightweight, and cross-platform code editor. It may not be a full-fledged IDE like IntelliJ Idea or PyCharm, but it is a powerful, distraction-free tool with a dedicated fanbase and a thriving ecosystem.
VS Code has become the editor many developers prefer during recent years, irrespective of their background, language, and technology of choice. Thus, the next logical step is to try and run VS Code anywhere. We have seen, for example, how GitHub integrates it in Codespaces, where you can spawn an instant development environment and tweak the code living in a repository of yours.
Working from home is not the same as remote working. Remote working means working from any location, anywhere in the world, 24 hours a day.
However, the drawback in GitHub Codespaces is the pricing. Currently, the service is in public beta and free to use. But GitHub will be announcing pricing for when Codespaces reaches general availability. Unfortunately, the details we get on the corresponding page are not that encouraging. No free tier, no small instances, and overall inflated prices.
What if you could build your own server, or rent a smaller instance, or even get a bigger one with GPU or TPU acceleration? Moreover, in the story below, we saw how you could isolate your projects and collaborate with your team members easily, using Remote Development.
towardsdatascience.com
But what if you could package VS Code alongside your project dependencies, create a truly flexible environment, fulfill the dream of working from any location, anywhere in the world, whenever you want, or onboarding new team members without any hassle? Let’s see how you can create your own VS Code server!
Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!
In this story, we will be using a VM on GCP, but you should easily use any machine or VM provider.
First, start a VM on GCP with at least 2 vCPU cores, 1GB of memory, and 32GB of standard storage. Note that this low-end option is not available on Codespaces. The difference between a VM with this configuration and Codespaces' budget offering is ~4 USD a month (for eight hours a day, five days a week). In Codespaces, you’d pay ~13.5 USD while in GCP ~9.5 USD.
It’s not that big of a difference but using your own VM gives you more flexibility; you can fit it exactly to your needs, scale it up when you need more horsepower, and back down when testing a new idea.
Navigate to Compute Engine -> VM Instances on the sidebarNow click Create Instance to create a new instanceChoose the region closest to you based on gcping.com (any zone is fine)Start an E2 series instance from the General-purpose familyChange the type to custom and set at least 2 vCPU cores and 1GB of RAMChange the Boot Disk to an Ubuntu 20.04 image and set it to 32GBNavigate to Security -> SSH Keys and add your public key there*Click create!
Navigate to Compute Engine -> VM Instances on the sidebar
Now click Create Instance to create a new instance
Choose the region closest to you based on gcping.com (any zone is fine)
Start an E2 series instance from the General-purpose family
Change the type to custom and set at least 2 vCPU cores and 1GB of RAM
Change the Boot Disk to an Ubuntu 20.04 image and set it to 32GB
Navigate to Security -> SSH Keys and add your public key there*
Click create!
* If you don’t know how to create your SSH key see the GCP guide here
Your instance will be ready in a few seconds. Click on the SSH button on the right and connect to the machine and install the VS Code server.
To install a VS Code server, we will use code-server by coder. To install it, run the following command:
curl -fsSL https://code-server.dev/install.sh | sh
Wait a few seconds and then start the server by executing code-server. A VS Code instance will start listening onlocalhost to avoid exposing itself to the world. This is crucial, as someone can completely take over your machine using the VC Code terminal.
So, how can you connect to the server? The simplest method is to use SSH forwarding. First, stop the server and run the following commands to disable the password authentication method and restart the server:
sed -i.bak 's/auth: password/auth: none/' ~/.config/code-server/config.yamlsudo systemctl restart code-server@$USER
Assuming that you have already set a project-wide SSH key, launch your local terminal and run the following command:
ssh -i [path/to/your/private/key] -N -L 8080:127.0.0.1:8080 [user]@<instance-ip>
Finally, launch a terminal and navigate to http://127.0.0.1:8080/. You now have your own VS Code server!
For detailed documentation, visit the code-server docs page on GitHub.
Visual Studio Code is a free, lightweight, and cross-platform code editor, a powerful, distraction-free tool with a dedicated fanbase and a thriving ecosystem.
Running it as a web application enables you to work from any location, anywhere in the world, and using any medium (even your iPad). Moreover, you can package it alongside your projects into siloed containers and create a seamless onboarding process. So, go on and build your own VS Code servers.
My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA.
If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Also, visit the resources page on my website, a place for great books and top-rated courses, to start building your own Data Science curriculum! | [
{
"code": null,
"e": 406,
"s": 172,
"text": "Visual Studio Code is a free, lightweight, and cross-platform code editor. It may not be a full-fledged IDE like IntelliJ Idea or PyCharm, but it is a powerful, distraction-free tool with a dedicated fanbase and a thriving ecosystem."
},
{
"code": null,
"e": 788,
"s": 406,
"text": "VS Code has become the editor many developers prefer during recent years, irrespective of their background, language, and technology of choice. Thus, the next logical step is to try and run VS Code anywhere. We have seen, for example, how GitHub integrates it in Codespaces, where you can spawn an instant development environment and tweak the code living in a repository of yours."
},
{
"code": null,
"e": 928,
"s": 788,
"text": "Working from home is not the same as remote working. Remote working means working from any location, anywhere in the world, 24 hours a day."
},
{
"code": null,
"e": 1282,
"s": 928,
"text": "However, the drawback in GitHub Codespaces is the pricing. Currently, the service is in public beta and free to use. But GitHub will be announcing pricing for when Codespaces reaches general availability. Unfortunately, the details we get on the corresponding page are not that encouraging. No free tier, no small instances, and overall inflated prices."
},
{
"code": null,
"e": 1552,
"s": 1282,
"text": "What if you could build your own server, or rent a smaller instance, or even get a bigger one with GPU or TPU acceleration? Moreover, in the story below, we saw how you could isolate your projects and collaborate with your team members easily, using Remote Development."
},
{
"code": null,
"e": 1575,
"s": 1552,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1882,
"s": 1575,
"text": "But what if you could package VS Code alongside your project dependencies, create a truly flexible environment, fulfill the dream of working from any location, anywhere in the world, whenever you want, or onboarding new team members without any hassle? Let’s see how you can create your own VS Code server!"
},
{
"code": null,
"e": 2082,
"s": 1882,
"text": "Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!"
},
{
"code": null,
"e": 2181,
"s": 2082,
"text": "In this story, we will be using a VM on GCP, but you should easily use any machine or VM provider."
},
{
"code": null,
"e": 2544,
"s": 2181,
"text": "First, start a VM on GCP with at least 2 vCPU cores, 1GB of memory, and 32GB of standard storage. Note that this low-end option is not available on Codespaces. The difference between a VM with this configuration and Codespaces' budget offering is ~4 USD a month (for eight hours a day, five days a week). In Codespaces, you’d pay ~13.5 USD while in GCP ~9.5 USD."
},
{
"code": null,
"e": 2748,
"s": 2544,
"text": "It’s not that big of a difference but using your own VM gives you more flexibility; you can fit it exactly to your needs, scale it up when you need more horsepower, and back down when testing a new idea."
},
{
"code": null,
"e": 3196,
"s": 2748,
"text": "Navigate to Compute Engine -> VM Instances on the sidebarNow click Create Instance to create a new instanceChoose the region closest to you based on gcping.com (any zone is fine)Start an E2 series instance from the General-purpose familyChange the type to custom and set at least 2 vCPU cores and 1GB of RAMChange the Boot Disk to an Ubuntu 20.04 image and set it to 32GBNavigate to Security -> SSH Keys and add your public key there*Click create!"
},
{
"code": null,
"e": 3254,
"s": 3196,
"text": "Navigate to Compute Engine -> VM Instances on the sidebar"
},
{
"code": null,
"e": 3305,
"s": 3254,
"text": "Now click Create Instance to create a new instance"
},
{
"code": null,
"e": 3377,
"s": 3305,
"text": "Choose the region closest to you based on gcping.com (any zone is fine)"
},
{
"code": null,
"e": 3437,
"s": 3377,
"text": "Start an E2 series instance from the General-purpose family"
},
{
"code": null,
"e": 3508,
"s": 3437,
"text": "Change the type to custom and set at least 2 vCPU cores and 1GB of RAM"
},
{
"code": null,
"e": 3573,
"s": 3508,
"text": "Change the Boot Disk to an Ubuntu 20.04 image and set it to 32GB"
},
{
"code": null,
"e": 3637,
"s": 3573,
"text": "Navigate to Security -> SSH Keys and add your public key there*"
},
{
"code": null,
"e": 3651,
"s": 3637,
"text": "Click create!"
},
{
"code": null,
"e": 3721,
"s": 3651,
"text": "* If you don’t know how to create your SSH key see the GCP guide here"
},
{
"code": null,
"e": 3863,
"s": 3721,
"text": "Your instance will be ready in a few seconds. Click on the SSH button on the right and connect to the machine and install the VS Code server."
},
{
"code": null,
"e": 3968,
"s": 3863,
"text": "To install a VS Code server, we will use code-server by coder. To install it, run the following command:"
},
{
"code": null,
"e": 4019,
"s": 3968,
"text": "curl -fsSL https://code-server.dev/install.sh | sh"
},
{
"code": null,
"e": 4275,
"s": 4019,
"text": "Wait a few seconds and then start the server by executing code-server. A VS Code instance will start listening onlocalhost to avoid exposing itself to the world. This is crucial, as someone can completely take over your machine using the VC Code terminal."
},
{
"code": null,
"e": 4484,
"s": 4275,
"text": "So, how can you connect to the server? The simplest method is to use SSH forwarding. First, stop the server and run the following commands to disable the password authentication method and restart the server:"
},
{
"code": null,
"e": 4600,
"s": 4484,
"text": "sed -i.bak 's/auth: password/auth: none/' ~/.config/code-server/config.yamlsudo systemctl restart code-server@$USER"
},
{
"code": null,
"e": 4717,
"s": 4600,
"text": "Assuming that you have already set a project-wide SSH key, launch your local terminal and run the following command:"
},
{
"code": null,
"e": 4798,
"s": 4717,
"text": "ssh -i [path/to/your/private/key] -N -L 8080:127.0.0.1:8080 [user]@<instance-ip>"
},
{
"code": null,
"e": 4903,
"s": 4798,
"text": "Finally, launch a terminal and navigate to http://127.0.0.1:8080/. You now have your own VS Code server!"
},
{
"code": null,
"e": 4974,
"s": 4903,
"text": "For detailed documentation, visit the code-server docs page on GitHub."
},
{
"code": null,
"e": 5134,
"s": 4974,
"text": "Visual Studio Code is a free, lightweight, and cross-platform code editor, a powerful, distraction-free tool with a dedicated fanbase and a thriving ecosystem."
},
{
"code": null,
"e": 5431,
"s": 5134,
"text": "Running it as a web application enables you to work from any location, anywhere in the world, and using any medium (even your iPad). Moreover, you can package it alongside your projects into siloed containers and create a seamless onboarding process. So, go on and build your own VS Code servers."
},
{
"code": null,
"e": 5688,
"s": 5431,
"text": "My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA."
}
] |
JDBC - CallableStatement Object Example | Following is the example, which makes use of the CallableStatement along with the following getEmpName() MySQL stored procedure −
Make sure you have created this stored procedure in your EMP Database. You can use MySQL Query Browser to get it done.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
This sample code has been written based on the environment and database setup done in the previous chapters.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
CallableStatement stmt = conn.prepareCall(QUERY);
) {
// Bind values into the parameters.
stmt.setInt(1, 102); // This would set ID
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID: 102 is " + empName);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Executing stored procedure...
Emp Name with ID: 102 is Zaid
C:\>
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2292,
"s": 2162,
"text": "Following is the example, which makes use of the CallableStatement along with the following getEmpName() MySQL stored procedure −"
},
{
"code": null,
"e": 2411,
"s": 2292,
"text": "Make sure you have created this stored procedure in your EMP Database. You can use MySQL Query Browser to get it done."
},
{
"code": null,
"e": 2653,
"s": 2411,
"text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$\nCREATE PROCEDURE `EMP`.`getEmpName` \n (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND $$\n\nDELIMITER ;"
},
{
"code": null,
"e": 2762,
"s": 2653,
"text": "This sample code has been written based on the environment and database setup done in the previous chapters."
},
{
"code": null,
"e": 2849,
"s": 2762,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 4047,
"s": 2849,
"text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"{call getEmpName (?, ?)}\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n CallableStatement stmt = conn.prepareCall(QUERY);\n ) {\t\t \n // Bind values into the parameters.\n stmt.setInt(1, 102); // This would set ID\n // Because second parameter is OUT so register it\n stmt.registerOutParameter(2, java.sql.Types.VARCHAR);\n //Use execute method to run stored procedure.\n System.out.println(\"Executing stored procedure...\" );\n stmt.execute();\n //Retrieve employee name with getXXX method\n String empName = stmt.getString(2);\n System.out.println(\"Emp Name with ID: 102 is \" + empName);\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 4097,
"s": 4047,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 4129,
"s": 4097,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 4190,
"s": 4129,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 4277,
"s": 4190,
"text": "C:\\>java JDBCExample\nExecuting stored procedure...\nEmp Name with ID: 102 is Zaid\nC:\\>\n"
},
{
"code": null,
"e": 4310,
"s": 4277,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4326,
"s": 4310,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4359,
"s": 4326,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4375,
"s": 4359,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4410,
"s": 4375,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4424,
"s": 4410,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4458,
"s": 4424,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4472,
"s": 4458,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4509,
"s": 4472,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4524,
"s": 4509,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4557,
"s": 4524,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4576,
"s": 4557,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4583,
"s": 4576,
"text": " Print"
},
{
"code": null,
"e": 4594,
"s": 4583,
"text": " Add Notes"
}
] |
Find the number of squares inside the given square grid - GeeksforGeeks | 08 Mar, 2022
Given a grid of side N * N, the task is to find the total number of squares that exist inside it. All squares selected can be of any length.Examples:
Input: N = 1 Output: 1
Input: N = 2 Output: 5
Input: N = 4 Output: 30
Approach 1: Taking a few examples, it can be observed that for a grid on size N * N, the number of squares inside it will be 12 + 22 + 32 + ... + N2Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of squares inside an n*n gridint cntSquares(int n){ int squares = 0; for (int i = 1; i <= n; i++) { squares += pow(i, 2); } return squares;} // Driver codeint main(){ int n = 4; cout << cntSquares(4); return 0;}
// Java implementation of the approachclass GFG { // Function to return the number // of squares inside an n*n grid static int cntSquares(int n) { int squares = 0; for (int i = 1; i <= n; i++) { squares += Math.pow(i, 2); } return squares; } // Driver code public static void main(String args[]) { int n = 4; System.out.print(cntSquares(4)); }}
# Python3 implementation of the approach # Function to return the number# of squares inside an n*n griddef cntSquares(n) : squares = 0; for i in range(1, n + 1) : squares += i ** 2; return squares; # Driver codeif __name__ == "__main__" : n = 4; print(cntSquares(4)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the number // of squares inside an n*n grid static int cntSquares(int n) { int squares = 0; for (int i = 1; i <= n; i++) { squares += (int)Math.Pow(i, 2); } return squares; } // Driver code public static void Main(String []args) { int n = 4; Console.Write(cntSquares(n)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Function to return the number // of squares inside an n*n grid function cntSquares(n) { let squares = 0; for (let i = 1; i <= n; i++) { squares += Math.pow(i, 2); } return squares; } let n = 4; document.write(cntSquares(n)); </script>
30
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2: By the use of direct formula. However, the sum has the closed form (direct formula) . Hence, we can employ this to calculate the sum in time.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream> using namespace std; int cnt_squares (int n){ /* Function to return the number of squares inside an n*n grid */ return n * (n + 1) * (2 * n + 1) / 6;} // Driver codeint main(){ cout << cnt_squares (4) << endl; return 0;}
// Java implementation of the approachclass GFG { static int cntSquares (int n) { /* Function to return the number of squares inside an n*n grid */ return n * (n + 1) * (2 * n + 1) / 6; } // Driver code public static void main(String args[]) { System.out.println (cntSquares(4)); }}
# Python3 implementation of the approach """Function to return the numberof squares inside an n*n grid""" def cntSquares(n) : return int (n * (n + 1) * (2 * n + 1) / 6) # Driver codeif __name__ == "__main__" : print (cntSquares (4));
// C# implementation of the approachusing System; class GFG{ /* Function to return the number of squares inside an n*n grid */ static int cntSquares (int n) { return n * (n + 1) * (2 * n + 1) / 6; } // Driver code public static void Main (String[] args) { Console.Write (cntSquares (4)); }}
<script> // Javascript implementation of the approach /* Function to return the number of squares inside an n*n grid */ function cntSquares (n) { return n * (n + 1) * (2 * n + 1) / 6; } document.write(cntSquares(4)); // This code is contributed by divyeshrabadiya07.</script>
30
Time Complexity: O(1)
Auxiliary Space: O(1)
29AjayKumar
ankthon
Snowden17_38
suresh07
divyeshrabadiya07
subhammahato348
square-rectangle
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Add two numbers without using arithmetic operators
Count ways to reach the n'th stair
Program to convert a given number to words
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Find Union and Intersection of two unsorted arrays | [
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 24453,
"s": 24301,
"text": "Given a grid of side N * N, the task is to find the total number of squares that exist inside it. All squares selected can be of any length.Examples: "
},
{
"code": null,
"e": 24478,
"s": 24453,
"text": "Input: N = 1 Output: 1 "
},
{
"code": null,
"e": 24503,
"s": 24478,
"text": "Input: N = 2 Output: 5 "
},
{
"code": null,
"e": 24529,
"s": 24503,
"text": "Input: N = 4 Output: 30 "
},
{
"code": null,
"e": 24731,
"s": 24531,
"text": "Approach 1: Taking a few examples, it can be observed that for a grid on size N * N, the number of squares inside it will be 12 + 22 + 32 + ... + N2Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24735,
"s": 24731,
"text": "C++"
},
{
"code": null,
"e": 24740,
"s": 24735,
"text": "Java"
},
{
"code": null,
"e": 24748,
"s": 24740,
"text": "Python3"
},
{
"code": null,
"e": 24751,
"s": 24748,
"text": "C#"
},
{
"code": null,
"e": 24762,
"s": 24751,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of squares inside an n*n gridint cntSquares(int n){ int squares = 0; for (int i = 1; i <= n; i++) { squares += pow(i, 2); } return squares;} // Driver codeint main(){ int n = 4; cout << cntSquares(4); return 0;}",
"e": 25121,
"s": 24762,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the number // of squares inside an n*n grid static int cntSquares(int n) { int squares = 0; for (int i = 1; i <= n; i++) { squares += Math.pow(i, 2); } return squares; } // Driver code public static void main(String args[]) { int n = 4; System.out.print(cntSquares(4)); }}",
"e": 25549,
"s": 25121,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the number# of squares inside an n*n griddef cntSquares(n) : squares = 0; for i in range(1, n + 1) : squares += i ** 2; return squares; # Driver codeif __name__ == \"__main__\" : n = 4; print(cntSquares(4)); # This code is contributed by AnkitRai01",
"e": 25884,
"s": 25549,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number // of squares inside an n*n grid static int cntSquares(int n) { int squares = 0; for (int i = 1; i <= n; i++) { squares += (int)Math.Pow(i, 2); } return squares; } // Driver code public static void Main(String []args) { int n = 4; Console.Write(cntSquares(n)); }} // This code is contributed by 29AjayKumar",
"e": 26375,
"s": 25884,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the number // of squares inside an n*n grid function cntSquares(n) { let squares = 0; for (let i = 1; i <= n; i++) { squares += Math.pow(i, 2); } return squares; } let n = 4; document.write(cntSquares(n)); </script>",
"e": 26765,
"s": 26375,
"text": null
},
{
"code": null,
"e": 26768,
"s": 26765,
"text": "30"
},
{
"code": null,
"e": 26792,
"s": 26770,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 26814,
"s": 26792,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27019,
"s": 26814,
"text": "Approach 2: By the use of direct formula. However, the sum has the closed form (direct formula) . Hence, we can employ this to calculate the sum in time.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27023,
"s": 27019,
"text": "C++"
},
{
"code": null,
"e": 27028,
"s": 27023,
"text": "Java"
},
{
"code": null,
"e": 27036,
"s": 27028,
"text": "Python3"
},
{
"code": null,
"e": 27039,
"s": 27036,
"text": "C#"
},
{
"code": null,
"e": 27050,
"s": 27039,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream> using namespace std; int cnt_squares (int n){ /* Function to return the number of squares inside an n*n grid */ return n * (n + 1) * (2 * n + 1) / 6;} // Driver codeint main(){ cout << cnt_squares (4) << endl; return 0;}",
"e": 27346,
"s": 27050,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { static int cntSquares (int n) { /* Function to return the number of squares inside an n*n grid */ return n * (n + 1) * (2 * n + 1) / 6; } // Driver code public static void main(String args[]) { System.out.println (cntSquares(4)); }}",
"e": 27678,
"s": 27346,
"text": null
},
{
"code": "# Python3 implementation of the approach \"\"\"Function to return the numberof squares inside an n*n grid\"\"\" def cntSquares(n) : return int (n * (n + 1) * (2 * n + 1) / 6) # Driver codeif __name__ == \"__main__\" : print (cntSquares (4));",
"e": 27918,
"s": 27678,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ /* Function to return the number of squares inside an n*n grid */ static int cntSquares (int n) { return n * (n + 1) * (2 * n + 1) / 6; } // Driver code public static void Main (String[] args) { Console.Write (cntSquares (4)); }}",
"e": 28253,
"s": 27918,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach /* Function to return the number of squares inside an n*n grid */ function cntSquares (n) { return n * (n + 1) * (2 * n + 1) / 6; } document.write(cntSquares(4)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 28568,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28571,
"s": 28568,
"text": "30"
},
{
"code": null,
"e": 28595,
"s": 28573,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28617,
"s": 28595,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28629,
"s": 28617,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28637,
"s": 28629,
"text": "ankthon"
},
{
"code": null,
"e": 28650,
"s": 28637,
"text": "Snowden17_38"
},
{
"code": null,
"e": 28659,
"s": 28650,
"text": "suresh07"
},
{
"code": null,
"e": 28677,
"s": 28659,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 28693,
"s": 28677,
"text": "subhammahato348"
},
{
"code": null,
"e": 28710,
"s": 28693,
"text": "square-rectangle"
},
{
"code": null,
"e": 28723,
"s": 28710,
"text": "Mathematical"
},
{
"code": null,
"e": 28736,
"s": 28723,
"text": "Mathematical"
},
{
"code": null,
"e": 28834,
"s": 28736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28843,
"s": 28834,
"text": "Comments"
},
{
"code": null,
"e": 28856,
"s": 28843,
"text": "Old Comments"
},
{
"code": null,
"e": 28900,
"s": 28856,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28925,
"s": 28900,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28958,
"s": 28925,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29009,
"s": 28958,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 29044,
"s": 29009,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 29087,
"s": 29044,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 29118,
"s": 29087,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 29189,
"s": 29118,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Pascal - Strings | The string in Pascal is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. Extended Pascal provides numerous types of string objects depending upon the system and implementation. We will discuss more common types of strings used in programs.
You can define a string in many ways −
Character arrays − This is a character string which is a sequence of zero or more byte-sized characters enclosed in single quotes.
Character arrays − This is a character string which is a sequence of zero or more byte-sized characters enclosed in single quotes.
String variables − The variable of String type, as defined in Turbo Pascal.
String variables − The variable of String type, as defined in Turbo Pascal.
Short strings − The variable of String type with size specification.
Short strings − The variable of String type with size specification.
Null terminated strings − The variable of pchar type.
Null terminated strings − The variable of pchar type.
AnsiStrings − Ansistrings are strings that have no length limit.
AnsiStrings − Ansistrings are strings that have no length limit.
Pascal provides only one string operator, string concatenation operator (+).
The following program prints first four kinds of strings. We will use AnsiStrings in the next example.
program exString;
var
greetings: string;
name: packed array [1..10] of char;
organisation: string[10];
message: pchar;
begin
greetings := 'Hello ';
message := 'Good Day!';
writeln('Please Enter your Name');
readln(name);
writeln('Please Enter the name of your Organisation');
readln(organisation);
writeln(greetings, name, ' from ', organisation);
writeln(message);
end.
When the above code is compiled and executed, it produces the following result −
Please Enter your Name
John Smith
Please Enter the name of your Organisation
Infotech
Hello John Smith from Infotech
Following example makes use of few more functions, let's see −
program exString;
uses sysutils;
var
str1, str2, str3 : ansistring;
str4: string;
len: integer;
begin
str1 := 'Hello ';
str2 := 'There!';
(* copy str1 into str3 *)
str3 := str1;
writeln('appendstr( str3, str1) : ', str3 );
(* concatenates str1 and str2 *)
appendstr( str1, str2);
writeln( 'appendstr( str1, str2) ' , str1 );
str4 := str1 + str2;
writeln('Now str4 is: ', str4);
(* total lenghth of str4 after concatenation *)
len := byte(str4[0]);
writeln('Length of the final string str4: ', len);
end.
When the above code is compiled and executed, it produces the following result −
appendstr( str3, str1) : Hello
appendstr( str1, str2) : Hello There!
Now str4 is: Hello There! There!
Length of the final string str4: 18
Pascal supports a wide range of functions and procedures that manipulate strings. These subprograms vary implement-wise. Here, we are listing various string manipulating subprograms provided by Free Pascal −
function AnsiCompareStr(const S1: ; const S2:):Integer;
Compares two strings
function AnsiCompareText(const S1: ; const S2:):Integer;
Compares two strings, case insensitive
function AnsiExtractQuotedStr(var Src: PChar; Quote: Char):;
Removes quotes from string
function AnsiLastChar(const S:):PChar;
Gets last character of string
function AnsiLowerCase(const s:):
Converts string to all-lowercase
function AnsiQuotedStr(const S: ; Quote: Char):;
Quotes a string
function AnsiStrComp(S1: PChar;S2: PChar):Integer;
Compares strings case-sensitive
function AnsiStrIComp(S1: PChar; S2: PChar):Integer;
Compares strings case-insensitive
function AnsiStrLComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer;
Compares L characters of strings case sensitive
function AnsiStrLIComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer;
Compares L characters of strings case insensitive
function AnsiStrLastChar(Str: PChar):PChar;
Gets last character of string
function AnsiStrLower(Str: PChar):PChar;
Converts string to all-lowercase
function AnsiStrUpper(Str: PChar):PChar;
Converts string to all-uppercase
function AnsiUpperCase(const s:):;
Converts string to all-uppercase
procedure AppendStr(var Dest: ; const S:);
Appends 2 strings
procedure AssignStr(var P: PString; const S:);
Assigns value of strings on heap
function CompareStr(const S1: ; const S2:):Integer; overload;
Compares two strings case sensitive
function CompareText(const S1: ; const S2:):Integer;
Compares two strings case insensitive
Removes string from heap
procedure DisposeStr(S: PShortString); overload;
Removes string from heap
function IsValidIdent( const Ident:):Boolean;
Is string a valid pascal identifier
function LastDelimiter(const Delimiters: ; const S:):Integer;
Last occurrence of character in a string
function LeftStr(const S: ; Count: Integer):;
Gets first N characters of a string
function LoadStr(Ident: Integer):;
Loads string from resources
function LowerCase(const s: ):; overload;
Converts string to all-lowercase
function LowerCase(const V: variant ):; overload;
Converts string to all-lowercase
function NewStr(const S:):PString; overload;
Allocates new string on heap
function RightStr(const S: ; Count: Integer):;
Gets last N characters of a string
function StrAlloc(Size: Cardinal):PChar;
Allocates memory for string
function StrBufSize(Str: PChar):SizeUInt;
Reserves memory for a string
procedure StrDispose(Str: PChar);
Removes string from heap
function StrPas(Str: PChar):;
Converts PChar to pascal string
function StrPCopy(Dest: PChar; Source:):PChar;
Copies pascal string
function StrPLCopy(Dest: PChar; Source: ; MaxLen: SizeUInt):PChar;
Copies N bytes of pascal string
function UpperCase(const s:):;
Converts string to all-uppercase
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2438,
"s": 2083,
"text": "The string in Pascal is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. Extended Pascal provides numerous types of string objects depending upon the system and implementation. We will discuss more common types of strings used in programs."
},
{
"code": null,
"e": 2477,
"s": 2438,
"text": "You can define a string in many ways −"
},
{
"code": null,
"e": 2610,
"s": 2477,
"text": "Character arrays − This is a character string which is a sequence of zero or more byte-sized characters enclosed in single quotes."
},
{
"code": null,
"e": 2743,
"s": 2610,
"text": "Character arrays − This is a character string which is a sequence of zero or more byte-sized characters enclosed in single quotes."
},
{
"code": null,
"e": 2819,
"s": 2743,
"text": "String variables − The variable of String type, as defined in Turbo Pascal."
},
{
"code": null,
"e": 2895,
"s": 2819,
"text": "String variables − The variable of String type, as defined in Turbo Pascal."
},
{
"code": null,
"e": 2964,
"s": 2895,
"text": "Short strings − The variable of String type with size specification."
},
{
"code": null,
"e": 3033,
"s": 2964,
"text": "Short strings − The variable of String type with size specification."
},
{
"code": null,
"e": 3087,
"s": 3033,
"text": "Null terminated strings − The variable of pchar type."
},
{
"code": null,
"e": 3141,
"s": 3087,
"text": "Null terminated strings − The variable of pchar type."
},
{
"code": null,
"e": 3206,
"s": 3141,
"text": "AnsiStrings − Ansistrings are strings that have no length limit."
},
{
"code": null,
"e": 3271,
"s": 3206,
"text": "AnsiStrings − Ansistrings are strings that have no length limit."
},
{
"code": null,
"e": 3348,
"s": 3271,
"text": "Pascal provides only one string operator, string concatenation operator (+)."
},
{
"code": null,
"e": 3451,
"s": 3348,
"text": "The following program prints first four kinds of strings. We will use AnsiStrings in the next example."
},
{
"code": null,
"e": 3872,
"s": 3451,
"text": "program exString;\nvar\n greetings: string;\n name: packed array [1..10] of char;\n organisation: string[10];\n message: pchar;\n\nbegin\n greetings := 'Hello ';\n message := 'Good Day!';\n \n writeln('Please Enter your Name');\n readln(name);\n \n writeln('Please Enter the name of your Organisation');\n readln(organisation);\n \n writeln(greetings, name, ' from ', organisation);\n writeln(message); \nend."
},
{
"code": null,
"e": 3953,
"s": 3872,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4071,
"s": 3953,
"text": "Please Enter your Name\nJohn Smith\nPlease Enter the name of your Organisation\nInfotech\nHello John Smith from Infotech\n"
},
{
"code": null,
"e": 4134,
"s": 4071,
"text": "Following example makes use of few more functions, let's see −"
},
{
"code": null,
"e": 4702,
"s": 4134,
"text": "program exString;\nuses sysutils;\nvar\n str1, str2, str3 : ansistring;\n str4: string;\n len: integer;\n\nbegin\n str1 := 'Hello ';\n str2 := 'There!';\n \n (* copy str1 into str3 *)\n str3 := str1;\n writeln('appendstr( str3, str1) : ', str3 );\n \n (* concatenates str1 and str2 *)\n appendstr( str1, str2);\n writeln( 'appendstr( str1, str2) ' , str1 );\n str4 := str1 + str2;\n writeln('Now str4 is: ', str4);\n \n (* total lenghth of str4 after concatenation *)\n len := byte(str4[0]);\n writeln('Length of the final string str4: ', len); \nend."
},
{
"code": null,
"e": 4783,
"s": 4702,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4922,
"s": 4783,
"text": "appendstr( str3, str1) : Hello\nappendstr( str1, str2) : Hello There!\nNow str4 is: Hello There! There!\nLength of the final string str4: 18\n"
},
{
"code": null,
"e": 5130,
"s": 4922,
"text": "Pascal supports a wide range of functions and procedures that manipulate strings. These subprograms vary implement-wise. Here, we are listing various string manipulating subprograms provided by Free Pascal −"
},
{
"code": null,
"e": 5187,
"s": 5130,
"text": "function AnsiCompareStr(const S1: ; const S2:):Integer; "
},
{
"code": null,
"e": 5208,
"s": 5187,
"text": "Compares two strings"
},
{
"code": null,
"e": 5265,
"s": 5208,
"text": "function AnsiCompareText(const S1: ; const S2:):Integer;"
},
{
"code": null,
"e": 5304,
"s": 5265,
"text": "Compares two strings, case insensitive"
},
{
"code": null,
"e": 5365,
"s": 5304,
"text": "function AnsiExtractQuotedStr(var Src: PChar; Quote: Char):;"
},
{
"code": null,
"e": 5392,
"s": 5365,
"text": "Removes quotes from string"
},
{
"code": null,
"e": 5431,
"s": 5392,
"text": "function AnsiLastChar(const S:):PChar;"
},
{
"code": null,
"e": 5461,
"s": 5431,
"text": "Gets last character of string"
},
{
"code": null,
"e": 5495,
"s": 5461,
"text": "function AnsiLowerCase(const s:):"
},
{
"code": null,
"e": 5528,
"s": 5495,
"text": "Converts string to all-lowercase"
},
{
"code": null,
"e": 5577,
"s": 5528,
"text": "function AnsiQuotedStr(const S: ; Quote: Char):;"
},
{
"code": null,
"e": 5593,
"s": 5577,
"text": "Quotes a string"
},
{
"code": null,
"e": 5644,
"s": 5593,
"text": "function AnsiStrComp(S1: PChar;S2: PChar):Integer;"
},
{
"code": null,
"e": 5676,
"s": 5644,
"text": "Compares strings case-sensitive"
},
{
"code": null,
"e": 5729,
"s": 5676,
"text": "function AnsiStrIComp(S1: PChar; S2: PChar):Integer;"
},
{
"code": null,
"e": 5763,
"s": 5729,
"text": "Compares strings case-insensitive"
},
{
"code": null,
"e": 5834,
"s": 5763,
"text": "function AnsiStrLComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer;"
},
{
"code": null,
"e": 5882,
"s": 5834,
"text": "Compares L characters of strings case sensitive"
},
{
"code": null,
"e": 5954,
"s": 5882,
"text": "function AnsiStrLIComp(S1: PChar; S2: PChar; MaxLen: Cardinal):Integer;"
},
{
"code": null,
"e": 6004,
"s": 5954,
"text": "Compares L characters of strings case insensitive"
},
{
"code": null,
"e": 6048,
"s": 6004,
"text": "function AnsiStrLastChar(Str: PChar):PChar;"
},
{
"code": null,
"e": 6078,
"s": 6048,
"text": "Gets last character of string"
},
{
"code": null,
"e": 6119,
"s": 6078,
"text": "function AnsiStrLower(Str: PChar):PChar;"
},
{
"code": null,
"e": 6152,
"s": 6119,
"text": "Converts string to all-lowercase"
},
{
"code": null,
"e": 6193,
"s": 6152,
"text": "function AnsiStrUpper(Str: PChar):PChar;"
},
{
"code": null,
"e": 6226,
"s": 6193,
"text": "Converts string to all-uppercase"
},
{
"code": null,
"e": 6261,
"s": 6226,
"text": "function AnsiUpperCase(const s:):;"
},
{
"code": null,
"e": 6294,
"s": 6261,
"text": "Converts string to all-uppercase"
},
{
"code": null,
"e": 6337,
"s": 6294,
"text": "procedure AppendStr(var Dest: ; const S:);"
},
{
"code": null,
"e": 6355,
"s": 6337,
"text": "Appends 2 strings"
},
{
"code": null,
"e": 6402,
"s": 6355,
"text": "procedure AssignStr(var P: PString; const S:);"
},
{
"code": null,
"e": 6435,
"s": 6402,
"text": "Assigns value of strings on heap"
},
{
"code": null,
"e": 6497,
"s": 6435,
"text": "function CompareStr(const S1: ; const S2:):Integer; overload;"
},
{
"code": null,
"e": 6533,
"s": 6497,
"text": "Compares two strings case sensitive"
},
{
"code": null,
"e": 6586,
"s": 6533,
"text": "function CompareText(const S1: ; const S2:):Integer;"
},
{
"code": null,
"e": 6624,
"s": 6586,
"text": "Compares two strings case insensitive"
},
{
"code": null,
"e": 6649,
"s": 6624,
"text": "Removes string from heap"
},
{
"code": null,
"e": 6698,
"s": 6649,
"text": "procedure DisposeStr(S: PShortString); overload;"
},
{
"code": null,
"e": 6723,
"s": 6698,
"text": "Removes string from heap"
},
{
"code": null,
"e": 6769,
"s": 6723,
"text": "function IsValidIdent( const Ident:):Boolean;"
},
{
"code": null,
"e": 6805,
"s": 6769,
"text": "Is string a valid pascal identifier"
},
{
"code": null,
"e": 6867,
"s": 6805,
"text": "function LastDelimiter(const Delimiters: ; const S:):Integer;"
},
{
"code": null,
"e": 6908,
"s": 6867,
"text": "Last occurrence of character in a string"
},
{
"code": null,
"e": 6954,
"s": 6908,
"text": "function LeftStr(const S: ; Count: Integer):;"
},
{
"code": null,
"e": 6990,
"s": 6954,
"text": "Gets first N characters of a string"
},
{
"code": null,
"e": 7026,
"s": 6990,
"text": "function LoadStr(Ident: Integer):; "
},
{
"code": null,
"e": 7054,
"s": 7026,
"text": "Loads string from resources"
},
{
"code": null,
"e": 7097,
"s": 7054,
"text": "function LowerCase(const s: ):; overload; "
},
{
"code": null,
"e": 7130,
"s": 7097,
"text": "Converts string to all-lowercase"
},
{
"code": null,
"e": 7181,
"s": 7130,
"text": "function LowerCase(const V: variant ):; overload; "
},
{
"code": null,
"e": 7214,
"s": 7181,
"text": "Converts string to all-lowercase"
},
{
"code": null,
"e": 7259,
"s": 7214,
"text": "function NewStr(const S:):PString; overload;"
},
{
"code": null,
"e": 7288,
"s": 7259,
"text": "Allocates new string on heap"
},
{
"code": null,
"e": 7335,
"s": 7288,
"text": "function RightStr(const S: ; Count: Integer):;"
},
{
"code": null,
"e": 7370,
"s": 7335,
"text": "Gets last N characters of a string"
},
{
"code": null,
"e": 7411,
"s": 7370,
"text": "function StrAlloc(Size: Cardinal):PChar;"
},
{
"code": null,
"e": 7439,
"s": 7411,
"text": "Allocates memory for string"
},
{
"code": null,
"e": 7481,
"s": 7439,
"text": "function StrBufSize(Str: PChar):SizeUInt;"
},
{
"code": null,
"e": 7510,
"s": 7481,
"text": "Reserves memory for a string"
},
{
"code": null,
"e": 7544,
"s": 7510,
"text": "procedure StrDispose(Str: PChar);"
},
{
"code": null,
"e": 7569,
"s": 7544,
"text": "Removes string from heap"
},
{
"code": null,
"e": 7600,
"s": 7569,
"text": "function StrPas(Str: PChar):; "
},
{
"code": null,
"e": 7632,
"s": 7600,
"text": "Converts PChar to pascal string"
},
{
"code": null,
"e": 7679,
"s": 7632,
"text": "function StrPCopy(Dest: PChar; Source:):PChar;"
},
{
"code": null,
"e": 7700,
"s": 7679,
"text": "Copies pascal string"
},
{
"code": null,
"e": 7767,
"s": 7700,
"text": "function StrPLCopy(Dest: PChar; Source: ; MaxLen: SizeUInt):PChar;"
},
{
"code": null,
"e": 7799,
"s": 7767,
"text": "Copies N bytes of pascal string"
},
{
"code": null,
"e": 7830,
"s": 7799,
"text": "function UpperCase(const s:):;"
},
{
"code": null,
"e": 7863,
"s": 7830,
"text": "Converts string to all-uppercase"
},
{
"code": null,
"e": 7898,
"s": 7863,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7921,
"s": 7898,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7928,
"s": 7921,
"text": " Print"
},
{
"code": null,
"e": 7939,
"s": 7928,
"text": " Add Notes"
}
] |
HTML - <li>Tag | The HTML <li> tag is used for specifying a list item in ordered, unordered, directory, and menu lists.
<!DOCTYPE html>
<html>
<head>
<title>HTML li Tag</title>
</head>
<body>
<ul>
<li>ol - ordered list</li>
<li>ul - unordered list</li>
<li>dir - directory list</li>
<li>menu - menu list</li>
</ul>
</body>
</html>
This will produce the following result −
ol - ordered list
ul - unordered list
dir - directory list
menu - menu list
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <li> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2477,
"s": 2374,
"text": "The HTML <li> tag is used for specifying a list item in ordered, unordered, directory, and menu lists."
},
{
"code": null,
"e": 2757,
"s": 2477,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML li Tag</title>\n </head>\n\n <body>\n <ul>\n <li>ol - ordered list</li>\n <li>ul - unordered list</li>\n <li>dir - directory list</li>\n <li>menu - menu list</li>\n </ul>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2798,
"s": 2757,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2816,
"s": 2798,
"text": "ol - ordered list"
},
{
"code": null,
"e": 2836,
"s": 2816,
"text": "ul - unordered list"
},
{
"code": null,
"e": 2857,
"s": 2836,
"text": "dir - directory list"
},
{
"code": null,
"e": 2874,
"s": 2857,
"text": "menu - menu list"
},
{
"code": null,
"e": 2958,
"s": 2874,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 3029,
"s": 2958,
"text": "The HTML <li> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3109,
"s": 3029,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 3142,
"s": 3109,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3156,
"s": 3142,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3191,
"s": 3156,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3205,
"s": 3191,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3240,
"s": 3205,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3257,
"s": 3240,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3292,
"s": 3257,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3323,
"s": 3292,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3356,
"s": 3323,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3387,
"s": 3356,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3422,
"s": 3387,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3453,
"s": 3422,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3460,
"s": 3453,
"text": " Print"
},
{
"code": null,
"e": 3471,
"s": 3460,
"text": " Add Notes"
}
] |
Python Inheritance | Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called
base class.
Child class is the class that inherits from another class,
also called derived class.
Any class can be a parent class, so the syntax is the same as creating any
other class:
Create a class named Person, with
firstname and lastname properties,
and a printname method:
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child
class:
Create a class named Student, which will inherit the properties
and methods from
the Person class:
Note: Use the pass
keyword when you do not want to add any other properties or methods to the
class.
Now the Student class has the same properties and methods as the Person
class.
Use the Student class to create an object,
and then execute the printname method:
So far we have created a child class that inherits the properties and methods
from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Add the __init__() function to the
Student class:
When you add the __init__() function, the child class will no longer inherit
the parent's __init__() function.
Note: The child's __init__()
function overrides the inheritance of the parent's
__init__() function.
To keep the inheritance of the parent's __init__()
function, add a call to the
parent's __init__() function:
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in the
__init__() function.
Python also has a super() function that
will make the child class inherit all the methods and properties from its
parent:
By using the super() function, you do not
have to use the name of the parent element, it will automatically inherit the
methods and properties from its parent.
Add a property called graduationyear to the
Student class:
In the example below, the year 2019 should be a variable, and passed into the
Student class when creating student objects.
To do so, add another parameter in the __init__() function:
Add a year parameter, and pass the correct
year when creating objects:
Add a method called welcome to the
Student class:
If you add a method in the child class with the same name as a function in
the parent class, the inheritance of the parent method will be overridden.
What is the correct syntax to create a class named Student that will inherit properties and methods from a class named Person?
class :
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 105,
"s": 0,
"text": "Inheritance allows us to define a class that inherits all the methods and properties from another class."
},
{
"code": null,
"e": 178,
"s": 105,
"text": "Parent class is the class being inherited from, also called \nbase class."
},
{
"code": null,
"e": 265,
"s": 178,
"text": "Child class is the class that inherits from another class, \nalso called derived class."
},
{
"code": null,
"e": 354,
"s": 265,
"text": "Any class can be a parent class, so the syntax is the same as creating any \nother class:"
},
{
"code": null,
"e": 448,
"s": 354,
"text": "Create a class named Person, with\nfirstname and lastname properties, \nand a printname method:"
},
{
"code": null,
"e": 587,
"s": 448,
"text": "To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child \nclass:"
},
{
"code": null,
"e": 688,
"s": 587,
"text": "Create a class named Student, which will inherit the properties \nand methods from \nthe Person class:"
},
{
"code": null,
"e": 795,
"s": 688,
"text": "Note: Use the pass \n keyword when you do not want to add any other properties or methods to the \n class."
},
{
"code": null,
"e": 875,
"s": 795,
"text": "Now the Student class has the same properties and methods as the Person \nclass."
},
{
"code": null,
"e": 958,
"s": 875,
"text": "Use the Student class to create an object, \nand then execute the printname method:"
},
{
"code": null,
"e": 1054,
"s": 958,
"text": "So far we have created a child class that inherits the properties and methods \nfrom its parent."
},
{
"code": null,
"e": 1143,
"s": 1054,
"text": "We want to add the __init__() function to the child class (instead of the pass keyword)."
},
{
"code": null,
"e": 1256,
"s": 1143,
"text": "Note: The __init__() function is called automatically every time the class is being used to create a new object."
},
{
"code": null,
"e": 1306,
"s": 1256,
"text": "Add the __init__() function to the\nStudent class:"
},
{
"code": null,
"e": 1418,
"s": 1306,
"text": "When you add the __init__() function, the child class will no longer inherit \nthe parent's __init__() function."
},
{
"code": null,
"e": 1525,
"s": 1418,
"text": "Note: The child's __init__() \n function overrides the inheritance of the parent's \n __init__() function."
},
{
"code": null,
"e": 1636,
"s": 1525,
"text": "To keep the inheritance of the parent's __init__() \nfunction, add a call to the \nparent's __init__() function:"
},
{
"code": null,
"e": 1805,
"s": 1636,
"text": "Now we have successfully added the __init__() function, and kept the \ninheritance of the parent class, and we are ready to add functionality in the\n__init__() function."
},
{
"code": null,
"e": 1929,
"s": 1805,
"text": "Python also has a super() function that \nwill make the child class inherit all the methods and properties from its \nparent:"
},
{
"code": null,
"e": 2091,
"s": 1929,
"text": "By using the super() function, you do not \nhave to use the name of the parent element, it will automatically inherit the \nmethods and properties from its parent."
},
{
"code": null,
"e": 2150,
"s": 2091,
"text": "Add a property called graduationyear to the\nStudent class:"
},
{
"code": null,
"e": 2334,
"s": 2150,
"text": "In the example below, the year 2019 should be a variable, and passed into the \nStudent class when creating student objects.\nTo do so, add another parameter in the __init__() function:"
},
{
"code": null,
"e": 2406,
"s": 2334,
"text": "Add a year parameter, and pass the correct \nyear when creating objects:"
},
{
"code": null,
"e": 2456,
"s": 2406,
"text": "Add a method called welcome to the\nStudent class:"
},
{
"code": null,
"e": 2607,
"s": 2456,
"text": "If you add a method in the child class with the same name as a function in \nthe parent class, the inheritance of the parent method will be overridden."
},
{
"code": null,
"e": 2734,
"s": 2607,
"text": "What is the correct syntax to create a class named Student that will inherit properties and methods from a class named Person?"
},
{
"code": null,
"e": 2743,
"s": 2734,
"text": "class :\n"
},
{
"code": null,
"e": 2762,
"s": 2743,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2795,
"s": 2762,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2837,
"s": 2795,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2944,
"s": 2837,
"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": 2963,
"s": 2944,
"text": "[email protected]"
}
] |
Unable to locate an element using xpath error in selenium-java | We may encounter the error - unable to locate element while working with Selenium webdriver. This leads to NoSuchElementException. This type of exception is thrown when there is no element on the page which matches with the locator value.
If error is encountered, we can fix it by the following ways −
Check if there is any syntax error in our xpath expression.
Check if there is any syntax error in our xpath expression.
Add additional expected wait conditions for the element.
Add additional expected wait conditions for the element.
Use an alternative xpath expression.
Use an alternative xpath expression.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class XpathError{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://www.tutorialspoint.com/index.htm");
WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
m.click();
//explicit wait condition - visibilityOfElementLocated
w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
System.out.println("Page title: " + driver.getTitle());
driver.quit();
}
} | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "We may encounter the error - unable to locate element while working with Selenium webdriver. This leads to NoSuchElementException. This type of exception is thrown when there is no element on the page which matches with the locator value."
},
{
"code": null,
"e": 1364,
"s": 1301,
"text": "If error is encountered, we can fix it by the following ways −"
},
{
"code": null,
"e": 1424,
"s": 1364,
"text": "Check if there is any syntax error in our xpath expression."
},
{
"code": null,
"e": 1484,
"s": 1424,
"text": "Check if there is any syntax error in our xpath expression."
},
{
"code": null,
"e": 1541,
"s": 1484,
"text": "Add additional expected wait conditions for the element."
},
{
"code": null,
"e": 1598,
"s": 1541,
"text": "Add additional expected wait conditions for the element."
},
{
"code": null,
"e": 1635,
"s": 1598,
"text": "Use an alternative xpath expression."
},
{
"code": null,
"e": 1672,
"s": 1635,
"text": "Use an alternative xpath expression."
},
{
"code": null,
"e": 2595,
"s": 1672,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class XpathError{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //launch URL\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n WebElement m = driver.findElement(By.xpath(\"//*[text()='Library']\"));\n m.click();\n //explicit wait condition - visibilityOfElementLocated\n w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText(\"Subscribe to Premium\")));\n System.out.println(\"Page title: \" + driver.getTitle());\n driver.quit();\n }\n}"
}
] |
Creating 3D animation using matplotlib | To create a 3D animation using matplotlib, we can take the following steps −
Import the required packages. For 3D animation, you need to import Axes3D from mpl_toolkits.mplot3d and matplotlib.animation.
Set the figure size and adjust the padding between and around the subplots.
Create t, x, y and data points using numpy.
Create a new figure or activate an existing figure.
Get the instance of 3D axes.
Turn off the axes.
Plot the lines with data.
Create an animation by repeatedly calling a function *animate*.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def animate(num, data, line):
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
line.set_color(colors[num % len(colors)])
line.set_alpha(0.7)
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return line
t = np.arange(0, 20, 0.2)
x = np.cos(t) - 1
y = 1 / 2 * (np.cos(2 * t) - 1)
data = np.array([x, y, t])
N = len(t)
fig = plt.figure()
ax = Axes3D(fig)
ax.axis('off')
line, = plt.plot(data[0], data[1], data[2], lw=7, c='red')
line_ani = animation.FuncAnimation(fig, animate, frames=N, fargs=(data, line), interval=50, blit=False)
plt.show()
It will produce the following output | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To create a 3D animation using matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1265,
"s": 1139,
"text": "Import the required packages. For 3D animation, you need to import Axes3D from mpl_toolkits.mplot3d and matplotlib.animation."
},
{
"code": null,
"e": 1341,
"s": 1265,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1385,
"s": 1341,
"text": "Create t, x, y and data points using numpy."
},
{
"code": null,
"e": 1437,
"s": 1385,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1466,
"s": 1437,
"text": "Get the instance of 3D axes."
},
{
"code": null,
"e": 1485,
"s": 1466,
"text": "Turn off the axes."
},
{
"code": null,
"e": 1511,
"s": 1485,
"text": "Plot the lines with data."
},
{
"code": null,
"e": 1575,
"s": 1511,
"text": "Create an animation by repeatedly calling a function *animate*."
},
{
"code": null,
"e": 1617,
"s": 1575,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2493,
"s": 1617,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom mpl_toolkits.mplot3d import Axes3D\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef animate(num, data, line):\n colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\n line.set_color(colors[num % len(colors)])\n line.set_alpha(0.7)\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n return line\n\nt = np.arange(0, 20, 0.2)\nx = np.cos(t) - 1\ny = 1 / 2 * (np.cos(2 * t) - 1)\ndata = np.array([x, y, t])\nN = len(t)\nfig = plt.figure()\nax = Axes3D(fig)\nax.axis('off')\n\nline, = plt.plot(data[0], data[1], data[2], lw=7, c='red')\nline_ani = animation.FuncAnimation(fig, animate, frames=N, fargs=(data, line), interval=50, blit=False)\n\nplt.show()"
},
{
"code": null,
"e": 2530,
"s": 2493,
"text": "It will produce the following output"
}
] |
C# | Check if a thread belongs to managed thread pool or not - GeeksforGeeks | 01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsThreadPoolThread to check if the thread belongs to the managed thread pool or not.
Syntax:
public bool IsThreadPoolThread { get; }
Return Value: This property returns true if the given thread belongs to the managed thread pool. Otherwise, return false. The return type of this property is System.Boolean.
Below programs illustrate the use of IsThreadPoolThread property:
Example 1:
// C# program to illustrate the use // of IsThreadPoolThread propertyusing System;using System.Threading; class GFG { // Main Method static public void Main() { Thread T; // Get the reference of main Thread // Using CurrentThread property T = Thread.CurrentThread; // Check if the main thread belongs to // the managed thread pool or not // Using IsThreadPoolThread property Console.WriteLine("Is main thread belongs to Thread"+ " pool? : {0} ", T.IsThreadPoolThread); }}
Output:
Is main thread belongs to Thread pool? : False
Example 2:
// C# program to illustrate the use// of IsThreadPoolThread propertyusing System;using System.Threading; class GFG { // Main method public static void Main() { // Creating and initializing threads Thread TR1 = new Thread(new ThreadStart(job)); ThreadPool.QueueUserWorkItem(new WaitCallback(job1)); TR1.Start(); } // Static methods public static void job() { Console.WriteLine("Is thread 1 belongs to thread pool: {0}", Thread.CurrentThread.IsThreadPoolThread); } public static void job1(object stateInfo) { Console.WriteLine("Is thread 2 belongs to thread pool: {0}", Thread.CurrentThread.IsThreadPoolThread); }}
Output:
Is thread 1 belongs to thread pool: False
Is thread 2 belongs to thread pool: True
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isthreadpoolthread?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24513,
"s": 24302,
"text": "A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsThreadPoolThread to check if the thread belongs to the managed thread pool or not."
},
{
"code": null,
"e": 24521,
"s": 24513,
"text": "Syntax:"
},
{
"code": null,
"e": 24561,
"s": 24521,
"text": "public bool IsThreadPoolThread { get; }"
},
{
"code": null,
"e": 24735,
"s": 24561,
"text": "Return Value: This property returns true if the given thread belongs to the managed thread pool. Otherwise, return false. The return type of this property is System.Boolean."
},
{
"code": null,
"e": 24801,
"s": 24735,
"text": "Below programs illustrate the use of IsThreadPoolThread property:"
},
{
"code": null,
"e": 24812,
"s": 24801,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the use // of IsThreadPoolThread propertyusing System;using System.Threading; class GFG { // Main Method static public void Main() { Thread T; // Get the reference of main Thread // Using CurrentThread property T = Thread.CurrentThread; // Check if the main thread belongs to // the managed thread pool or not // Using IsThreadPoolThread property Console.WriteLine(\"Is main thread belongs to Thread\"+ \" pool? : {0} \", T.IsThreadPoolThread); }}",
"e": 25382,
"s": 24812,
"text": null
},
{
"code": null,
"e": 25390,
"s": 25382,
"text": "Output:"
},
{
"code": null,
"e": 25438,
"s": 25390,
"text": "Is main thread belongs to Thread pool? : False "
},
{
"code": null,
"e": 25449,
"s": 25438,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the use// of IsThreadPoolThread propertyusing System;using System.Threading; class GFG { // Main method public static void Main() { // Creating and initializing threads Thread TR1 = new Thread(new ThreadStart(job)); ThreadPool.QueueUserWorkItem(new WaitCallback(job1)); TR1.Start(); } // Static methods public static void job() { Console.WriteLine(\"Is thread 1 belongs to thread pool: {0}\", Thread.CurrentThread.IsThreadPoolThread); } public static void job1(object stateInfo) { Console.WriteLine(\"Is thread 2 belongs to thread pool: {0}\", Thread.CurrentThread.IsThreadPoolThread); }}",
"e": 26200,
"s": 25449,
"text": null
},
{
"code": null,
"e": 26208,
"s": 26200,
"text": "Output:"
},
{
"code": null,
"e": 26292,
"s": 26208,
"text": "Is thread 1 belongs to thread pool: False\nIs thread 2 belongs to thread pool: True\n"
},
{
"code": null,
"e": 26303,
"s": 26292,
"text": "Reference:"
},
{
"code": null,
"e": 26414,
"s": 26303,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isthreadpoolthread?view=netframework-4.7.2"
},
{
"code": null,
"e": 26436,
"s": 26414,
"text": "CSharp Multithreading"
},
{
"code": null,
"e": 26456,
"s": 26436,
"text": "CSharp Thread Class"
},
{
"code": null,
"e": 26459,
"s": 26456,
"text": "C#"
},
{
"code": null,
"e": 26557,
"s": 26459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26575,
"s": 26557,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26598,
"s": 26575,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26626,
"s": 26598,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26666,
"s": 26626,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26709,
"s": 26666,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26731,
"s": 26709,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26748,
"s": 26731,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26764,
"s": 26748,
"text": "C# | List Class"
},
{
"code": null,
"e": 26814,
"s": 26764,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
How to Create a Tolerance Chart in Excel? | 01 May, 2021
A tolerance chart shows how a particular data item compares to the maximum and minimum permissible values. In this article, we’ll analyze the average results of the students of a class using a tolerance chart.
Tolerance Chart
Follow the below steps to create a Tolerance chart in Excel:
Step 1: The first step is to make your data table. This table must have three main attributes, Minimum, Maximum, and Range. Here, the range is the difference between the Maximum and the Minimum values. You can use this formula and apply it to all corresponding cells. Take a look at the following image for better clarity.
Step 2: Next, select the entire table and click on Insert.
Note: The menus may look different for different versions of Excel, but the basic principles remain the same.
Step 3: Find Stacked Area Chart under the Charts sub-section, and click on it. You may delete the legend on the right-hand side if you want.
Stacked Area Chart
Step 4: Now, from the table, select all the values from the ‘min’ row. Then click Ctrl + C, to copy. Now, click on the chart and hit Ctrl + V, to paste. This will result in an additional layer being added to the stacked chart as shown below:
Step 5: Now, select the colored charts that correspond to Min (the top-most layer), Max, and Result and make the following conversions. Note – All others remain the same.
Max --> Line Chart
Min --> Line Chart
Result --> Line Chart with Markers
Right-click on the Layer you want to change and click on ‘Change Series Chart Type‘
The following screen will appear where you can select from the available Line Charts on the left.
Select Line from the left pane and choose the corresponding Line Chart mentioned above.
Do, this for all items and the final result would look something like this.
Step 6: Now, select the bottom-most layer, i.e., the min layer, and double-click on it. Then, select No Fill from the Fill section on the left.
Step 7: Next, right-click on the bottom axis and select Format Axis. Navigate to the bottom and select “On tick Marks”.
Your Tolerance Chart is ready!
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Introduction to Excel Spreadsheet
How to make a 3 Axis Graph using Excel?
Macros in Excel
How to Extract the Last Word From a Cell in Excel? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2021"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "A tolerance chart shows how a particular data item compares to the maximum and minimum permissible values. In this article, we’ll analyze the average results of the students of a class using a tolerance chart."
},
{
"code": null,
"e": 254,
"s": 238,
"text": "Tolerance Chart"
},
{
"code": null,
"e": 315,
"s": 254,
"text": "Follow the below steps to create a Tolerance chart in Excel:"
},
{
"code": null,
"e": 638,
"s": 315,
"text": "Step 1: The first step is to make your data table. This table must have three main attributes, Minimum, Maximum, and Range. Here, the range is the difference between the Maximum and the Minimum values. You can use this formula and apply it to all corresponding cells. Take a look at the following image for better clarity."
},
{
"code": null,
"e": 698,
"s": 638,
"text": "Step 2: Next, select the entire table and click on Insert. "
},
{
"code": null,
"e": 808,
"s": 698,
"text": "Note: The menus may look different for different versions of Excel, but the basic principles remain the same."
},
{
"code": null,
"e": 949,
"s": 808,
"text": "Step 3: Find Stacked Area Chart under the Charts sub-section, and click on it. You may delete the legend on the right-hand side if you want."
},
{
"code": null,
"e": 968,
"s": 949,
"text": "Stacked Area Chart"
},
{
"code": null,
"e": 1210,
"s": 968,
"text": "Step 4: Now, from the table, select all the values from the ‘min’ row. Then click Ctrl + C, to copy. Now, click on the chart and hit Ctrl + V, to paste. This will result in an additional layer being added to the stacked chart as shown below:"
},
{
"code": null,
"e": 1381,
"s": 1210,
"text": "Step 5: Now, select the colored charts that correspond to Min (the top-most layer), Max, and Result and make the following conversions. Note – All others remain the same."
},
{
"code": null,
"e": 1454,
"s": 1381,
"text": "Max --> Line Chart\nMin --> Line Chart\nResult --> Line Chart with Markers"
},
{
"code": null,
"e": 1538,
"s": 1454,
"text": "Right-click on the Layer you want to change and click on ‘Change Series Chart Type‘"
},
{
"code": null,
"e": 1636,
"s": 1538,
"text": "The following screen will appear where you can select from the available Line Charts on the left."
},
{
"code": null,
"e": 1724,
"s": 1636,
"text": "Select Line from the left pane and choose the corresponding Line Chart mentioned above."
},
{
"code": null,
"e": 1800,
"s": 1724,
"text": "Do, this for all items and the final result would look something like this."
},
{
"code": null,
"e": 1944,
"s": 1800,
"text": "Step 6: Now, select the bottom-most layer, i.e., the min layer, and double-click on it. Then, select No Fill from the Fill section on the left."
},
{
"code": null,
"e": 2064,
"s": 1944,
"text": "Step 7: Next, right-click on the bottom axis and select Format Axis. Navigate to the bottom and select “On tick Marks”."
},
{
"code": null,
"e": 2095,
"s": 2064,
"text": "Your Tolerance Chart is ready!"
},
{
"code": null,
"e": 2102,
"s": 2095,
"text": "Picked"
},
{
"code": null,
"e": 2108,
"s": 2102,
"text": "Excel"
},
{
"code": null,
"e": 2206,
"s": 2108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2244,
"s": 2206,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 2285,
"s": 2244,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 2317,
"s": 2285,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 2372,
"s": 2317,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 2400,
"s": 2372,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 2458,
"s": 2400,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 2492,
"s": 2458,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 2532,
"s": 2492,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 2548,
"s": 2532,
"text": "Macros in Excel"
}
] |
How to Execute WordCount Program in MapReduce using Cloudera Distribution Hadoop(CDH) | 24 Jun, 2021
Counting the number of words in any language is a piece of cake like in C, C++, Python, Java, etc. MapReduce also uses Java but it is very easy if you know the syntax on how to write it. It is the basic of MapReduce. You will first learn how to execute this code similar to “Hello World” program in other languages. So here are the steps which show how to write a MapReduce code for Word Count.Example:Input:
Hello I am GeeksforGeeks
Hello I am an Intern
Output:
GeeksforGeeks 1
Hello 2
I 2
Intern 1
am 2
an 1
Steps:
First Open Eclipse -> then select File -> New -> Java Project ->Name it WordCount -> then Finish.
Create Three Java Classes into the project. Name them WCDriver(having the main function), WCMapper, WCReducer.
You have to include two Reference Libraries for that:Right Click on Project -> then select Build Path-> Click on Configure Build Path
In the above figure, you can see the Add External JARs option on the Right Hand Side. Click on it and add the below mention files. You can find these files in /usr/lib/1. /usr/lib/hadoop-0.20-mapreduce/hadoop-core-2.6.0-mr1-cdh5.13.0.jar 2. /usr/lib/hadoop/hadoop-common-2.6.0-cdh5.13.0.jar
Mapper Code: You have to copy paste this program into the WCMapper Java Class file.
Java
// Importing librariesimport java.io.IOException;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.Mapper;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reporter; public class WCMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { // Map function public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter rep) throws IOException { String line = value.toString(); // Splitting the line on spaces for (String word : line.split(" ")) { if (word.length() > 0) { output.collect(new Text(word), new IntWritable(1)); } } }}
Reducer Code: You have to copy paste this program into the WCReducer Java Class file.
Java
// Importing librariesimport java.io.IOException;import java.util.Iterator;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reducer;import org.apache.hadoop.mapred.Reporter; public class WCReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { // Reduce function public void reduce(Text key, Iterator<IntWritable> value, OutputCollector<Text, IntWritable> output, Reporter rep) throws IOException { int count = 0; // Counting the frequency of each words while (value.hasNext()) { IntWritable i = value.next(); count += i.get(); } output.collect(key, new IntWritable(count)); }}
Driver Code: You have to copy paste this program into the WCDriver Java Class file.
Java
// Importing librariesimport java.io.IOException;import org.apache.hadoop.conf.Configured;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.FileInputFormat;import org.apache.hadoop.mapred.FileOutputFormat;import org.apache.hadoop.mapred.JobClient;import org.apache.hadoop.mapred.JobConf;import org.apache.hadoop.util.Tool;import org.apache.hadoop.util.ToolRunner; public class WCDriver extends Configured implements Tool { public int run(String args[]) throws IOException { if (args.length < 2) { System.out.println("Please give valid inputs"); return -1; } JobConf conf = new JobConf(WCDriver.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); conf.setMapperClass(WCMapper.class); conf.setReducerClass(WCReducer.class); conf.setMapOutputKeyClass(Text.class); conf.setMapOutputValueClass(IntWritable.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); JobClient.runJob(conf); return 0; } // Main Method public static void main(String args[]) throws Exception { int exitCode = ToolRunner.run(new WCDriver(), args); System.out.println(exitCode); }}
Now you have to make a jar file. Right Click on Project-> Click on Export-> Select export destination as Jar File-> Name the jar File(WordCount.jar) -> Click on next -> at last Click on Finish. Now copy this file into the Workspace directory of Cloudera
Open the terminal on CDH and change the directory to the workspace. You can do this by using “cd workspace/” command. Now, Create a text file(WCFile.txt) and move it to HDFS. For that open terminal and write this code(remember you should be in the same directory as jar file you have created just now).
Now, run this command to copy the file input file into the HDFS.
hadoop fs -put WCFile.txt WCFile.txt
Now to run the jar file by writing the code as shown in the screenshot.
After Executing the code, you can see the result in WCOutput file or by writing following command on terminal.
hadoop fs -cat WCOutput/part-00000
maxkhkh5
surinderdawra388
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Hadoop and Spark
Hadoop Streaming Using Python - Word Count Problem
Architecture of HBase
Hadoop - Different Modes of Operation
What is Big Data?
Architecture and Working of Hive
How to Create Table in Hive?
Applications of Big Data
Introduction to Apache Pig
What is Schema On Read and Schema On Write in Hadoop? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 463,
"s": 52,
"text": "Counting the number of words in any language is a piece of cake like in C, C++, Python, Java, etc. MapReduce also uses Java but it is very easy if you know the syntax on how to write it. It is the basic of MapReduce. You will first learn how to execute this code similar to “Hello World” program in other languages. So here are the steps which show how to write a MapReduce code for Word Count.Example:Input: "
},
{
"code": null,
"e": 509,
"s": 463,
"text": "Hello I am GeeksforGeeks\nHello I am an Intern"
},
{
"code": null,
"e": 518,
"s": 509,
"text": "Output: "
},
{
"code": null,
"e": 590,
"s": 518,
"text": "GeeksforGeeks 1\nHello 2\nI 2\nIntern 1\nam 2\nan 1"
},
{
"code": null,
"e": 599,
"s": 590,
"text": "Steps: "
},
{
"code": null,
"e": 698,
"s": 599,
"text": "First Open Eclipse -> then select File -> New -> Java Project ->Name it WordCount -> then Finish. "
},
{
"code": null,
"e": 809,
"s": 698,
"text": "Create Three Java Classes into the project. Name them WCDriver(having the main function), WCMapper, WCReducer."
},
{
"code": null,
"e": 944,
"s": 809,
"text": "You have to include two Reference Libraries for that:Right Click on Project -> then select Build Path-> Click on Configure Build Path "
},
{
"code": null,
"e": 1236,
"s": 944,
"text": "In the above figure, you can see the Add External JARs option on the Right Hand Side. Click on it and add the below mention files. You can find these files in /usr/lib/1. /usr/lib/hadoop-0.20-mapreduce/hadoop-core-2.6.0-mr1-cdh5.13.0.jar 2. /usr/lib/hadoop/hadoop-common-2.6.0-cdh5.13.0.jar "
},
{
"code": null,
"e": 1323,
"s": 1238,
"text": "Mapper Code: You have to copy paste this program into the WCMapper Java Class file. "
},
{
"code": null,
"e": 1328,
"s": 1323,
"text": "Java"
},
{
"code": "// Importing librariesimport java.io.IOException;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.Mapper;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reporter; public class WCMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { // Map function public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter rep) throws IOException { String line = value.toString(); // Splitting the line on spaces for (String word : line.split(\" \")) { if (word.length() > 0) { output.collect(new Text(word), new IntWritable(1)); } } }}",
"e": 2256,
"s": 1328,
"text": null
},
{
"code": null,
"e": 2343,
"s": 2256,
"text": "Reducer Code: You have to copy paste this program into the WCReducer Java Class file. "
},
{
"code": null,
"e": 2348,
"s": 2343,
"text": "Java"
},
{
"code": "// Importing librariesimport java.io.IOException;import java.util.Iterator;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.MapReduceBase;import org.apache.hadoop.mapred.OutputCollector;import org.apache.hadoop.mapred.Reducer;import org.apache.hadoop.mapred.Reporter; public class WCReducer extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { // Reduce function public void reduce(Text key, Iterator<IntWritable> value, OutputCollector<Text, IntWritable> output, Reporter rep) throws IOException { int count = 0; // Counting the frequency of each words while (value.hasNext()) { IntWritable i = value.next(); count += i.get(); } output.collect(key, new IntWritable(count)); }}",
"e": 3270,
"s": 2348,
"text": null
},
{
"code": null,
"e": 3355,
"s": 3270,
"text": "Driver Code: You have to copy paste this program into the WCDriver Java Class file. "
},
{
"code": null,
"e": 3360,
"s": 3355,
"text": "Java"
},
{
"code": "// Importing librariesimport java.io.IOException;import org.apache.hadoop.conf.Configured;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapred.FileInputFormat;import org.apache.hadoop.mapred.FileOutputFormat;import org.apache.hadoop.mapred.JobClient;import org.apache.hadoop.mapred.JobConf;import org.apache.hadoop.util.Tool;import org.apache.hadoop.util.ToolRunner; public class WCDriver extends Configured implements Tool { public int run(String args[]) throws IOException { if (args.length < 2) { System.out.println(\"Please give valid inputs\"); return -1; } JobConf conf = new JobConf(WCDriver.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); conf.setMapperClass(WCMapper.class); conf.setReducerClass(WCReducer.class); conf.setMapOutputKeyClass(Text.class); conf.setMapOutputValueClass(IntWritable.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); JobClient.runJob(conf); return 0; } // Main Method public static void main(String args[]) throws Exception { int exitCode = ToolRunner.run(new WCDriver(), args); System.out.println(exitCode); }}",
"e": 4760,
"s": 3360,
"text": null
},
{
"code": null,
"e": 5015,
"s": 4760,
"text": "Now you have to make a jar file. Right Click on Project-> Click on Export-> Select export destination as Jar File-> Name the jar File(WordCount.jar) -> Click on next -> at last Click on Finish. Now copy this file into the Workspace directory of Cloudera "
},
{
"code": null,
"e": 5325,
"s": 5021,
"text": "Open the terminal on CDH and change the directory to the workspace. You can do this by using “cd workspace/” command. Now, Create a text file(WCFile.txt) and move it to HDFS. For that open terminal and write this code(remember you should be in the same directory as jar file you have created just now). "
},
{
"code": null,
"e": 5391,
"s": 5325,
"text": "Now, run this command to copy the file input file into the HDFS. "
},
{
"code": null,
"e": 5428,
"s": 5391,
"text": "hadoop fs -put WCFile.txt WCFile.txt"
},
{
"code": null,
"e": 5503,
"s": 5430,
"text": "Now to run the jar file by writing the code as shown in the screenshot. "
},
{
"code": null,
"e": 5615,
"s": 5503,
"text": "After Executing the code, you can see the result in WCOutput file or by writing following command on terminal. "
},
{
"code": null,
"e": 5650,
"s": 5615,
"text": "hadoop fs -cat WCOutput/part-00000"
},
{
"code": null,
"e": 5663,
"s": 5654,
"text": "maxkhkh5"
},
{
"code": null,
"e": 5680,
"s": 5663,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5687,
"s": 5680,
"text": "Hadoop"
},
{
"code": null,
"e": 5694,
"s": 5687,
"text": "Hadoop"
},
{
"code": null,
"e": 5792,
"s": 5694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5828,
"s": 5792,
"text": "Difference Between Hadoop and Spark"
},
{
"code": null,
"e": 5879,
"s": 5828,
"text": "Hadoop Streaming Using Python - Word Count Problem"
},
{
"code": null,
"e": 5901,
"s": 5879,
"text": "Architecture of HBase"
},
{
"code": null,
"e": 5939,
"s": 5901,
"text": "Hadoop - Different Modes of Operation"
},
{
"code": null,
"e": 5957,
"s": 5939,
"text": "What is Big Data?"
},
{
"code": null,
"e": 5990,
"s": 5957,
"text": "Architecture and Working of Hive"
},
{
"code": null,
"e": 6019,
"s": 5990,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 6044,
"s": 6019,
"text": "Applications of Big Data"
},
{
"code": null,
"e": 6071,
"s": 6044,
"text": "Introduction to Apache Pig"
}
] |
How to start a new activity by clicking a button on Android using Kotlin? | This example demonstrates how to start new activity on click button on Android using Kotlin
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@android:color/background_dark"
android:padding="4dp"
android:text="Open New Activity"
android:textColor="@color/colorAccent"
android:textSize="32sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
}
Step 4 − Create a new activity and add the following code −
activity_second.xml −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="4dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Welcome to Second Activity"
android:textAlignment="center"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
SecondActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code. | [
{
"code": null,
"e": 1279,
"s": 1187,
"text": "This example demonstrates how to start new activity on click button on Android using Kotlin"
},
{
"code": null,
"e": 1408,
"s": 1279,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1473,
"s": 1408,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2489,
"s": 1473,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:background=\"@android:color/background_dark\"\n android:padding=\"4dp\"\n android:text=\"Open New Activity\"\n android:textColor=\"@color/colorAccent\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2544,
"s": 2489,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3057,
"s": 2544,
"text": "import android.content.Intent\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n val button: Button = findViewById(R.id.button)\n button.setOnClickListener {\n val intent = Intent(this, SecondActivity::class.java)\n startActivity(intent)\n }\n }\n}"
},
{
"code": null,
"e": 3117,
"s": 3057,
"text": "Step 4 − Create a new activity and add the following code −"
},
{
"code": null,
"e": 3139,
"s": 3117,
"text": "activity_second.xml −"
},
{
"code": null,
"e": 4130,
"s": 3139,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:padding=\"4dp\"\n android:layout_height=\"match_parent\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Welcome to Second Activity\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 4148,
"s": 4130,
"text": "SecondActivity.kt"
},
{
"code": null,
"e": 4417,
"s": 4148,
"text": "import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nclass SecondActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_second)\n }\n}"
},
{
"code": null,
"e": 4472,
"s": 4417,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5143,
"s": 4472,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5493,
"s": 5143,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 5534,
"s": 5493,
"text": "Click here to download the project code."
}
] |
How to copy a table from one MySQL database to another? | The following is the syntax to copy a table from one database to another.
INSERT INTO yourDestinationDatabaseName.yourTableName SELECT * from yourSourceDatabaseName.yourtableName;
Let us see an example.
The CREATE command is used to create a table in the database ‘business’. We are creating a new table here.
mysql> use business;
Database changed
mysql> create table OriginalTable
-> (
-> id int
-> );
Query OK, 0 rows affected (0.46 sec)
Creating a new table in the database ‘test’.
mysql> use test;
Database changed
mysql> create table OriginalTable
-> (
-> id int
-> );
Query OK, 0 rows affected (0.47 sec
Records are inserted with the help of INSERT command in the first table.
mysql> use business;
Database changed
mysql> insert into OriginalTable values(1),(2),(3),(4);
Query OK, 4 rows affected (0.18 sec)
Records: 4 Duplicates: 0 Warnings: 0
To display all the records.
mysql> select *from OriginalTable;
Here is the output.
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
4 rows in set (0.00 sec)
To copy the above table from database “business” into another database “test”.
mysql> INSERT INTO test.OriginalTable SELECT * from business.OriginalTable;
Query OK, 4 rows affected (0.20 sec)
Records: 4 Duplicates: 0 Warnings: 0
To check if the table has been copied.
mysql> use test;
Database changed
mysql> select *from OriginalTable;
The following output shows that the table “OriginalTable” have been copied successfully into the second database.
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1261,
"s": 1187,
"text": "The following is the syntax to copy a table from one database to another."
},
{
"code": null,
"e": 1368,
"s": 1261,
"text": "INSERT INTO yourDestinationDatabaseName.yourTableName SELECT * from yourSourceDatabaseName.yourtableName;\n"
},
{
"code": null,
"e": 1391,
"s": 1368,
"text": "Let us see an example."
},
{
"code": null,
"e": 1498,
"s": 1391,
"text": "The CREATE command is used to create a table in the database ‘business’. We are creating a new table here."
},
{
"code": null,
"e": 1637,
"s": 1498,
"text": "mysql> use business;\nDatabase changed\nmysql> create table OriginalTable\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 1682,
"s": 1637,
"text": "Creating a new table in the database ‘test’."
},
{
"code": null,
"e": 1816,
"s": 1682,
"text": "mysql> use test;\nDatabase changed\nmysql> create table OriginalTable\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.47 sec"
},
{
"code": null,
"e": 1889,
"s": 1816,
"text": "Records are inserted with the help of INSERT command in the first table."
},
{
"code": null,
"e": 2059,
"s": 1889,
"text": "mysql> use business;\nDatabase changed\nmysql> insert into OriginalTable values(1),(2),(3),(4);\nQuery OK, 4 rows affected (0.18 sec)\nRecords: 4 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2087,
"s": 2059,
"text": "To display all the records."
},
{
"code": null,
"e": 2122,
"s": 2087,
"text": "mysql> select *from OriginalTable;"
},
{
"code": null,
"e": 2142,
"s": 2122,
"text": "Here is the output."
},
{
"code": null,
"e": 2240,
"s": 2142,
"text": "+------+\n| id |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+------+\n4 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2319,
"s": 2240,
"text": "To copy the above table from database “business” into another database “test”."
},
{
"code": null,
"e": 2472,
"s": 2319,
"text": "mysql> INSERT INTO test.OriginalTable SELECT * from business.OriginalTable;\nQuery OK, 4 rows affected (0.20 sec)\nRecords: 4 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2511,
"s": 2472,
"text": "To check if the table has been copied."
},
{
"code": null,
"e": 2580,
"s": 2511,
"text": "mysql> use test;\nDatabase changed\nmysql> select *from OriginalTable;"
},
{
"code": null,
"e": 2694,
"s": 2580,
"text": "The following output shows that the table “OriginalTable” have been copied successfully into the second database."
},
{
"code": null,
"e": 2792,
"s": 2694,
"text": "+------+\n| id |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+------+\n4 rows in set (0.00 sec)\n"
}
] |
Print the middle character of a string | 10 Nov, 2021
Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character.
Examples:
Input: str = “Java”Output: vExplanation: The length of the given string is even. Therefore, there would be two middle characters ‘a’ and ‘v’, we print the second middle character.
Input: str = “GeeksForGeeks”Output: oExplanation: The length of the given string is odd. Therefore, there would be only one middle character, we print that middle character.
Approach:
Get the string whose middle character is to be found.Calculate the length of the given string.Finding the middle index of the string.Now, print the middle character of the string at index middle using function charAt() in Java.
Get the string whose middle character is to be found.
Calculate the length of the given string.
Finding the middle index of the string.
Now, print the middle character of the string at index middle using function charAt() in Java.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function that prints the middle// character of a stringvoid printMiddleCharacter(string str){ // Finding string length int len = str.size(); // Finding middle index of string int middle = len / 2; // Print the middle character // of the string cout << str[middle];} // Driver Codeint main(){ // Given string str string str = "GeeksForGeeks"; // Function Call printMiddleCharacter(str); return 0;} // This code is contributed by Sapnasingh
// Java program for the above approachclass GFG { // Function that prints the middle // character of a string public static void printMiddleCharacter(String str) { // Finding string length int len = str.length(); // Finding middle index of string int middle = len / 2; // Print the middle character // of the string System.out.println(str.charAt(middle)); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call printMiddleCharacter(str); }}
# Python3 program for the above approach # Function that prints the middle# character of a stringdef printMiddleCharacter(str): # Finding string length length = len(str); # Finding middle index of string middle = length // 2; # Print the middle character # of the string print(str[middle]); # Driver Code # Given string strstr = "GeeksForGeeks"; # Function CallprintMiddleCharacter(str); # This code is contributed by sapnasingh4991
// C# program for the above approachusing System; class GFG{ // Function that prints the middle// character of a stringpublic static void printMiddlechar(String str){ // Finding string length int len = str.Length; // Finding middle index of string int middle = len / 2; // Print the middle character // of the string Console.WriteLine(str[middle]);} // Driver Codepublic static void Main(String []args){ // Given string str String str = "GeeksForGeeks"; // Function call printMiddlechar(str);}} // This code is contributed by amal kumar choubey
<script> // Javascript program for the above approach // Function that prints the middle // character of a string function printMiddleCharacter(str) { // Finding string length let len = str.length; // Finding middle index of string let middle = parseInt(len / 2, 10); // Print the middle character // of the string document.write(str[middle]); } // Given string str let str = "GeeksForGeeks"; // Function Call printMiddleCharacter(str); // This code is contributed by divyeshrabadiya07.</script>
o
Time Complexity: O(1) Auxiliary Space: O(1)
Amal Kumar Choubey
sapnasingh4991
divyeshrabadiya07
Kirti_Mangal
Java-String-Programs
strings
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exception Handling in C++
Different ways of Reading a text file in Java
Operators in C / C++
Introduction To PYTHON
Destructors in C++
Write a program to reverse an array or string
KMP Algorithm for Pattern Searching
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 252,
"s": 53,
"text": "Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character."
},
{
"code": null,
"e": 262,
"s": 252,
"text": "Examples:"
},
{
"code": null,
"e": 442,
"s": 262,
"text": "Input: str = “Java”Output: vExplanation: The length of the given string is even. Therefore, there would be two middle characters ‘a’ and ‘v’, we print the second middle character."
},
{
"code": null,
"e": 616,
"s": 442,
"text": "Input: str = “GeeksForGeeks”Output: oExplanation: The length of the given string is odd. Therefore, there would be only one middle character, we print that middle character."
},
{
"code": null,
"e": 626,
"s": 616,
"text": "Approach:"
},
{
"code": null,
"e": 854,
"s": 626,
"text": "Get the string whose middle character is to be found.Calculate the length of the given string.Finding the middle index of the string.Now, print the middle character of the string at index middle using function charAt() in Java."
},
{
"code": null,
"e": 908,
"s": 854,
"text": "Get the string whose middle character is to be found."
},
{
"code": null,
"e": 950,
"s": 908,
"text": "Calculate the length of the given string."
},
{
"code": null,
"e": 990,
"s": 950,
"text": "Finding the middle index of the string."
},
{
"code": null,
"e": 1085,
"s": 990,
"text": "Now, print the middle character of the string at index middle using function charAt() in Java."
},
{
"code": null,
"e": 1136,
"s": 1085,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1140,
"s": 1136,
"text": "C++"
},
{
"code": null,
"e": 1145,
"s": 1140,
"text": "Java"
},
{
"code": null,
"e": 1153,
"s": 1145,
"text": "Python3"
},
{
"code": null,
"e": 1156,
"s": 1153,
"text": "C#"
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function that prints the middle// character of a stringvoid printMiddleCharacter(string str){ // Finding string length int len = str.size(); // Finding middle index of string int middle = len / 2; // Print the middle character // of the string cout << str[middle];} // Driver Codeint main(){ // Given string str string str = \"GeeksForGeeks\"; // Function Call printMiddleCharacter(str); return 0;} // This code is contributed by Sapnasingh",
"e": 1741,
"s": 1167,
"text": null
},
{
"code": "// Java program for the above approachclass GFG { // Function that prints the middle // character of a string public static void printMiddleCharacter(String str) { // Finding string length int len = str.length(); // Finding middle index of string int middle = len / 2; // Print the middle character // of the string System.out.println(str.charAt(middle)); } // Driver Code public static void main(String args[]) { // Given string str String str = \"GeeksForGeeks\"; // Function Call printMiddleCharacter(str); }}",
"e": 2367,
"s": 1741,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that prints the middle# character of a stringdef printMiddleCharacter(str): # Finding string length length = len(str); # Finding middle index of string middle = length // 2; # Print the middle character # of the string print(str[middle]); # Driver Code # Given string strstr = \"GeeksForGeeks\"; # Function CallprintMiddleCharacter(str); # This code is contributed by sapnasingh4991",
"e": 2828,
"s": 2367,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function that prints the middle// character of a stringpublic static void printMiddlechar(String str){ // Finding string length int len = str.Length; // Finding middle index of string int middle = len / 2; // Print the middle character // of the string Console.WriteLine(str[middle]);} // Driver Codepublic static void Main(String []args){ // Given string str String str = \"GeeksForGeeks\"; // Function call printMiddlechar(str);}} // This code is contributed by amal kumar choubey",
"e": 3419,
"s": 2828,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function that prints the middle // character of a string function printMiddleCharacter(str) { // Finding string length let len = str.length; // Finding middle index of string let middle = parseInt(len / 2, 10); // Print the middle character // of the string document.write(str[middle]); } // Given string str let str = \"GeeksForGeeks\"; // Function Call printMiddleCharacter(str); // This code is contributed by divyeshrabadiya07.</script>",
"e": 4009,
"s": 3419,
"text": null
},
{
"code": null,
"e": 4011,
"s": 4009,
"text": "o"
},
{
"code": null,
"e": 4058,
"s": 4013,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4077,
"s": 4058,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 4092,
"s": 4077,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 4110,
"s": 4092,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 4123,
"s": 4110,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 4144,
"s": 4123,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 4152,
"s": 4144,
"text": "strings"
},
{
"code": null,
"e": 4171,
"s": 4152,
"text": "School Programming"
},
{
"code": null,
"e": 4179,
"s": 4171,
"text": "Strings"
},
{
"code": null,
"e": 4187,
"s": 4179,
"text": "Strings"
},
{
"code": null,
"e": 4285,
"s": 4187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4311,
"s": 4285,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 4357,
"s": 4311,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 4378,
"s": 4357,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4401,
"s": 4378,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4420,
"s": 4401,
"text": "Destructors in C++"
},
{
"code": null,
"e": 4466,
"s": 4420,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4502,
"s": 4466,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 4562,
"s": 4502,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4596,
"s": 4562,
"text": "Longest Common Subsequence | DP-4"
}
] |
How to Alter a SQLite Table using Python ? | 03 Jun, 2021
In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module.
We can do this by using ALTER statement. It allows to:
Add one or more column to the table
The syntax of ALTER TABLE to add a new column in an existing table in SQLite is given below:
ALTER TABLE table_name ADD COLUMN column_name colume_type
The column is added but will have all the values to be NULL.
To create a table:
Python3
import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Drop the GEEK table if already exists.cursor_obj.execute("DROP TABLE IF EXISTS GEEK") # Creating tabletable = """ CREATE TABLE GEEK ( Email VARCHAR(255) NOT NULL, Name CHAR(25) NOT NULL, Score INT ); """ cursor_obj.execute(table) # Inserting data into geek tableconnection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek1",25)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek2",15)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek3",36)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek4",27)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek5",40)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek6",14)""")connection_obj.execute( """INSERT INTO GEEK (Email,Name,Score) VALUES ("[email protected]","Geek7",10)""") # Display tabledata = cursor_obj.execute("""SELECT * FROM GEEK""")print('GEEK Table:')for row in data: print(row) connection_obj.commit() # Close the connectionconnection_obj.close()
Output:
Now we add a new column “UserName”:
Python3
import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Add a new column to geek tablenew_column = "ALTER TABLE GEEK ADD COLUMN UserName CHAR(25)" cursor_obj.execute(new_column) # Display tabledata = cursor_obj.execute("SELECT * FROM GEEK")print('GEEK Table:')for row in data: print(row) connection_obj.commit() # Close the connectionconnection_obj.close()
Output:
The syntax of ALTER TABLE to change the name of the table in SQLite is given below:
ALTER TABLE table_name RENAME TO newTableName;
We will use the same GEEK table that we created above:
Python3
import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # select from sqlite_mastercursor_obj.execute("SELECT * FROM sqlite_master") table = cursor_obj.fetchall()print("Before changing the name of Table")print("The name of the table:", table[0][2]) # Rename the SQLite TablerenameTable = "ALTER TABLE GEEK RENAME TO GFG"cursor_obj.execute(renameTable) # select from sqlite_mastercursor_obj.execute("SELECT * FROM sqlite_master") table = cursor_obj.fetchall() print("After changing the name of Table")print("The name of the table:", table[0][2]) connection_obj.commit() connection_obj.close()
Output:
sooda367
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module. "
},
{
"code": null,
"e": 212,
"s": 157,
"text": "We can do this by using ALTER statement. It allows to:"
},
{
"code": null,
"e": 248,
"s": 212,
"text": "Add one or more column to the table"
},
{
"code": null,
"e": 341,
"s": 248,
"text": "The syntax of ALTER TABLE to add a new column in an existing table in SQLite is given below:"
},
{
"code": null,
"e": 399,
"s": 341,
"text": "ALTER TABLE table_name ADD COLUMN column_name colume_type"
},
{
"code": null,
"e": 460,
"s": 399,
"text": "The column is added but will have all the values to be NULL."
},
{
"code": null,
"e": 479,
"s": 460,
"text": "To create a table:"
},
{
"code": null,
"e": 487,
"s": 479,
"text": "Python3"
},
{
"code": "import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Drop the GEEK table if already exists.cursor_obj.execute(\"DROP TABLE IF EXISTS GEEK\") # Creating tabletable = \"\"\" CREATE TABLE GEEK ( Email VARCHAR(255) NOT NULL, Name CHAR(25) NOT NULL, Score INT ); \"\"\" cursor_obj.execute(table) # Inserting data into geek tableconnection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek1\",25)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek2\",15)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek3\",36)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek4\",27)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek5\",40)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek6\",14)\"\"\")connection_obj.execute( \"\"\"INSERT INTO GEEK (Email,Name,Score) VALUES (\"[email protected]\",\"Geek7\",10)\"\"\") # Display tabledata = cursor_obj.execute(\"\"\"SELECT * FROM GEEK\"\"\")print('GEEK Table:')for row in data: print(row) connection_obj.commit() # Close the connectionconnection_obj.close()",
"e": 1867,
"s": 487,
"text": null
},
{
"code": null,
"e": 1875,
"s": 1867,
"text": "Output:"
},
{
"code": null,
"e": 1911,
"s": 1875,
"text": "Now we add a new column “UserName”:"
},
{
"code": null,
"e": 1919,
"s": 1911,
"text": "Python3"
},
{
"code": "import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Add a new column to geek tablenew_column = \"ALTER TABLE GEEK ADD COLUMN UserName CHAR(25)\" cursor_obj.execute(new_column) # Display tabledata = cursor_obj.execute(\"SELECT * FROM GEEK\")print('GEEK Table:')for row in data: print(row) connection_obj.commit() # Close the connectionconnection_obj.close()",
"e": 2358,
"s": 1919,
"text": null
},
{
"code": null,
"e": 2366,
"s": 2358,
"text": "Output:"
},
{
"code": null,
"e": 2450,
"s": 2366,
"text": "The syntax of ALTER TABLE to change the name of the table in SQLite is given below:"
},
{
"code": null,
"e": 2497,
"s": 2450,
"text": "ALTER TABLE table_name RENAME TO newTableName;"
},
{
"code": null,
"e": 2552,
"s": 2497,
"text": "We will use the same GEEK table that we created above:"
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "Python3"
},
{
"code": "import sqlite3 # Connecting to sqliteconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # select from sqlite_mastercursor_obj.execute(\"SELECT * FROM sqlite_master\") table = cursor_obj.fetchall()print(\"Before changing the name of Table\")print(\"The name of the table:\", table[0][2]) # Rename the SQLite TablerenameTable = \"ALTER TABLE GEEK RENAME TO GFG\"cursor_obj.execute(renameTable) # select from sqlite_mastercursor_obj.execute(\"SELECT * FROM sqlite_master\") table = cursor_obj.fetchall() print(\"After changing the name of Table\")print(\"The name of the table:\", table[0][2]) connection_obj.commit() connection_obj.close()",
"e": 3230,
"s": 2560,
"text": null
},
{
"code": null,
"e": 3238,
"s": 3230,
"text": "Output:"
},
{
"code": null,
"e": 3247,
"s": 3238,
"text": "sooda367"
},
{
"code": null,
"e": 3254,
"s": 3247,
"text": "Picked"
},
{
"code": null,
"e": 3268,
"s": 3254,
"text": "Python-SQLite"
},
{
"code": null,
"e": 3275,
"s": 3268,
"text": "Python"
}
] |
Lodash _.memoize() Method | 16 Sep, 2020
The _.memoize() method is used to memorize a given function by caching the result computed by the function. If resolver is issued, the cache key for store the result is determined based on the arguments given to the memoized method. By default, the first argument provided to the memoized function is used as the map cache key.
Syntax:
_.memoize(func, [resolver])
Parameters: This method accepts two parameters as mentioned above and described below:
func: This parameter holds the function to have its output memoized.
resolver: It is the function to resolve the cache key.
Return Value: This method returns the new memoized function.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.memoize() method var sum = _.memoize(function (n) { return n < 1 ? n : n + sum(n - 1); }); // Sum of first 6 natural number console.log(sum(6));
Output:
21
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); var object = { 'cpp': 5, 'java': 8 }; // Use of _.memoize() method var values = _.memoize(_.values); // value of object console.log(values(object)); // Modify the result cache.values.cache.set(object, ['html', 'css']);console.log(values(object));
Output:
[5, 8]
['html', 'css']
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Sep, 2020"
},
{
"code": null,
"e": 356,
"s": 28,
"text": "The _.memoize() method is used to memorize a given function by caching the result computed by the function. If resolver is issued, the cache key for store the result is determined based on the arguments given to the memoized method. By default, the first argument provided to the memoized function is used as the map cache key."
},
{
"code": null,
"e": 364,
"s": 356,
"text": "Syntax:"
},
{
"code": null,
"e": 393,
"s": 364,
"text": "_.memoize(func, [resolver])\n"
},
{
"code": null,
"e": 480,
"s": 393,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 549,
"s": 480,
"text": "func: This parameter holds the function to have its output memoized."
},
{
"code": null,
"e": 604,
"s": 549,
"text": "resolver: It is the function to resolve the cache key."
},
{
"code": null,
"e": 665,
"s": 604,
"text": "Return Value: This method returns the new memoized function."
},
{
"code": null,
"e": 759,
"s": 665,
"text": "Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. "
},
{
"code": null,
"e": 770,
"s": 759,
"text": "Example 1:"
},
{
"code": null,
"e": 781,
"s": 770,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.memoize() method var sum = _.memoize(function (n) { return n < 1 ? n : n + sum(n - 1); }); // Sum of first 6 natural number console.log(sum(6));",
"e": 1011,
"s": 781,
"text": null
},
{
"code": null,
"e": 1019,
"s": 1011,
"text": "Output:"
},
{
"code": null,
"e": 1023,
"s": 1019,
"text": "21\n"
},
{
"code": null,
"e": 1036,
"s": 1023,
"text": "Example 2: "
},
{
"code": null,
"e": 1047,
"s": 1036,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var object = { 'cpp': 5, 'java': 8 }; // Use of _.memoize() method var values = _.memoize(_.values); // value of object console.log(values(object)); // Modify the result cache.values.cache.set(object, ['html', 'css']);console.log(values(object));",
"e": 1364,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Output:"
},
{
"code": null,
"e": 1396,
"s": 1372,
"text": "[5, 8]\n['html', 'css']\n"
},
{
"code": null,
"e": 1498,
"s": 1396,
"text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 1516,
"s": 1498,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": "JavaScript"
},
{
"code": null,
"e": 1544,
"s": 1527,
"text": "Web Technologies"
}
] |
GATE | GATE CS 2010 | Question 65 | 28 Jun, 2021
If 137 + 276 = 435 how much is 731 + 672?(A) 534(B) 1403(C) 1623(D) 1513Answer: (C)Explanation: If we try adding the numbers directly (i.e. considering decimal)
1
137
+276
---
3
Since 7+6=13 and the given answer 435 has 5 in the one’s place therefore the numbers are in base 8; Because 13 will correspond to 15 (7+8) in base 8 system. As shown:
Now converting 731 and 672 in decimal
7×8^2 + 3×8^1 + 1×8^0 = 4736×8^2 + 7×8^1 + 2×8^0 = 442
Adding 473 + 442 = 915
Converting 915 into base 8 = 1623
This explanation has been contributed by Kriti Kushwaha.
More questions at: number-representation
Quiz of this Question
jayanth_mkv
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 215,
"s": 54,
"text": "If 137 + 276 = 435 how much is 731 + 672?(A) 534(B) 1403(C) 1623(D) 1513Answer: (C)Explanation: If we try adding the numbers directly (i.e. considering decimal)"
},
{
"code": null,
"e": 250,
"s": 215,
"text": " \n 1 \n 137\n +276 \n --- \n 3\n"
},
{
"code": null,
"e": 417,
"s": 250,
"text": "Since 7+6=13 and the given answer 435 has 5 in the one’s place therefore the numbers are in base 8; Because 13 will correspond to 15 (7+8) in base 8 system. As shown:"
},
{
"code": null,
"e": 455,
"s": 417,
"text": "Now converting 731 and 672 in decimal"
},
{
"code": null,
"e": 510,
"s": 455,
"text": "7×8^2 + 3×8^1 + 1×8^0 = 4736×8^2 + 7×8^1 + 2×8^0 = 442"
},
{
"code": null,
"e": 533,
"s": 510,
"text": "Adding 473 + 442 = 915"
},
{
"code": null,
"e": 567,
"s": 533,
"text": "Converting 915 into base 8 = 1623"
},
{
"code": null,
"e": 624,
"s": 567,
"text": "This explanation has been contributed by Kriti Kushwaha."
},
{
"code": null,
"e": 665,
"s": 624,
"text": "More questions at: number-representation"
},
{
"code": null,
"e": 687,
"s": 665,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 699,
"s": 687,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 712,
"s": 699,
"text": "GATE-CS-2010"
},
{
"code": null,
"e": 730,
"s": 712,
"text": "GATE-GATE CS 2010"
},
{
"code": null,
"e": 735,
"s": 730,
"text": "GATE"
}
] |
Reverse a Linked List in groups of given size | Set 2 | 24 Jun, 2022
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples:
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 5
Output: 5->4->3->2->1->8->7->6->NULL.
We have already discussed its solution in the below post Reverse a Linked List in groups of given size | Set 1In this post, we have used a stack that will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of the prev node to the top element of the stack. Repeat this process, until NULL is reached.This algorithm uses O(k) extra space.
C++
Java
Python3
C#
Javascript
// C++ program to reverse a linked list in groups// of given size#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */struct Node* Reverse(struct Node* head, int k){ // Create a stack of Node* stack<Node*> mystack; struct Node* current = head; struct Node* prev = NULL; while (current != NULL) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != NULL && count < k) { mystack.push(current); current = current->next; count++; } // Now pop the elements of stack one by one while (mystack.size() > 0) { // If final list has not been started yet. if (prev == NULL) { prev = mystack.top(); head = prev; mystack.pop(); } else { prev->next = mystack.top(); prev = prev->next; mystack.pop(); } } } // Next of last element will point to NULL. prev->next = NULL; return head;} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct Node* head = NULL; /* Created Linked list is 1->2->3->4->5->6->7->8->9 */ push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("\nGiven linked list \n"); printList(head); head = Reverse(head, 3); printf("\nReversed Linked list \n"); printList(head); return 0;}
// Java program to reverse a linked list in groups // of given size import java.util.*;class GfG { /* Link list node */static class Node { int data; Node next; }static Node head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) { // Create a stack of Node* Stack<Node> mystack = new Stack<Node> (); Node current = head; Node prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one by one while (mystack.size() > 0) { // If final list has not been started yet. if (prev == null) { prev = mystack.peek(); head = prev; mystack.pop(); } else { prev.next = mystack.peek(); prev = prev.next; mystack.pop(); } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS *//* Function to push a node */static void push( int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } /* Driver code*/public static void main(String[] args) { /* Start with the empty list */ //Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ push( 9); push( 8); push( 7); push( 6); push( 5); push(4); push(3); push(2); push( 1); System.out.println("Given linked list "); printList(head); head = Reverse(head, 3); System.out.println(); System.out.println("Reversed Linked list "); printList(head); } } // This code is contributed by Prerna Saini
# Python3 program to reverse a Linked List# in groups of given size # Node classclass Node(object): __slots__ = 'data', 'next' # Constructor to initialize the node object def __init__(self, data = None, next = None): self.data = data self.next = next def __repr__(self): return repr(self.data) class LinkedList(object): # Function to initialize head def __init__(self): self.head = None # Utility function to print nodes # of LinkedList def __repr__(self): nodes = [] curr = self.head while curr: nodes.append(repr(curr)) curr = curr.next return '[' + ', '.join(nodes) + ']' # Function to insert a new node at # the beginning def prepend(self, data): self.head = Node(data = data, next = self.head) # Reverses the linked list in groups of size k # and returns the pointer to the new head node. def reverse(self, k = 1): if self.head is None: return curr = self.head prev = None new_stack = [] while curr is not None: val = 0 # Terminate the loop whichever comes first # either current == None or value >= k while curr is not None and val < k: new_stack.append(curr.data) curr = curr.next val += 1 # Now pop the elements of stack one by one while new_stack: # If final list has not been started yet. if prev is None: prev = Node(new_stack.pop()) self.head = prev else: prev.next = Node(new_stack.pop()) prev = prev.next # Next of last element will point to None. prev.next = None return self.head # Driver Codellist = LinkedList() llist.prepend(9)llist.prepend(8)llist.prepend(7)llist.prepend(6)llist.prepend(5)llist.prepend(4)llist.prepend(3)llist.prepend(2)llist.prepend(1) print("Given linked list")print(llist)llist.head = llist.reverse(3) print("Reversed Linked list")print(llist) # This code is contributed by # Sagar Kumar Sinha(sagarsinha7777)
// C# program to reverse a linked list // in groups of given size using System;using System.Collections; class GfG { /* Link list node */public class Node { public int data; public Node next; } static Node head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) { // Create a stack of Node* Stack mystack = new Stack(); Node current = head; Node prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != null && count < k) { mystack.Push(current); current = current.next; count++; } // Now Pop the elements of stack one by one while (mystack.Count > 0) { // If final list has not been started yet. if (prev == null) { prev = (Node)mystack.Peek(); head = prev; mystack.Pop(); } else { prev.next = (Node)mystack.Peek(); prev = prev.next; mystack.Pop(); } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS *//* Function to Push a node */static void Push( int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } /* Driver code*/public static void Main(String []args) { /* Start with the empty list */ //Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ Push( 9); Push( 8); Push( 7); Push( 6); Push( 5); Push(4); Push(3); Push(2); Push( 1); Console.WriteLine("Given linked list "); printList(head); head = Reverse(head, 3); Console.WriteLine(); Console.WriteLine("Reversed Linked list "); printList(head); } } // This code is contributed by Arnab Kundu
<script>// javascript program to reverse a linked list in groups // of given size class GfG { /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }} var head = null; /* * Reverses the linked list in groups of size k and returns the pointer to the * new head node. */ function Reverse(head , k) { // Create a stack of Node* var mystack = [];var current = head;var prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k var count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one by one while (mystack.length > 0) { // If final list has not been started yet. if (prev == null) { prev = mystack.pop(); head = prev; } else { prev.next = mystack.pop(); prev = prev.next; } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS */ /* Function to push a node */ function push(new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } /* Driver code */ /* Start with the empty list */ // Node head = null; /* * Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ push(9); push(8); push(7); push(6); push(5); push(4); push(3); push(2); push(1); document.write("Given linked list <br/>"); printList(head); head = Reverse(head, 3); document.write("<br/>"); document.write("Reversed Linked list <br/>"); printList(head); // This code contributed by aashish1995 </script>
Output:
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list.
Auxiliary Space: O(k), as we are using extra space for the stack.
Reverse a Linked List in groups of given size | Set 2 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse a Linked List in groups of given size | Set 2 | 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 / 5:06•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aF9PGkR0dWU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
sagarsinha7777
prerna saini
andrew1234
nidhi_biet
aashish1995
arorakashish0911
rohan07
Accolite
Adobe
MakeMyTrip
Microsoft
Paytm
Snapdeal
VMWare
Linked List
Paytm
VMWare
Accolite
Microsoft
Snapdeal
MakeMyTrip
Adobe
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Remove duplicates from an unsorted linked list
Write a function to get the intersection point of two Linked Lists
Circular Linked List | Set 1 (Introduction and Applications)
Implement a stack using singly linked list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 167,
"s": 54,
"text": "Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: "
},
{
"code": null,
"e": 345,
"s": 167,
"text": "Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3 \nOutput: 3->2->1->6->5->4->8->7->NULL. \n\nInputs: 1->2->3->4->5->6->7->8->NULL and k = 5\nOutput: 5->4->3->2->1->8->7->6->NULL."
},
{
"code": null,
"e": 836,
"s": 347,
"text": "We have already discussed its solution in the below post Reverse a Linked List in groups of given size | Set 1In this post, we have used a stack that will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of the prev node to the top element of the stack. Repeat this process, until NULL is reached.This algorithm uses O(k) extra space. "
},
{
"code": null,
"e": 840,
"s": 836,
"text": "C++"
},
{
"code": null,
"e": 845,
"s": 840,
"text": "Java"
},
{
"code": null,
"e": 853,
"s": 845,
"text": "Python3"
},
{
"code": null,
"e": 856,
"s": 853,
"text": "C#"
},
{
"code": null,
"e": 867,
"s": 856,
"text": "Javascript"
},
{
"code": "// C++ program to reverse a linked list in groups// of given size#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */struct Node* Reverse(struct Node* head, int k){ // Create a stack of Node* stack<Node*> mystack; struct Node* current = head; struct Node* prev = NULL; while (current != NULL) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != NULL && count < k) { mystack.push(current); current = current->next; count++; } // Now pop the elements of stack one by one while (mystack.size() > 0) { // If final list has not been started yet. if (prev == NULL) { prev = mystack.top(); head = prev; mystack.pop(); } else { prev->next = mystack.top(); prev = prev->next; mystack.pop(); } } } // Next of last element will point to NULL. prev->next = NULL; return head;} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct Node* head = NULL; /* Created Linked list is 1->2->3->4->5->6->7->8->9 */ push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf(\"\\nGiven linked list \\n\"); printList(head); head = Reverse(head, 3); printf(\"\\nReversed Linked list \\n\"); printList(head); return 0;}",
"e": 3228,
"s": 867,
"text": null
},
{
"code": "// Java program to reverse a linked list in groups // of given size import java.util.*;class GfG { /* Link list node */static class Node { int data; Node next; }static Node head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) { // Create a stack of Node* Stack<Node> mystack = new Stack<Node> (); Node current = head; Node prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one by one while (mystack.size() > 0) { // If final list has not been started yet. if (prev == null) { prev = mystack.peek(); head = prev; mystack.pop(); } else { prev.next = mystack.peek(); prev = prev.next; mystack.pop(); } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS *//* Function to push a node */static void push( int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */static void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } /* Driver code*/public static void main(String[] args) { /* Start with the empty list */ //Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ push( 9); push( 8); push( 7); push( 6); push( 5); push(4); push(3); push(2); push( 1); System.out.println(\"Given linked list \"); printList(head); head = Reverse(head, 3); System.out.println(); System.out.println(\"Reversed Linked list \"); printList(head); } } // This code is contributed by Prerna Saini",
"e": 5652,
"s": 3228,
"text": null
},
{
"code": "# Python3 program to reverse a Linked List# in groups of given size # Node classclass Node(object): __slots__ = 'data', 'next' # Constructor to initialize the node object def __init__(self, data = None, next = None): self.data = data self.next = next def __repr__(self): return repr(self.data) class LinkedList(object): # Function to initialize head def __init__(self): self.head = None # Utility function to print nodes # of LinkedList def __repr__(self): nodes = [] curr = self.head while curr: nodes.append(repr(curr)) curr = curr.next return '[' + ', '.join(nodes) + ']' # Function to insert a new node at # the beginning def prepend(self, data): self.head = Node(data = data, next = self.head) # Reverses the linked list in groups of size k # and returns the pointer to the new head node. def reverse(self, k = 1): if self.head is None: return curr = self.head prev = None new_stack = [] while curr is not None: val = 0 # Terminate the loop whichever comes first # either current == None or value >= k while curr is not None and val < k: new_stack.append(curr.data) curr = curr.next val += 1 # Now pop the elements of stack one by one while new_stack: # If final list has not been started yet. if prev is None: prev = Node(new_stack.pop()) self.head = prev else: prev.next = Node(new_stack.pop()) prev = prev.next # Next of last element will point to None. prev.next = None return self.head # Driver Codellist = LinkedList() llist.prepend(9)llist.prepend(8)llist.prepend(7)llist.prepend(6)llist.prepend(5)llist.prepend(4)llist.prepend(3)llist.prepend(2)llist.prepend(1) print(\"Given linked list\")print(llist)llist.head = llist.reverse(3) print(\"Reversed Linked list\")print(llist) # This code is contributed by # Sagar Kumar Sinha(sagarsinha7777)",
"e": 7933,
"s": 5652,
"text": null
},
{
"code": "// C# program to reverse a linked list // in groups of given size using System;using System.Collections; class GfG { /* Link list node */public class Node { public int data; public Node next; } static Node head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */static Node Reverse(Node head, int k) { // Create a stack of Node* Stack mystack = new Stack(); Node current = head; Node prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k int count = 0; while (current != null && count < k) { mystack.Push(current); current = current.next; count++; } // Now Pop the elements of stack one by one while (mystack.Count > 0) { // If final list has not been started yet. if (prev == null) { prev = (Node)mystack.Peek(); head = prev; mystack.Pop(); } else { prev.next = (Node)mystack.Peek(); prev = prev.next; mystack.Pop(); } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS *//* Function to Push a node */static void Push( int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } /* Driver code*/public static void Main(String []args) { /* Start with the empty list */ //Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ Push( 9); Push( 8); Push( 7); Push( 6); Push( 5); Push(4); Push(3); Push(2); Push( 1); Console.WriteLine(\"Given linked list \"); printList(head); head = Reverse(head, 3); Console.WriteLine(); Console.WriteLine(\"Reversed Linked list \"); printList(head); } } // This code is contributed by Arnab Kundu",
"e": 10391,
"s": 7933,
"text": null
},
{
"code": "<script>// javascript program to reverse a linked list in groups // of given size class GfG { /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }} var head = null; /* * Reverses the linked list in groups of size k and returns the pointer to the * new head node. */ function Reverse(head , k) { // Create a stack of Node* var mystack = [];var current = head;var prev = null; while (current != null) { // Terminate the loop whichever comes first // either current == NULL or count >= k var count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one by one while (mystack.length > 0) { // If final list has not been started yet. if (prev == null) { prev = mystack.pop(); head = prev; } else { prev.next = mystack.pop(); prev = prev.next; } } } // Next of last element will point to NULL. prev.next = null; return head; } /* UTILITY FUNCTIONS */ /* Function to push a node */ function push(new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } /* Driver code */ /* Start with the empty list */ // Node head = null; /* * Created Linked list is 1->2->3-> 4->5->6->7->8->9 */ push(9); push(8); push(7); push(6); push(5); push(4); push(3); push(2); push(1); document.write(\"Given linked list <br/>\"); printList(head); head = Reverse(head, 3); document.write(\"<br/>\"); document.write(\"Reversed Linked list <br/>\"); printList(head); // This code contributed by aashish1995 </script>",
"e": 12905,
"s": 10391,
"text": null
},
{
"code": null,
"e": 12915,
"s": 12905,
"text": "Output: "
},
{
"code": null,
"e": 12984,
"s": 12915,
"text": "Given Linked List\n1 2 3 4 5 6 7 8 9 \nReversed list\n3 2 1 6 5 4 9 8 7"
},
{
"code": null,
"e": 13102,
"s": 12984,
"text": "Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list."
},
{
"code": null,
"e": 13169,
"s": 13102,
"text": "Auxiliary Space: O(k), as we are using extra space for the stack. "
},
{
"code": null,
"e": 14093,
"s": 13169,
"text": "Reverse a Linked List in groups of given size | Set 2 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse a Linked List in groups of given size | Set 2 | 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 / 5:06•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=aF9PGkR0dWU\" 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": 14516,
"s": 14093,
"text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 14531,
"s": 14516,
"text": "sagarsinha7777"
},
{
"code": null,
"e": 14544,
"s": 14531,
"text": "prerna saini"
},
{
"code": null,
"e": 14555,
"s": 14544,
"text": "andrew1234"
},
{
"code": null,
"e": 14566,
"s": 14555,
"text": "nidhi_biet"
},
{
"code": null,
"e": 14578,
"s": 14566,
"text": "aashish1995"
},
{
"code": null,
"e": 14595,
"s": 14578,
"text": "arorakashish0911"
},
{
"code": null,
"e": 14603,
"s": 14595,
"text": "rohan07"
},
{
"code": null,
"e": 14612,
"s": 14603,
"text": "Accolite"
},
{
"code": null,
"e": 14618,
"s": 14612,
"text": "Adobe"
},
{
"code": null,
"e": 14629,
"s": 14618,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 14639,
"s": 14629,
"text": "Microsoft"
},
{
"code": null,
"e": 14645,
"s": 14639,
"text": "Paytm"
},
{
"code": null,
"e": 14654,
"s": 14645,
"text": "Snapdeal"
},
{
"code": null,
"e": 14661,
"s": 14654,
"text": "VMWare"
},
{
"code": null,
"e": 14673,
"s": 14661,
"text": "Linked List"
},
{
"code": null,
"e": 14679,
"s": 14673,
"text": "Paytm"
},
{
"code": null,
"e": 14686,
"s": 14679,
"text": "VMWare"
},
{
"code": null,
"e": 14695,
"s": 14686,
"text": "Accolite"
},
{
"code": null,
"e": 14705,
"s": 14695,
"text": "Microsoft"
},
{
"code": null,
"e": 14714,
"s": 14705,
"text": "Snapdeal"
},
{
"code": null,
"e": 14725,
"s": 14714,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 14731,
"s": 14725,
"text": "Adobe"
},
{
"code": null,
"e": 14743,
"s": 14731,
"text": "Linked List"
},
{
"code": null,
"e": 14841,
"s": 14743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14873,
"s": 14841,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 14937,
"s": 14873,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 14984,
"s": 14937,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 15039,
"s": 14984,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 15074,
"s": 15039,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 15130,
"s": 15074,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 15177,
"s": 15130,
"text": "Remove duplicates from an unsorted linked list"
},
{
"code": null,
"e": 15244,
"s": 15177,
"text": "Write a function to get the intersection point of two Linked Lists"
},
{
"code": null,
"e": 15305,
"s": 15244,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
}
] |
How to create a session only cookies with JavaScript? | To create a session only cookie, you need to set the expiration date of the cookie to be some years ahead. You need to set the expire attribute −
current time + 5 years
The expire attribute shows the date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Note − Do not consider removing the expire value to create a session only cookie. This won’t work. Set the expire attribute to the future date. | [
{
"code": null,
"e": 1333,
"s": 1187,
"text": "To create a session only cookie, you need to set the expiration date of the cookie to be some years ahead. You need to set the expire attribute −"
},
{
"code": null,
"e": 1356,
"s": 1333,
"text": "current time + 5 years"
},
{
"code": null,
"e": 1493,
"s": 1356,
"text": "The expire attribute shows the date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 1637,
"s": 1493,
"text": "Note − Do not consider removing the expire value to create a session only cookie. This won’t work. Set the expire attribute to the future date."
}
] |
Variadic functions in C | 04 Jun, 2022
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(...) as the last parameter.
Syntax:
int function_name(data_type variable_name, ...);
Values of the passed arguments can be accessed through the header file named as:
#include <stdarg.h>
<stdarg.h> includes the following methods:
Methods
Description
Here, va_list holds the information needed by va_start, va_arg, va_end, and va_copy.
Program 1:
The following simple C program will demonstrate the working of the variadic function AddNumbers():
C
// C program for the above approach #include <stdarg.h>#include <stdio.h> // Variadic function to add numbersint AddNumbers(int n, ...){ int Sum = 0; // Declaring pointer to the // argument list va_list ptr; // Initializing argument to the // list pointer va_start(ptr, n); for (int i = 0; i < n; i++) // Accessing current variable // and pointing to next one Sum += va_arg(ptr, int); // Ending argument list traversal va_end(ptr); return Sum;} // Driver Codeint main(){ printf("\n\n Variadic functions: \n"); // Variable number of arguments printf("\n 1 + 2 = %d ", AddNumbers(2, 1, 2)); printf("\n 3 + 4 + 5 = %d ", AddNumbers(3, 3, 4, 5)); printf("\n 6 + 7 + 8 + 9 = %d ", AddNumbers(4, 6, 7, 8, 9)); printf("\n"); return 0;}
Variadic functions:
1 + 2 = 3
3 + 4 + 5 = 12
6 + 7 + 8 + 9 = 30
Program 2: Below is the C program consisting of the variadic function LargestNumber():
C
// C program for the above approach#include <stdarg.h>#include <stdio.h> // Variadic function to find the largest numberint LargestNumber(int n, ...){ int max = 0; // Declaring pointer to the // argument list va_list ptr; // Initializing argument to the // list pointer va_start(ptr, n); for (int i = 0; i < n; i++) { // Accessing current variable // and pointing to next int temp = va_arg(ptr, int); max = temp > max ? temp : max; } // End of argument list traversal va_end(ptr); return max;} // Driver Codeint main(){ printf("\n\n Variadic functions: \n"); // Variable number of arguments printf("\n %d ", LargestNumber(2, 1, 2)); printf("\n %d ", LargestNumber(3, 3, 4, 5)); printf("\n %d ", LargestNumber(4, 6, 7, 8, 9)); printf("\n"); return 0;}
Variadic functions:
2
5
9
anikakapoor
sagartomar9927
tauleshwar
C Basics
C-Functions
Functions
C++
C++ Programs
Functions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jun, 2022"
},
{
"code": null,
"e": 389,
"s": 52,
"text": "Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(...) as the last parameter."
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Syntax:"
},
{
"code": null,
"e": 446,
"s": 397,
"text": "int function_name(data_type variable_name, ...);"
},
{
"code": null,
"e": 527,
"s": 446,
"text": "Values of the passed arguments can be accessed through the header file named as:"
},
{
"code": null,
"e": 547,
"s": 527,
"text": "#include <stdarg.h>"
},
{
"code": null,
"e": 590,
"s": 547,
"text": "<stdarg.h> includes the following methods:"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Methods"
},
{
"code": null,
"e": 610,
"s": 598,
"text": "Description"
},
{
"code": null,
"e": 695,
"s": 610,
"text": "Here, va_list holds the information needed by va_start, va_arg, va_end, and va_copy."
},
{
"code": null,
"e": 706,
"s": 695,
"text": "Program 1:"
},
{
"code": null,
"e": 805,
"s": 706,
"text": "The following simple C program will demonstrate the working of the variadic function AddNumbers():"
},
{
"code": null,
"e": 807,
"s": 805,
"text": "C"
},
{
"code": "// C program for the above approach #include <stdarg.h>#include <stdio.h> // Variadic function to add numbersint AddNumbers(int n, ...){ int Sum = 0; // Declaring pointer to the // argument list va_list ptr; // Initializing argument to the // list pointer va_start(ptr, n); for (int i = 0; i < n; i++) // Accessing current variable // and pointing to next one Sum += va_arg(ptr, int); // Ending argument list traversal va_end(ptr); return Sum;} // Driver Codeint main(){ printf(\"\\n\\n Variadic functions: \\n\"); // Variable number of arguments printf(\"\\n 1 + 2 = %d \", AddNumbers(2, 1, 2)); printf(\"\\n 3 + 4 + 5 = %d \", AddNumbers(3, 3, 4, 5)); printf(\"\\n 6 + 7 + 8 + 9 = %d \", AddNumbers(4, 6, 7, 8, 9)); printf(\"\\n\"); return 0;}",
"e": 1652,
"s": 807,
"text": null
},
{
"code": null,
"e": 1723,
"s": 1652,
"text": "Variadic functions: \n\n 1 + 2 = 3 \n 3 + 4 + 5 = 12 \n 6 + 7 + 8 + 9 = 30"
},
{
"code": null,
"e": 1812,
"s": 1725,
"text": "Program 2: Below is the C program consisting of the variadic function LargestNumber():"
},
{
"code": null,
"e": 1814,
"s": 1812,
"text": "C"
},
{
"code": "// C program for the above approach#include <stdarg.h>#include <stdio.h> // Variadic function to find the largest numberint LargestNumber(int n, ...){ int max = 0; // Declaring pointer to the // argument list va_list ptr; // Initializing argument to the // list pointer va_start(ptr, n); for (int i = 0; i < n; i++) { // Accessing current variable // and pointing to next int temp = va_arg(ptr, int); max = temp > max ? temp : max; } // End of argument list traversal va_end(ptr); return max;} // Driver Codeint main(){ printf(\"\\n\\n Variadic functions: \\n\"); // Variable number of arguments printf(\"\\n %d \", LargestNumber(2, 1, 2)); printf(\"\\n %d \", LargestNumber(3, 3, 4, 5)); printf(\"\\n %d \", LargestNumber(4, 6, 7, 8, 9)); printf(\"\\n\"); return 0;}",
"e": 2691,
"s": 1814,
"text": null
},
{
"code": null,
"e": 2724,
"s": 2691,
"text": "Variadic functions: \n\n 2 \n 5 \n 9"
},
{
"code": null,
"e": 2738,
"s": 2726,
"text": "anikakapoor"
},
{
"code": null,
"e": 2753,
"s": 2738,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2764,
"s": 2753,
"text": "tauleshwar"
},
{
"code": null,
"e": 2773,
"s": 2764,
"text": "C Basics"
},
{
"code": null,
"e": 2785,
"s": 2773,
"text": "C-Functions"
},
{
"code": null,
"e": 2795,
"s": 2785,
"text": "Functions"
},
{
"code": null,
"e": 2799,
"s": 2795,
"text": "C++"
},
{
"code": null,
"e": 2812,
"s": 2799,
"text": "C++ Programs"
},
{
"code": null,
"e": 2822,
"s": 2812,
"text": "Functions"
},
{
"code": null,
"e": 2826,
"s": 2822,
"text": "CPP"
},
{
"code": null,
"e": 2924,
"s": 2826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2948,
"s": 2924,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2968,
"s": 2948,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3001,
"s": 2968,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3026,
"s": 3001,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3070,
"s": 3026,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3105,
"s": 3070,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 3139,
"s": 3105,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 3183,
"s": 3139,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 3242,
"s": 3183,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Merge odd and even positioned nodes of two Linked Lists alternately | 19 Jan, 2022
Given two linked lists L1 and L2, the task is to print a new list obtained by merging odd position nodes of L1 with the even positioned nodes of L2 alternately.
Examples:
Input: L1 = 8->5->3->2->10->NULL, L2 = 11->13->1->6->9->NULLOutput: 8->13->3->6->10->NULL Explanation:The odd positioned nodes of L1 are {8, 3, 10} and the even positioned nodes L2 are {13, 6}. Merging them alternately generates the linked list 8->13->3->6->10->NULL
Input: L1 = 1->5->10->12->13->19->6->NULL, L2 = 2->7->9->NULL Output: 1->7->10->13->6->NULLExplanation:The odd positioned nodes of L1 are {1, 10, 13, 6} and the even positioned node of L2 is {7}.Merging them alternately generates the linked list 1->7->10->13->6->NULL
Approach: Follow the steps below to solve the problem:
Start traversing from the first node of L1 and for the second node of L2 simultaneously.
Add the first node of L1 to the resultant list and connect it with the second node of L2 and move to the next odd node in L1. Similarly, add connect the second node of L2 to the current odd node of L1 and move to the next even node in L2.
Repeat the above step until the end of one of the lists is reached.
Traverse the other list and keep adding the required nodes from that list to the resultant list.
Finally, print the resultant list.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a Nodeclass node {public: int data; node* next; node(int d) { data = d; next = NULL; }}; // Function to insert the node// at the head of the linkedlistvoid insert_at_head(node*& head, int data){ node* n = new node(data); n->next = head; head = n; return;} // Function to print the linked listvoid print(node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl; return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelynode* merge_alternate(node* head1, node* head2){ // Traverse from the second // node of second linked list if (head2) head2 = head2->next; // Stores the head of // the resultant list node* head3 = NULL; // Stores the current node node* cur = NULL; // Store the first node of // first list in the result if (head1) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != NULL && head2 != NULL) { // If there is a previous node then // connect that with the current node if (cur) cur->next = head1; // Update the current node cur = head1; // If next odd node exists if (head1->next != NULL) // Store the next odd node head1 = head1->next->next; // Otherwise else // Reach end of list head1 = NULL; // Connect the first node // with the second node cur->next = head2; // Update the current node cur = head2; // If next even node exists if (head2->next != NULL) // Store the next even node head2 = head2->next->next; // Otherwise else // Reach the end of the list head2 = NULL; } // If end of the second // list has been reached while (head1 != NULL) { // Connect with the // previous node if (cur) cur->next = head1; // Update the current node cur = head1; // If next odd node exists if (head1->next != NULL) // Store the next odd node head1 = head1->next->next; // Otherwise else // Reach end of list head1 = NULL; } // If end of second list // has been reached while (head2 != NULL) { // Connect with the // previous node if (cur) cur->next = head2; // Update the current node cur = head2; // If next even node exists if (head2->next != NULL) // Store the next odd node head2 = head2->next->next; // Otherwise else // Reach end of list head2 = NULL; } // End of the resultant list if (cur) cur->next = NULL; // Returning the head of // the resultant node return head3;} // Driver Codeint main(){ node *head1 = NULL, *head2 = NULL; // Create linked list insert_at_head(head1, 6); insert_at_head(head1, 19); insert_at_head(head1, 13); insert_at_head(head1, 12); insert_at_head(head1, 10); insert_at_head(head1, 5); insert_at_head(head1, 1); insert_at_head(head2, 9); insert_at_head(head2, 7); insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of a Nodestatic class node{ public int data; node next; node(int d) { data = d; next = null; }}; // Function to insert the node// at the head of the linkedliststatic node insert_at_head(node head, int data){ node n = new node(data); n.next = head; head = n; return head;} // Function to print the linked liststatic void print(node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; } System.out.println(); return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelystatic node merge_alternate(node head1, node head2){ // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list node head3 = null; // Stores the current node node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous node then // connect that with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3;} // Driver Codepublic static void main(String[] args){ node head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}} // This code is contributed by gauravrajput1
# Python3 program to implement# the above approach # Structure of a Nodeclass node: def __init__(self, d): self.data = d; self.next = None; # Function to insert the node# at the head of the linkedlistdef insert_at_head(head, data): n = node(data); n.next = head; head = n; return head; # Function to print the linked listdef printx(head): while (head != None): print(head.data, end = ' ') head = head.next; print() return; # Function to merge the odd and# even positioned nodes of two# given linked lists alternatelydef merge_alternate(head1, head2): # Traverse from the second # node of second linked list if (head2): head2 = head2.next; # Stores the head of # the resultant list head3 = None; # Stores the current node cur = None; # Store the first node of # first list in the result if (head1): head3 = head1; # Otherwise else: head3 = head2; # Traverse until end of a # one of the list is reached while (head1 != None and head2 != None): # If there is a previous node then # connect that with the current node if (cur): cur.next = head1; # Update the current node cur = head1; # If next odd node exists if (head1.next != None): # Store the next odd node head1 = head1.next.next; # Otherwise else: # Reach end of list head1 = None; # Connect the first node # with the second node cur.next = head2; # Update the current node cur = head2; # If next even node exists if (head2.next != None): # Store the next even node head2 = head2.next.next; # Otherwise else: # Reach the end of the list head2 = None; # If end of the second # list has been reached while (head1 != None): # Connect with the # previous node if (cur): cur.next = head1; # Update the current node cur = head1; # If next odd node exists if (head1.next != None): # Store the next odd node head1 = head1.next.next; # Otherwise else: # Reach end of list head1 = None; # If end of second list # has been reached while (head2 != None): # Connect with the # previous node if (cur): cur.next = head2; # Update the current node cur = head2; # If next even node exists if (head2.next != None): # Store the next odd node head2 = head2.next.next; # Otherwise else: # Reach end of list head2 = None; # End of the resultant list if (cur): cur.next = None; # Returning the head of # the resultant node return head3; # Driver Codeif __name__=='__main__': head1 = None head2 = None; # Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2) # Merging the linked lists head1 = merge_alternate(head1, head2); printx(head1); # This code is contributed by rutvik_56
// C# program to implement// the above approachusing System;class GFG{ // Structure of a Nodeclass node{ public int data; public node next; public node(int d) { data = d; next = null; }}; // Function to insert the node// at the head of the linkedliststatic node insert_at_head(node head, int data){ node n = new node(data); n.next = head; head = n; return head;} // Function to print the linked liststatic void print(node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine(); return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelystatic node merge_alternate(node head1, node head2){ // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list node head3 = null; // Stores the current node node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous // node then connect that // with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3;} // Driver Codepublic static void Main(String[] args){ node head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}} // This code is contributed by Princi Singh
<script>// javascript program to implement// the above approach // Structure of a Node class node { constructor(d) { this.data = d; this.next = null; } } // Function to insert the node // at the head of the linkedlist function insert_at_head( head , data) { n = new node(data); n.next = head; head = n; return head; } // Function to print the linked list function print( head) { while (head != null) { document.write(head.data + " "); head = head.next; } document.write(); return; } // Function to merge the odd and // even positioned nodes of two // given linked lists alternately function merge_alternate( head1, head2) { // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list head3 = null; // Stores the current node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous node then // connect that with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3; } // Driver Code head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1); // This code is contributed by umadevi9616</script>
1 7 10 13 6
Time Complexity: O(N)Auxiliary Space: O(1)
GauravRajput1
princi singh
rutvik_56
umadevi9616
arorakashish0911
Data Structures
Linked List
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
What is Data Structure: Types, Classifications and Applications
TCS NQT Coding Sheet
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "Given two linked lists L1 and L2, the task is to print a new list obtained by merging odd position nodes of L1 with the even positioned nodes of L2 alternately."
},
{
"code": null,
"e": 199,
"s": 189,
"text": "Examples:"
},
{
"code": null,
"e": 467,
"s": 199,
"text": "Input: L1 = 8->5->3->2->10->NULL, L2 = 11->13->1->6->9->NULLOutput: 8->13->3->6->10->NULL Explanation:The odd positioned nodes of L1 are {8, 3, 10} and the even positioned nodes L2 are {13, 6}. Merging them alternately generates the linked list 8->13->3->6->10->NULL"
},
{
"code": null,
"e": 736,
"s": 467,
"text": "Input: L1 = 1->5->10->12->13->19->6->NULL, L2 = 2->7->9->NULL Output: 1->7->10->13->6->NULLExplanation:The odd positioned nodes of L1 are {1, 10, 13, 6} and the even positioned node of L2 is {7}.Merging them alternately generates the linked list 1->7->10->13->6->NULL"
},
{
"code": null,
"e": 792,
"s": 736,
"text": " Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 881,
"s": 792,
"text": "Start traversing from the first node of L1 and for the second node of L2 simultaneously."
},
{
"code": null,
"e": 1120,
"s": 881,
"text": "Add the first node of L1 to the resultant list and connect it with the second node of L2 and move to the next odd node in L1. Similarly, add connect the second node of L2 to the current odd node of L1 and move to the next even node in L2."
},
{
"code": null,
"e": 1188,
"s": 1120,
"text": "Repeat the above step until the end of one of the lists is reached."
},
{
"code": null,
"e": 1285,
"s": 1188,
"text": "Traverse the other list and keep adding the required nodes from that list to the resultant list."
},
{
"code": null,
"e": 1320,
"s": 1285,
"text": "Finally, print the resultant list."
},
{
"code": null,
"e": 1372,
"s": 1320,
"text": " Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1376,
"s": 1372,
"text": "C++"
},
{
"code": null,
"e": 1381,
"s": 1376,
"text": "Java"
},
{
"code": null,
"e": 1389,
"s": 1381,
"text": "Python3"
},
{
"code": null,
"e": 1392,
"s": 1389,
"text": "C#"
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of a Nodeclass node {public: int data; node* next; node(int d) { data = d; next = NULL; }}; // Function to insert the node// at the head of the linkedlistvoid insert_at_head(node*& head, int data){ node* n = new node(data); n->next = head; head = n; return;} // Function to print the linked listvoid print(node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl; return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelynode* merge_alternate(node* head1, node* head2){ // Traverse from the second // node of second linked list if (head2) head2 = head2->next; // Stores the head of // the resultant list node* head3 = NULL; // Stores the current node node* cur = NULL; // Store the first node of // first list in the result if (head1) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != NULL && head2 != NULL) { // If there is a previous node then // connect that with the current node if (cur) cur->next = head1; // Update the current node cur = head1; // If next odd node exists if (head1->next != NULL) // Store the next odd node head1 = head1->next->next; // Otherwise else // Reach end of list head1 = NULL; // Connect the first node // with the second node cur->next = head2; // Update the current node cur = head2; // If next even node exists if (head2->next != NULL) // Store the next even node head2 = head2->next->next; // Otherwise else // Reach the end of the list head2 = NULL; } // If end of the second // list has been reached while (head1 != NULL) { // Connect with the // previous node if (cur) cur->next = head1; // Update the current node cur = head1; // If next odd node exists if (head1->next != NULL) // Store the next odd node head1 = head1->next->next; // Otherwise else // Reach end of list head1 = NULL; } // If end of second list // has been reached while (head2 != NULL) { // Connect with the // previous node if (cur) cur->next = head2; // Update the current node cur = head2; // If next even node exists if (head2->next != NULL) // Store the next odd node head2 = head2->next->next; // Otherwise else // Reach end of list head2 = NULL; } // End of the resultant list if (cur) cur->next = NULL; // Returning the head of // the resultant node return head3;} // Driver Codeint main(){ node *head1 = NULL, *head2 = NULL; // Create linked list insert_at_head(head1, 6); insert_at_head(head1, 19); insert_at_head(head1, 13); insert_at_head(head1, 12); insert_at_head(head1, 10); insert_at_head(head1, 5); insert_at_head(head1, 1); insert_at_head(head2, 9); insert_at_head(head2, 7); insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}",
"e": 5010,
"s": 1403,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of a Nodestatic class node{ public int data; node next; node(int d) { data = d; next = null; }}; // Function to insert the node// at the head of the linkedliststatic node insert_at_head(node head, int data){ node n = new node(data); n.next = head; head = n; return head;} // Function to print the linked liststatic void print(node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; } System.out.println(); return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelystatic node merge_alternate(node head1, node head2){ // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list node head3 = null; // Stores the current node node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous node then // connect that with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3;} // Driver Codepublic static void main(String[] args){ node head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}} // This code is contributed by gauravrajput1",
"e": 8468,
"s": 5010,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Structure of a Nodeclass node: def __init__(self, d): self.data = d; self.next = None; # Function to insert the node# at the head of the linkedlistdef insert_at_head(head, data): n = node(data); n.next = head; head = n; return head; # Function to print the linked listdef printx(head): while (head != None): print(head.data, end = ' ') head = head.next; print() return; # Function to merge the odd and# even positioned nodes of two# given linked lists alternatelydef merge_alternate(head1, head2): # Traverse from the second # node of second linked list if (head2): head2 = head2.next; # Stores the head of # the resultant list head3 = None; # Stores the current node cur = None; # Store the first node of # first list in the result if (head1): head3 = head1; # Otherwise else: head3 = head2; # Traverse until end of a # one of the list is reached while (head1 != None and head2 != None): # If there is a previous node then # connect that with the current node if (cur): cur.next = head1; # Update the current node cur = head1; # If next odd node exists if (head1.next != None): # Store the next odd node head1 = head1.next.next; # Otherwise else: # Reach end of list head1 = None; # Connect the first node # with the second node cur.next = head2; # Update the current node cur = head2; # If next even node exists if (head2.next != None): # Store the next even node head2 = head2.next.next; # Otherwise else: # Reach the end of the list head2 = None; # If end of the second # list has been reached while (head1 != None): # Connect with the # previous node if (cur): cur.next = head1; # Update the current node cur = head1; # If next odd node exists if (head1.next != None): # Store the next odd node head1 = head1.next.next; # Otherwise else: # Reach end of list head1 = None; # If end of second list # has been reached while (head2 != None): # Connect with the # previous node if (cur): cur.next = head2; # Update the current node cur = head2; # If next even node exists if (head2.next != None): # Store the next odd node head2 = head2.next.next; # Otherwise else: # Reach end of list head2 = None; # End of the resultant list if (cur): cur.next = None; # Returning the head of # the resultant node return head3; # Driver Codeif __name__=='__main__': head1 = None head2 = None; # Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2) # Merging the linked lists head1 = merge_alternate(head1, head2); printx(head1); # This code is contributed by rutvik_56",
"e": 12075,
"s": 8468,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Structure of a Nodeclass node{ public int data; public node next; public node(int d) { data = d; next = null; }}; // Function to insert the node// at the head of the linkedliststatic node insert_at_head(node head, int data){ node n = new node(data); n.next = head; head = n; return head;} // Function to print the linked liststatic void print(node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine(); return;} // Function to merge the odd and// even positioned nodes of two// given linked lists alternatelystatic node merge_alternate(node head1, node head2){ // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list node head3 = null; // Stores the current node node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous // node then connect that // with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3;} // Driver Codepublic static void Main(String[] args){ node head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1);}} // This code is contributed by Princi Singh",
"e": 15544,
"s": 12075,
"text": null
},
{
"code": "<script>// javascript program to implement// the above approach // Structure of a Node class node { constructor(d) { this.data = d; this.next = null; } } // Function to insert the node // at the head of the linkedlist function insert_at_head( head , data) { n = new node(data); n.next = head; head = n; return head; } // Function to print the linked list function print( head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } document.write(); return; } // Function to merge the odd and // even positioned nodes of two // given linked lists alternately function merge_alternate( head1, head2) { // Traverse from the second // node of second linked list if (head2 != null) head2 = head2.next; // Stores the head of // the resultant list head3 = null; // Stores the current node cur = null; // Store the first node of // first list in the result if (head1 != null) head3 = head1; // Otherwise else head3 = head2; // Traverse until end of a // one of the list is reached while (head1 != null && head2 != null) { // If there is a previous node then // connect that with the current node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; // Connect the first node // with the second node cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next even node head2 = head2.next.next; // Otherwise else // Reach the end of the list head2 = null; } // If end of the second // list has been reached while (head1 != null) { // Connect with the // previous node if (cur != null) cur.next = head1; // Update the current node cur = head1; // If next odd node exists if (head1.next != null) // Store the next odd node head1 = head1.next.next; // Otherwise else // Reach end of list head1 = null; } // If end of second list // has been reached while (head2 != null) { // Connect with the // previous node if (cur != null) cur.next = head2; // Update the current node cur = head2; // If next even node exists if (head2.next != null) // Store the next odd node head2 = head2.next.next; // Otherwise else // Reach end of list head2 = null; } // End of the resultant list if (cur != null) cur.next = null; // Returning the head of // the resultant node return head3; } // Driver Code head1 = null, head2 = null; // Create linked list head1 = insert_at_head(head1, 6); head1 = insert_at_head(head1, 19); head1 = insert_at_head(head1, 13); head1 = insert_at_head(head1, 12); head1 = insert_at_head(head1, 10); head1 = insert_at_head(head1, 5); head1 = insert_at_head(head1, 1); head2 = insert_at_head(head2, 9); head2 = insert_at_head(head2, 7); head2 = insert_at_head(head2, 2); // Merging the linked lists head1 = merge_alternate(head1, head2); print(head1); // This code is contributed by umadevi9616</script>",
"e": 19766,
"s": 15544,
"text": null
},
{
"code": null,
"e": 19778,
"s": 19766,
"text": "1 7 10 13 6"
},
{
"code": null,
"e": 19823,
"s": 19780,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 19837,
"s": 19823,
"text": "GauravRajput1"
},
{
"code": null,
"e": 19850,
"s": 19837,
"text": "princi singh"
},
{
"code": null,
"e": 19860,
"s": 19850,
"text": "rutvik_56"
},
{
"code": null,
"e": 19872,
"s": 19860,
"text": "umadevi9616"
},
{
"code": null,
"e": 19889,
"s": 19872,
"text": "arorakashish0911"
},
{
"code": null,
"e": 19905,
"s": 19889,
"text": "Data Structures"
},
{
"code": null,
"e": 19917,
"s": 19905,
"text": "Linked List"
},
{
"code": null,
"e": 19933,
"s": 19917,
"text": "Data Structures"
},
{
"code": null,
"e": 19945,
"s": 19933,
"text": "Linked List"
},
{
"code": null,
"e": 20043,
"s": 19945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20075,
"s": 20043,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 20113,
"s": 20075,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 20181,
"s": 20113,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 20245,
"s": 20181,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 20266,
"s": 20245,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 20301,
"s": 20266,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 20340,
"s": 20301,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 20362,
"s": 20340,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 20410,
"s": 20362,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
How to create custom banner background using CSS ? | 11 Jun, 2020
In modern web designs, the custom background has emerged as a popular design for the banner background. A custom background has an infinite number of designs. The design is purely based on one’s imagination and creativity. Some common examples of custom backgrounds include wavy background, skewed background, etc.
This article will show the approach used to create the Sawblade background as it’s bottom resembles that of a saw. It is also known as zig-zag pattern.
Approach: The approach is to first create a chain of small triangles at the bottom and then rotate them along the X-axis so that they form the blade-like appearance.
HTML Code: In the HTML section, the <div> element is created which will be used to hold the pattern.
HTML
<html lang="en"><head> <title> Custom background </title></head><body> <div class="geeks"> </div></body></html>
CSS Code: The CSS can be defined using the following steps:
Step 1: Provide a basic background color to the body.
Step 2: Align the created div to the center with a different background color of choice.
Step 3: Using the before selector, create a small chain of triangles by using the linear-gradient property with same degree but keeping one of them as negative.
Step 4: Use the rotate() function to rotate the triangles on the X-axis.
CSS
<style> body { background: green; } .geeks { position: absolute; top: 50%; width: 100%; height: 50%; background: white; } .geeks::before { content: ""; position: absolute; width: 100%; height: 15px; display: block; background: linear-gradient( -45deg, transparent, 33.33%, green 33.33%, green 66.66%, transparent 66.66%), linear-gradient(45deg, transparent, 33.33%,green 33.33%, green 66.66%, transparent 66.66%); background-size: 30px 60px; transform: rotateX(180deg); }</style>
Complete Code: In this section, we will combine the above two sections to make the custom banner background using HTML and CSS.
HTML
<html lang="en"> <head> <title> Custom background </title> <style> body { background: green; } .geeks { position: absolute; top: 50%; width: 100%; height: 50%; background: white; } .geeks::before { content: ""; position: absolute; width: 100%; height: 15px; display: block; background: linear-gradient( -45deg, transparent, 33.33%, green 33.33%, green 66.66%, transparent 66.66%), linear-gradient(45deg, transparent, 33.33%,green 33.33%, green 66.66%, transparent 66.66%); background-size: 30px 60px; transform: rotateX(180deg); } </style></head> <body> <div class="geeks"> </div></body> </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 343,
"s": 28,
"text": "In modern web designs, the custom background has emerged as a popular design for the banner background. A custom background has an infinite number of designs. The design is purely based on one’s imagination and creativity. Some common examples of custom backgrounds include wavy background, skewed background, etc."
},
{
"code": null,
"e": 495,
"s": 343,
"text": "This article will show the approach used to create the Sawblade background as it’s bottom resembles that of a saw. It is also known as zig-zag pattern."
},
{
"code": null,
"e": 661,
"s": 495,
"text": "Approach: The approach is to first create a chain of small triangles at the bottom and then rotate them along the X-axis so that they form the blade-like appearance."
},
{
"code": null,
"e": 763,
"s": 661,
"text": "HTML Code: In the HTML section, the <div> element is created which will be used to hold the pattern. "
},
{
"code": null,
"e": 768,
"s": 763,
"text": "HTML"
},
{
"code": "<html lang=\"en\"><head> <title> Custom background </title></head><body> <div class=\"geeks\"> </div></body></html>",
"e": 887,
"s": 768,
"text": null
},
{
"code": null,
"e": 947,
"s": 887,
"text": "CSS Code: The CSS can be defined using the following steps:"
},
{
"code": null,
"e": 1001,
"s": 947,
"text": "Step 1: Provide a basic background color to the body."
},
{
"code": null,
"e": 1090,
"s": 1001,
"text": "Step 2: Align the created div to the center with a different background color of choice."
},
{
"code": null,
"e": 1251,
"s": 1090,
"text": "Step 3: Using the before selector, create a small chain of triangles by using the linear-gradient property with same degree but keeping one of them as negative."
},
{
"code": null,
"e": 1324,
"s": 1251,
"text": "Step 4: Use the rotate() function to rotate the triangles on the X-axis."
},
{
"code": null,
"e": 1328,
"s": 1324,
"text": "CSS"
},
{
"code": "<style> body { background: green; } .geeks { position: absolute; top: 50%; width: 100%; height: 50%; background: white; } .geeks::before { content: \"\"; position: absolute; width: 100%; height: 15px; display: block; background: linear-gradient( -45deg, transparent, 33.33%, green 33.33%, green 66.66%, transparent 66.66%), linear-gradient(45deg, transparent, 33.33%,green 33.33%, green 66.66%, transparent 66.66%); background-size: 30px 60px; transform: rotateX(180deg); }</style>",
"e": 1997,
"s": 1328,
"text": null
},
{
"code": null,
"e": 2125,
"s": 1997,
"text": "Complete Code: In this section, we will combine the above two sections to make the custom banner background using HTML and CSS."
},
{
"code": null,
"e": 2130,
"s": 2125,
"text": "HTML"
},
{
"code": "<html lang=\"en\"> <head> <title> Custom background </title> <style> body { background: green; } .geeks { position: absolute; top: 50%; width: 100%; height: 50%; background: white; } .geeks::before { content: \"\"; position: absolute; width: 100%; height: 15px; display: block; background: linear-gradient( -45deg, transparent, 33.33%, green 33.33%, green 66.66%, transparent 66.66%), linear-gradient(45deg, transparent, 33.33%,green 33.33%, green 66.66%, transparent 66.66%); background-size: 30px 60px; transform: rotateX(180deg); } </style></head> <body> <div class=\"geeks\"> </div></body> </html>",
"e": 3045,
"s": 2130,
"text": null
},
{
"code": null,
"e": 3054,
"s": 3045,
"text": "Output: "
},
{
"code": null,
"e": 3063,
"s": 3054,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3073,
"s": 3063,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3077,
"s": 3073,
"text": "CSS"
},
{
"code": null,
"e": 3082,
"s": 3077,
"text": "HTML"
},
{
"code": null,
"e": 3099,
"s": 3082,
"text": "Web Technologies"
},
{
"code": null,
"e": 3126,
"s": 3099,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3131,
"s": 3126,
"text": "HTML"
}
] |
Sorting objects of user defined class in Python | 29 Dec, 2020
The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced version of sorting elements but instead of a list we are dealing with objects of a class.
Here sorted() method will be used.
Syntax:
sorted (iterable, key(optional), reverse(optional) )
Example: This is just a generic example to show how this method is employed
Python3
print(sorted([1,26,3,9])) print(sorted("Geeks foR gEEks".split(), key=str.lower))
Output:
[1, 3, 9, 26]
['foR', 'Geeks', 'gEEks']
Method 1:
In order to sort objects of a user-defined class, a key needs to be set for the sorted method, such that the key will be an indicator of how the objects should be sorted. With reference to the examples given below, here a function has been provided to the key which one by one compares the specified variable value for each object and returns a sorted list of objects for a class.
Example 1: Sorting elements in ascending order of the integer value given to them
Python3
class GFG: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG("geeks", 1), GFG("computer", 3), GFG("for", 2), GFG("geeks", 4), GFG("science", 3)] # sorting objects on the basis of value # stored at variable bprint(sorted(gfg, key=lambda x: x.b))
Output:
[(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]
Example 2: Sorting objects on the basis of the string value a variable holds
Python3
class GFG: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG("geeks", 1), GFG("computer", 3), GFG("for", 2), GFG("geeks", 4), GFG("science", 3)] # sorting objects on the basis of value # stored at variable aprint(sorted(gfg, key=lambda x: x.a.lower()))
Output:
[(‘computer’, 3), (‘for’, 2), (‘geeks’, 1), (‘geeks’, 4), (‘science’, 3)]
Method 2:
This method depicts how objects of a user-defined class can be sorted using functools inbuilt method total_ordering as a decorator to the class. Here, the class is defined normally as done in the above examples, only difference being during sorting, total_ordering() decorator is used. Two requirements for using total_ordering() are-
Out of less than(__lt__), greater than(__gt__), less than equal to(__le__) and greater than equal to(__ge__), atleast one should be defined in the class being decorated using this method.
Equal to (__eq__) should be defined.
In the example given below less than and greater than, both are defined even though during processing only one is called(in this less than) since one is enough to decide the order of the elements but it is good programming practice to define all in case one thing fails. During sorting one of the comparison methods are called to compare objects on the basis of some element and the sorted result is returned.
Example:
Python3
import functoolsfrom functools import total_ordering @total_orderingclass GFG: print("inside class") def __init__(self, a, b): self.a = a self.b = b def __lt__(self, obj): return ((self.b) < (obj.b)) def __gt__(self, obj): return ((self.b) > (obj.b)) def __le__(self, obj): return ((self.b) <= (obj.b)) def __ge__(self, obj): return ((self.b) >= (obj.b)) def __eq__(self, obj): return (self.b == obj.b) def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG("geeks", 1), GFG("computer", 3), GFG("for", 2), GFG("geeks", 4), GFG("science", 3)] # before sortingprint(gfg) # sorting objects on the basis of value # stored at variable b# after sortingprint(sorted(gfg))
Output:
inside class[(‘geeks’, 1), (‘computer’, 3), (‘for’, 2), (‘geeks’, 4), (‘science’, 3)][(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]
Python function-programs
Python functools-module
Python-Functions
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": "\n29 Dec, 2020"
},
{
"code": null,
"e": 468,
"s": 28,
"text": "The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced version of sorting elements but instead of a list we are dealing with objects of a class. "
},
{
"code": null,
"e": 504,
"s": 468,
"text": "Here sorted() method will be used. "
},
{
"code": null,
"e": 512,
"s": 504,
"text": "Syntax:"
},
{
"code": null,
"e": 565,
"s": 512,
"text": "sorted (iterable, key(optional), reverse(optional) )"
},
{
"code": null,
"e": 641,
"s": 565,
"text": "Example: This is just a generic example to show how this method is employed"
},
{
"code": null,
"e": 649,
"s": 641,
"text": "Python3"
},
{
"code": "print(sorted([1,26,3,9])) print(sorted(\"Geeks foR gEEks\".split(), key=str.lower))",
"e": 732,
"s": 649,
"text": null
},
{
"code": null,
"e": 740,
"s": 732,
"text": "Output:"
},
{
"code": null,
"e": 780,
"s": 740,
"text": "[1, 3, 9, 26]\n['foR', 'Geeks', 'gEEks']"
},
{
"code": null,
"e": 790,
"s": 780,
"text": "Method 1:"
},
{
"code": null,
"e": 1171,
"s": 790,
"text": "In order to sort objects of a user-defined class, a key needs to be set for the sorted method, such that the key will be an indicator of how the objects should be sorted. With reference to the examples given below, here a function has been provided to the key which one by one compares the specified variable value for each object and returns a sorted list of objects for a class."
},
{
"code": null,
"e": 1253,
"s": 1171,
"text": "Example 1: Sorting elements in ascending order of the integer value given to them"
},
{
"code": null,
"e": 1261,
"s": 1253,
"text": "Python3"
},
{
"code": "class GFG: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG(\"geeks\", 1), GFG(\"computer\", 3), GFG(\"for\", 2), GFG(\"geeks\", 4), GFG(\"science\", 3)] # sorting objects on the basis of value # stored at variable bprint(sorted(gfg, key=lambda x: x.b))",
"e": 1638,
"s": 1261,
"text": null
},
{
"code": null,
"e": 1646,
"s": 1638,
"text": "Output:"
},
{
"code": null,
"e": 1720,
"s": 1646,
"text": "[(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]"
},
{
"code": null,
"e": 1797,
"s": 1720,
"text": "Example 2: Sorting objects on the basis of the string value a variable holds"
},
{
"code": null,
"e": 1805,
"s": 1797,
"text": "Python3"
},
{
"code": "class GFG: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG(\"geeks\", 1), GFG(\"computer\", 3), GFG(\"for\", 2), GFG(\"geeks\", 4), GFG(\"science\", 3)] # sorting objects on the basis of value # stored at variable aprint(sorted(gfg, key=lambda x: x.a.lower()))",
"e": 2190,
"s": 1805,
"text": null
},
{
"code": null,
"e": 2198,
"s": 2190,
"text": "Output:"
},
{
"code": null,
"e": 2272,
"s": 2198,
"text": "[(‘computer’, 3), (‘for’, 2), (‘geeks’, 1), (‘geeks’, 4), (‘science’, 3)]"
},
{
"code": null,
"e": 2282,
"s": 2272,
"text": "Method 2:"
},
{
"code": null,
"e": 2617,
"s": 2282,
"text": "This method depicts how objects of a user-defined class can be sorted using functools inbuilt method total_ordering as a decorator to the class. Here, the class is defined normally as done in the above examples, only difference being during sorting, total_ordering() decorator is used. Two requirements for using total_ordering() are-"
},
{
"code": null,
"e": 2805,
"s": 2617,
"text": "Out of less than(__lt__), greater than(__gt__), less than equal to(__le__) and greater than equal to(__ge__), atleast one should be defined in the class being decorated using this method."
},
{
"code": null,
"e": 2842,
"s": 2805,
"text": "Equal to (__eq__) should be defined."
},
{
"code": null,
"e": 3252,
"s": 2842,
"text": "In the example given below less than and greater than, both are defined even though during processing only one is called(in this less than) since one is enough to decide the order of the elements but it is good programming practice to define all in case one thing fails. During sorting one of the comparison methods are called to compare objects on the basis of some element and the sorted result is returned."
},
{
"code": null,
"e": 3261,
"s": 3252,
"text": "Example:"
},
{
"code": null,
"e": 3269,
"s": 3261,
"text": "Python3"
},
{
"code": "import functoolsfrom functools import total_ordering @total_orderingclass GFG: print(\"inside class\") def __init__(self, a, b): self.a = a self.b = b def __lt__(self, obj): return ((self.b) < (obj.b)) def __gt__(self, obj): return ((self.b) > (obj.b)) def __le__(self, obj): return ((self.b) <= (obj.b)) def __ge__(self, obj): return ((self.b) >= (obj.b)) def __eq__(self, obj): return (self.b == obj.b) def __repr__(self): return str((self.a, self.b)) # list of objectsgfg = [GFG(\"geeks\", 1), GFG(\"computer\", 3), GFG(\"for\", 2), GFG(\"geeks\", 4), GFG(\"science\", 3)] # before sortingprint(gfg) # sorting objects on the basis of value # stored at variable b# after sortingprint(sorted(gfg))",
"e": 4082,
"s": 3269,
"text": null
},
{
"code": null,
"e": 4090,
"s": 4082,
"text": "Output:"
},
{
"code": null,
"e": 4249,
"s": 4090,
"text": "inside class[(‘geeks’, 1), (‘computer’, 3), (‘for’, 2), (‘geeks’, 4), (‘science’, 3)][(‘geeks’, 1), (‘for’, 2), (‘computer’, 3), (‘science’, 3), (‘geeks’, 4)]"
},
{
"code": null,
"e": 4274,
"s": 4249,
"text": "Python function-programs"
},
{
"code": null,
"e": 4298,
"s": 4274,
"text": "Python functools-module"
},
{
"code": null,
"e": 4315,
"s": 4298,
"text": "Python-Functions"
},
{
"code": null,
"e": 4322,
"s": 4315,
"text": "Python"
},
{
"code": null,
"e": 4420,
"s": 4322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4452,
"s": 4420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4479,
"s": 4452,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4500,
"s": 4479,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4523,
"s": 4500,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4579,
"s": 4523,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4610,
"s": 4579,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4652,
"s": 4610,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4694,
"s": 4652,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4733,
"s": 4694,
"text": "Python | Get unique values from a list"
}
] |
SQL | Difference between functions and stored procedures in PL/SQL | 06 Jun, 2022
Prerequisite:
Procedures in PL/SQL
Functions in PL/SQL.
Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)):
1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and returns the result of the function. Example:
SP ->
create or replace procedure GEEKS(x int)
is
y int;
begin
.....
UDF->
FUNCTION GEEKS(x int)
/*return statement so we must return value in function */
RETURN int
IS
y int;
BEGIN
.....
2. SP can have input/output parameters but UDF only has input parameters. Example:
SP ->
CREATE OR REPLACE PROCEDURE Factorial(x IN NUMBER, result OUT NUMBER)
is
begin
....
UDF ->
FUNCTION Factorial(x IN NUMBER) /* only input parameter */
return NUMBER
is
result NUMBER;
begin
.....
3. We can call UDF from SP but cannot call SP from a function. Example:
Calling UDF cal() inside SP square() but reverse is not possible.
set serveroutput on;
declare
a int;
c int;
function cal(temp int)
return int
as
ans int;
begin
ans:=temp* temp;
return ans;
end;
procedure square(x in int, ans out int)
is
begin
dbms_output.put_line('calling function in procedure');
ans:= cal(x);
end;
begin
a:=6;
square(a, c);
dbms_output.put_line('the answer is '|| c);
end;
OUTPUT:
calling function in the procedure
the answer is 36
4. We cannot use SP in SQL statements like SELECT, INSERT, UPDATE, DELETE, MERGE, etc. but we can use them with UDF.
5. SP is not allowed to be used in SELECT statements, but UDF can be used.
6. SP cannot be used anywhere in the WHERE/HAVING/SELECT part of SQL queries, but UDF can be used.
7. The execution plan can be re-used in SP but in UDF it will be compiled every time.
8. We can use try-catch exception handling in SP but we cannot do that in UDF.
9. We can use transactions in SP but it is not possible in UDF.
10. We can consider UDF as an expression but it is not possible in SP.
11. SP cannot be used in the join clause but it is possible in UDF as a resultset.
12. SP can have both table variables and temporary tables but UDF can have only table variables as it does not permit the use of temporary tables.
13. Advantages of using UDF–
Enables faster execution
Modular Programming
Can reduce network traffic (data)
Advantages of using SP–
Improved security measures
Client/server traffic is reduced.
Programming abstraction and efficient code reuse
Pre-compiled Execution
itskawal2000
annieahujaweb2020
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 67,
"s": 52,
"text": "Prerequisite: "
},
{
"code": null,
"e": 88,
"s": 67,
"text": "Procedures in PL/SQL"
},
{
"code": null,
"e": 109,
"s": 88,
"text": "Functions in PL/SQL."
},
{
"code": null,
"e": 197,
"s": 109,
"text": "Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): "
},
{
"code": null,
"e": 388,
"s": 197,
"text": "1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and returns the result of the function. Example: "
},
{
"code": null,
"e": 602,
"s": 388,
"text": "SP ->\ncreate or replace procedure GEEKS(x int) \nis\ny int;\nbegin\n.....\n\nUDF->\nFUNCTION GEEKS(x int) \n/*return statement so we must return value in function */ \nRETURN int \nIS \n y int; \nBEGIN \n....."
},
{
"code": null,
"e": 686,
"s": 602,
"text": "2. SP can have input/output parameters but UDF only has input parameters. Example: "
},
{
"code": null,
"e": 894,
"s": 686,
"text": " SP ->\n CREATE OR REPLACE PROCEDURE Factorial(x IN NUMBER, result OUT NUMBER)\n is\n begin\n ....\n\nUDF ->\nFUNCTION Factorial(x IN NUMBER) /* only input parameter */ \nreturn NUMBER\nis\nresult NUMBER;\nbegin\n....."
},
{
"code": null,
"e": 967,
"s": 894,
"text": "3. We can call UDF from SP but cannot call SP from a function. Example: "
},
{
"code": null,
"e": 1428,
"s": 967,
"text": "Calling UDF cal() inside SP square() but reverse is not possible.\n\nset serveroutput on;\ndeclare\na int;\nc int;\n\nfunction cal(temp int)\nreturn int\nas \nans int;\nbegin\nans:=temp* temp;\nreturn ans;\nend;\n\nprocedure square(x in int, ans out int) \nis\nbegin\ndbms_output.put_line('calling function in procedure');\nans:= cal(x);\nend;\n\nbegin\na:=6;\nsquare(a, c);\ndbms_output.put_line('the answer is '|| c);\nend;\n\nOUTPUT: \ncalling function in the procedure\nthe answer is 36"
},
{
"code": null,
"e": 1545,
"s": 1428,
"text": "4. We cannot use SP in SQL statements like SELECT, INSERT, UPDATE, DELETE, MERGE, etc. but we can use them with UDF."
},
{
"code": null,
"e": 1620,
"s": 1545,
"text": "5. SP is not allowed to be used in SELECT statements, but UDF can be used."
},
{
"code": null,
"e": 1719,
"s": 1620,
"text": "6. SP cannot be used anywhere in the WHERE/HAVING/SELECT part of SQL queries, but UDF can be used."
},
{
"code": null,
"e": 1805,
"s": 1719,
"text": "7. The execution plan can be re-used in SP but in UDF it will be compiled every time."
},
{
"code": null,
"e": 1884,
"s": 1805,
"text": "8. We can use try-catch exception handling in SP but we cannot do that in UDF."
},
{
"code": null,
"e": 1948,
"s": 1884,
"text": "9. We can use transactions in SP but it is not possible in UDF."
},
{
"code": null,
"e": 2019,
"s": 1948,
"text": "10. We can consider UDF as an expression but it is not possible in SP."
},
{
"code": null,
"e": 2102,
"s": 2019,
"text": "11. SP cannot be used in the join clause but it is possible in UDF as a resultset."
},
{
"code": null,
"e": 2249,
"s": 2102,
"text": "12. SP can have both table variables and temporary tables but UDF can have only table variables as it does not permit the use of temporary tables."
},
{
"code": null,
"e": 2279,
"s": 2249,
"text": "13. Advantages of using UDF– "
},
{
"code": null,
"e": 2304,
"s": 2279,
"text": "Enables faster execution"
},
{
"code": null,
"e": 2324,
"s": 2304,
"text": "Modular Programming"
},
{
"code": null,
"e": 2358,
"s": 2324,
"text": "Can reduce network traffic (data)"
},
{
"code": null,
"e": 2388,
"s": 2358,
"text": " Advantages of using SP–"
},
{
"code": null,
"e": 2415,
"s": 2388,
"text": "Improved security measures"
},
{
"code": null,
"e": 2449,
"s": 2415,
"text": "Client/server traffic is reduced."
},
{
"code": null,
"e": 2498,
"s": 2449,
"text": "Programming abstraction and efficient code reuse"
},
{
"code": null,
"e": 2522,
"s": 2498,
"text": "Pre-compiled Execution "
},
{
"code": null,
"e": 2535,
"s": 2522,
"text": "itskawal2000"
},
{
"code": null,
"e": 2553,
"s": 2535,
"text": "annieahujaweb2020"
},
{
"code": null,
"e": 2564,
"s": 2553,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 2569,
"s": 2564,
"text": "DBMS"
},
{
"code": null,
"e": 2573,
"s": 2569,
"text": "SQL"
},
{
"code": null,
"e": 2578,
"s": 2573,
"text": "DBMS"
},
{
"code": null,
"e": 2582,
"s": 2578,
"text": "SQL"
}
] |
Python | Pandas dataframe.cumsum() | 16 Nov, 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 dataframe.cumsum() is used to find the cumulative sum value over any axis. Each cell is populated with the cumulative sum of the values seen so far.
Syntax: DataFrame.cumsum(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cumsum : Series
Example #1: Use cumsum() function to find the cumulative sum of the values along the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # Print the dataframedf
Output :
Now find the cumulative sum of the values over the index axis
# To find the cumulative sumdf.cumsum(axis = 0)
Output :
Example #2: Use cumsum() function to find the cumulative sum of the values seen so far along the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # To find the cumulative sum along column axisdf.cumsum(axis = 1)
Output :
Example #3: Use cumsum() function to find the cumulative sum of the values seen so far along the index axis in a data frame with NaN value present in dataframe.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4], "B":[None, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, None]}) # To find the cumulative sumdf.cumsum(axis = 0, skipna = True)
Output :
The output is a dataframe with cells containing the cumulative sum of the values seen so far along the index axis. Any Nan value in the dataframe is skipped.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 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": 398,
"s": 242,
"text": "Pandas dataframe.cumsum() is used to find the cumulative sum value over any axis. Each cell is populated with the cumulative sum of the values seen so far."
},
{
"code": null,
"e": 464,
"s": 398,
"text": "Syntax: DataFrame.cumsum(axis=None, skipna=True, *args, **kwargs)"
},
{
"code": null,
"e": 592,
"s": 464,
"text": "Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA"
},
{
"code": null,
"e": 617,
"s": 592,
"text": "Returns: cumsum : Series"
},
{
"code": null,
"e": 714,
"s": 617,
"text": "Example #1: Use cumsum() function to find the cumulative sum of the values along the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # Print the dataframedf",
"e": 955,
"s": 714,
"text": null
},
{
"code": null,
"e": 964,
"s": 955,
"text": "Output :"
},
{
"code": null,
"e": 1026,
"s": 964,
"text": "Now find the cumulative sum of the values over the index axis"
},
{
"code": "# To find the cumulative sumdf.cumsum(axis = 0)",
"e": 1074,
"s": 1026,
"text": null
},
{
"code": null,
"e": 1083,
"s": 1074,
"text": "Output :"
},
{
"code": null,
"e": 1195,
"s": 1085,
"text": "Example #2: Use cumsum() function to find the cumulative sum of the values seen so far along the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # To find the cumulative sum along column axisdf.cumsum(axis = 1)",
"e": 1478,
"s": 1195,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1478,
"text": "Output :"
},
{
"code": null,
"e": 1650,
"s": 1489,
"text": "Example #3: Use cumsum() function to find the cumulative sum of the values seen so far along the index axis in a data frame with NaN value present in dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, None, 4], \"B\":[None, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, None]}) # To find the cumulative sumdf.cumsum(axis = 0, skipna = True)",
"e": 1938,
"s": 1650,
"text": null
},
{
"code": null,
"e": 1947,
"s": 1938,
"text": "Output :"
},
{
"code": null,
"e": 2105,
"s": 1947,
"text": "The output is a dataframe with cells containing the cumulative sum of the values seen so far along the index axis. Any Nan value in the dataframe is skipped."
},
{
"code": null,
"e": 2129,
"s": 2105,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2161,
"s": 2129,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2175,
"s": 2161,
"text": "Python-pandas"
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Python"
},
{
"code": null,
"e": 2280,
"s": 2182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2298,
"s": 2280,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2340,
"s": 2298,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2362,
"s": 2340,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2388,
"s": 2362,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2420,
"s": 2388,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2449,
"s": 2420,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2476,
"s": 2449,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2497,
"s": 2476,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2533,
"s": 2497,
"text": "Convert integer to string in Python"
}
] |
How do you use regular expressions in Cucumber? | We can use regular expressions in Cucumber for selecting a collection of
similar statements in the feature file.
feature file
Feature: Exam Syllabus
Scenario Outline: Summer and Winter Exam Schedule
Given Exam time table in summer season
Given Mathematics and Physics Syllabus
Given Exam time table in winter season
The step Definition file has @Given("^Exam time table in ([^\"]*) season$") which maps two Given statements in a Feature file with the help of regular expression.
@Given ("^Exam time table in ([^\"]*) season$")
public void timeTable(String season){
if (season.equals("winter")){
System.out.println("The winter syllabus");
}else{
System.out.println("The summer syllabus");
}
}
@Given ("^Mathematics and Physics Syllabus$")
public void syllabusList(){
System.out.println("Mathematics and Physics syllabus is");
} | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "We can use regular expressions in Cucumber for selecting a collection of\nsimilar statements in the feature file."
},
{
"code": null,
"e": 1188,
"s": 1175,
"text": "feature file"
},
{
"code": null,
"e": 1378,
"s": 1188,
"text": "Feature: Exam Syllabus\nScenario Outline: Summer and Winter Exam Schedule\nGiven Exam time table in summer season\nGiven Mathematics and Physics Syllabus\nGiven Exam time table in winter season"
},
{
"code": null,
"e": 1541,
"s": 1378,
"text": "The step Definition file has @Given(\"^Exam time table in ([^\\\"]*) season$\") which maps two Given statements in a Feature file with the help of regular expression."
},
{
"code": null,
"e": 1913,
"s": 1541,
"text": "@Given (\"^Exam time table in ([^\\\"]*) season$\")\npublic void timeTable(String season){\n if (season.equals(\"winter\")){\n System.out.println(\"The winter syllabus\");\n }else{\n System.out.println(\"The summer syllabus\");\n }\n}\n@Given (\"^Mathematics and Physics Syllabus$\")\npublic void syllabusList(){\n System.out.println(\"Mathematics and Physics syllabus is\");\n}"
}
] |
Buy chocolates and save N rupees | Practice | GeeksforGeeks | Geek wants to buy chocolates. The shop only has two types of chocolates. One costs 3 rupees and the other costs 7 rupees. Geek has 100 rupees. Is it possible for him to save exactly N rupees after visiting the shop ?
Example 1:
Input: N = 99
Output: 0
Explaination: Geek needs to save 99 rupees.
That means he can only spend 1 rupee. But
no chocolate is available for 1 rupee. Therefore
there is no way for him to save N rupees.
Eaxmple 2:
Input: N = 97
Output: 1
Explaination: Geek can buy one chocolate
for 3 rupees and save 97 rupees.
Your Task:
You do not need to read input or print anything. Your task is to complete the function isPossible() which takes N as input parameter and returns 1 if Geek can save N rupees else returns 0.
Expected Time Compexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
0 ≤ N ≤ 100
+1
shekfider
This comment was deleted.
0
adiraju uttej3 years ago
adiraju uttej
Java solution:-
https://ide.geeksforgeeks.o...
0
Shubham Singh4 years ago
Shubham Singh
gfg needs to do something our time are wasted due to wrong test cases.output gives 0 when i take it as custom input but when i submit it says wrong answerfor input 89.
my code is
#include<iostream>using namespace std;int main() {int test;cin>>test;while(test--){ int n,flag=0; cin>>n; int i,j; for(i=0;i<=100;i=i+7) { for(j=0;j<=100;j+=3) { if(((100-(i+j)==n)&&(i!=0 || j!=0)) { cout<<"1"<<endl; flag="1;" break;="" }="" }="" }="" if(flag="=0)" cout<<"0"<<endl;="" }="" return="" 0;="" }="">
0
Raj Sahu4 years ago
Raj Sahu
https://code.hackerearth.co...
this code is giving answer for 90 to be 1, but the g4g ide is not!
can somebody help me with this?
0
Pranav Bharadwaj4 years ago
Pranav Bharadwaj
It is showing correct output for input 1 as 1, should the output be 0?*Sorry wrong question. Ignore
0
sonali dongre4 years ago
sonali dongre
https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... TYzRvvL
why this is showing wrong output for input 89 but while compiling it is giving right output
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": 443,
"s": 226,
"text": "Geek wants to buy chocolates. The shop only has two types of chocolates. One costs 3 rupees and the other costs 7 rupees. Geek has 100 rupees. Is it possible for him to save exactly N rupees after visiting the shop ?"
},
{
"code": null,
"e": 455,
"s": 443,
"text": "\nExample 1:"
},
{
"code": null,
"e": 660,
"s": 455,
"text": "Input: N = 99\nOutput: 0\nExplaination: Geek needs to save 99 rupees. \nThat means he can only spend 1 rupee. But \nno chocolate is available for 1 rupee. Therefore \nthere is no way for him to save N rupees. "
},
{
"code": null,
"e": 672,
"s": 660,
"text": "\nEaxmple 2:"
},
{
"code": null,
"e": 771,
"s": 672,
"text": "Input: N = 97\nOutput: 1\nExplaination: Geek can buy one chocolate \nfor 3 rupees and save 97 rupees."
},
{
"code": null,
"e": 972,
"s": 771,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function isPossible() which takes N as input parameter and returns 1 if Geek can save N rupees else returns 0."
},
{
"code": null,
"e": 1034,
"s": 972,
"text": "\nExpected Time Compexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1060,
"s": 1034,
"text": "\nConstraints:\n0 ≤ N ≤ 100"
},
{
"code": null,
"e": 1063,
"s": 1060,
"text": "+1"
},
{
"code": null,
"e": 1073,
"s": 1063,
"text": "shekfider"
},
{
"code": null,
"e": 1099,
"s": 1073,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1101,
"s": 1099,
"text": "0"
},
{
"code": null,
"e": 1126,
"s": 1101,
"text": "adiraju uttej3 years ago"
},
{
"code": null,
"e": 1140,
"s": 1126,
"text": "adiraju uttej"
},
{
"code": null,
"e": 1156,
"s": 1140,
"text": "Java solution:-"
},
{
"code": null,
"e": 1187,
"s": 1156,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 1189,
"s": 1187,
"text": "0"
},
{
"code": null,
"e": 1214,
"s": 1189,
"text": "Shubham Singh4 years ago"
},
{
"code": null,
"e": 1228,
"s": 1214,
"text": "Shubham Singh"
},
{
"code": null,
"e": 1396,
"s": 1228,
"text": "gfg needs to do something our time are wasted due to wrong test cases.output gives 0 when i take it as custom input but when i submit it says wrong answerfor input 89."
},
{
"code": null,
"e": 1407,
"s": 1396,
"text": "my code is"
},
{
"code": null,
"e": 1786,
"s": 1407,
"text": "#include<iostream>using namespace std;int main() {int test;cin>>test;while(test--){ int n,flag=0; cin>>n; int i,j; for(i=0;i<=100;i=i+7) { for(j=0;j<=100;j+=3) { if(((100-(i+j)==n)&&(i!=0 || j!=0)) { cout<<\"1\"<<endl; flag=\"1;\" break;=\"\" }=\"\" }=\"\" }=\"\" if(flag=\"=0)\" cout<<\"0\"<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 1788,
"s": 1786,
"text": "0"
},
{
"code": null,
"e": 1808,
"s": 1788,
"text": "Raj Sahu4 years ago"
},
{
"code": null,
"e": 1817,
"s": 1808,
"text": "Raj Sahu"
},
{
"code": null,
"e": 1848,
"s": 1817,
"text": "https://code.hackerearth.co..."
},
{
"code": null,
"e": 1915,
"s": 1848,
"text": "this code is giving answer for 90 to be 1, but the g4g ide is not!"
},
{
"code": null,
"e": 1947,
"s": 1915,
"text": "can somebody help me with this?"
},
{
"code": null,
"e": 1949,
"s": 1947,
"text": "0"
},
{
"code": null,
"e": 1977,
"s": 1949,
"text": "Pranav Bharadwaj4 years ago"
},
{
"code": null,
"e": 1994,
"s": 1977,
"text": "Pranav Bharadwaj"
},
{
"code": null,
"e": 2094,
"s": 1994,
"text": "It is showing correct output for input 1 as 1, should the output be 0?*Sorry wrong question. Ignore"
},
{
"code": null,
"e": 2096,
"s": 2094,
"text": "0"
},
{
"code": null,
"e": 2121,
"s": 2096,
"text": "sonali dongre4 years ago"
},
{
"code": null,
"e": 2135,
"s": 2121,
"text": "sonali dongre"
},
{
"code": null,
"e": 2205,
"s": 2135,
"text": "https://ide.geeksforgeeks.o... https://uploads.disquscdn.c... TYzRvvL"
},
{
"code": null,
"e": 2297,
"s": 2205,
"text": "why this is showing wrong output for input 89 but while compiling it is giving right output"
},
{
"code": null,
"e": 2443,
"s": 2297,
"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": 2479,
"s": 2443,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2489,
"s": 2479,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2499,
"s": 2489,
"text": "\nContest\n"
},
{
"code": null,
"e": 2562,
"s": 2499,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2710,
"s": 2562,
"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": 2918,
"s": 2710,
"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": 3024,
"s": 2918,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Advanced Excel Logical - IFS Function | The IFS function checks whether one or more conditions are met and returns a value that corresponds to the first TRUE condition. This Function was added in Excel 2016.
IFS (logical_test1, value_if_true1, [logical_test2, value_if_true2], [logical_test3, value_if_true3]...)
As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments.
As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments.
To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met.
To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met.
If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical "You've entered too few arguments for this function" error message.
If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical "You've entered too few arguments for this function" error message.
If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error.
If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error.
If no TRUE conditions are found, IFS returns #N/A! error.
If no TRUE conditions are found, IFS returns #N/A! error.
Excel 2016
296 Lectures
146 hours
Arun Motoori
56 Lectures
5.5 hours
Pavan Lalwani
120 Lectures
6.5 hours
Inf Sid
134 Lectures
8.5 hours
Yoda Learning
46 Lectures
7.5 hours
William Fiset
25 Lectures
1.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2022,
"s": 1854,
"text": "The IFS function checks whether one or more conditions are met and returns a value that corresponds to the first TRUE condition. This Function was added in Excel 2016."
},
{
"code": null,
"e": 2129,
"s": 2022,
"text": "IFS (logical_test1, value_if_true1, [logical_test2, value_if_true2], [logical_test3, value_if_true3]...) \n"
},
{
"code": null,
"e": 2236,
"s": 2129,
"text": "As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments."
},
{
"code": null,
"e": 2343,
"s": 2236,
"text": "As functions are limited to 254 parameters, you can use up to 127 pairs of condition and result arguments."
},
{
"code": null,
"e": 2552,
"s": 2343,
"text": "To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met."
},
{
"code": null,
"e": 2761,
"s": 2552,
"text": "To specify a default result, enter a condition that will always be true for your final logical_test argument, such as TRUE or 1=1. The corresponding value will return, if none of the other conditions are met."
},
{
"code": null,
"e": 2929,
"s": 2761,
"text": "If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical \"You've entered too few arguments for this function\" error message."
},
{
"code": null,
"e": 3097,
"s": 2929,
"text": "If a logical_test argument is supplied without a corresponding value_if_true, IFS shows the typical \"You've entered too few arguments for this function\" error message."
},
{
"code": null,
"e": 3216,
"s": 3097,
"text": "If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error."
},
{
"code": null,
"e": 3335,
"s": 3216,
"text": "If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, IFS returns a #VALUE! Error."
},
{
"code": null,
"e": 3393,
"s": 3335,
"text": "If no TRUE conditions are found, IFS returns #N/A! error."
},
{
"code": null,
"e": 3451,
"s": 3393,
"text": "If no TRUE conditions are found, IFS returns #N/A! error."
},
{
"code": null,
"e": 3462,
"s": 3451,
"text": "Excel 2016"
},
{
"code": null,
"e": 3498,
"s": 3462,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3512,
"s": 3498,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3547,
"s": 3512,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3562,
"s": 3547,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3598,
"s": 3562,
"text": "\n 120 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3607,
"s": 3598,
"text": " Inf Sid"
},
{
"code": null,
"e": 3643,
"s": 3607,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3658,
"s": 3643,
"text": " Yoda Learning"
},
{
"code": null,
"e": 3693,
"s": 3658,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3708,
"s": 3693,
"text": " William Fiset"
},
{
"code": null,
"e": 3743,
"s": 3708,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3757,
"s": 3743,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3764,
"s": 3757,
"text": " Print"
},
{
"code": null,
"e": 3775,
"s": 3764,
"text": " Add Notes"
}
] |
Prevent scientific notation in matplotlib.pyplot | To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.
Pass two lists to draw a line using plot() method.
Pass two lists to draw a line using plot() method.
Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation.
Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation.
To show the figure, use plt.show() method.
To show the figure, use plt.show() method.
from matplotlib import pyplot as plt
plt.plot([1, 2, 3, 4, 5], [11, 12, 13, 14, 15])
plt.ticklabel_format(style='plain') # to prevent scientific notation.
plt.show() | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To prevent scientific notation, we must pass style='plain' in the ticklabel_format method."
},
{
"code": null,
"e": 1204,
"s": 1153,
"text": "Pass two lists to draw a line using plot() method."
},
{
"code": null,
"e": 1255,
"s": 1204,
"text": "Pass two lists to draw a line using plot() method."
},
{
"code": null,
"e": 1442,
"s": 1255,
"text": "Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation."
},
{
"code": null,
"e": 1629,
"s": 1442,
"text": "Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation."
},
{
"code": null,
"e": 1672,
"s": 1629,
"text": "To show the figure, use plt.show() method."
},
{
"code": null,
"e": 1715,
"s": 1672,
"text": "To show the figure, use plt.show() method."
},
{
"code": null,
"e": 1884,
"s": 1715,
"text": "from matplotlib import pyplot as plt\nplt.plot([1, 2, 3, 4, 5], [11, 12, 13, 14, 15])\nplt.ticklabel_format(style='plain') # to prevent scientific notation.\nplt.show()"
}
] |
Summarizing data with Pandas crosstab | by B. Chen | Towards Data Science | The most immediate effect of summarizing data is to take data that may be overwhelming to work with, and reduce it to a few key summary values that can be viewed, often in a table or plot.
Source from Introduction to Data Science [1]
Data summarization is a process to present the summary of generated data in an easily comprehensible and informative manner. Pandas provides several options for summarizing data: groupby, pivot_table, and crosstab.
We have previously covered the Pandas pivot_table() and groupby(), this article will explore the Pandas crosstab() and how to use it for your data analysis. This article is structured as follows:
Simplest crosstab tableDisplaying multiple rows and columnsShowing total with marginsGetting the percentage of occurs with normalizeSpecifying values and performing aggregationHandling missing valuesVisualization with Seaborn heatmap
Simplest crosstab table
Displaying multiple rows and columns
Showing total with margins
Getting the percentage of occurs with normalize
Specifying values and performing aggregation
Handling missing values
Visualization with Seaborn heatmap
Please check out the Notebook for source code. More tutorials are available from Github Repo.
For demonstration, we will be working on coffee sales data. Let’s import some libraries and load data to get started:
import pandas as pddef load_data(): return pd.read_csv('coffee_sales.csv', parse_dates=['order_date'])df = load_data()df.head()
When you create a crosstab table, you’ll need to specify what you want on the rows and how to split the columns. By default, it is calculating the number of observations in each combination. In our example, let’s use the region as our row index and split the columns by product_category.
pd.crosstab(df['region'], df['product_category'])
In some cases, you would prefer a custom label for display purposes. To do that, we can include the specific rownames and colnames:
pd.crosstab( df['region'], df['product_category'], rownames=['US Region'], colnames=['Product Category'])
One of the most useful features of crosstab is that you can pass in multiple indexes and columns, and it does all the grouping for us. For example, if we want to see how the data is distributed by market, we can include the market column by including it in a list:
pd.crosstab( df['region'], [df['product_category'], df['market']])
Similarly, we can specify a custom label for display purposes. Both rownames and colnames accept a list of labels with each corresponding to the row and column.
pd.crosstab( df['region'], [df['product_category'], df['market']], rownames=['US Region'], colnames=['Product Category', 'Market'])
Another common display in a crosstab table is to show the subtotals for each row and column. We can add them by setting the margins=True argument:
pd.crosstab(df['region'], df['product_category'], margins = True)
By default, the subtotals are displayed with the label “All”. We can specify a custom label using the margins_name argument:
pd.crosstab( df['region'], df['product_category'], margins = True, margins_name = 'Subtotals')
One of the common tasks in data analysis is to understand the percentage of occurs. This can be accomplished by setting the normalize argument to True:
pd.crosstab(df['region'], df['product_category'], normalize = True)
If we prefer the result to be formatted with a percent sign (%), we can call style.format('{:.2%}') as follows:
pd.crosstab( df['region'], df['product_category'], normalize = True).style.format('{:.2%}')
In addition, this calculation is applied to the subtotals when the margins is True:
pd.crosstab( df['region'], df['product_category'], margins = True, normalize = True).style.format('{:.2%}')
The normalize argument accepts the other two values 'index' and 'columns' :
If 'index' is given, it will normalize over each row.
If 'columns' is given, it will normalize over each column.
pd.crosstab( df['region'], df['product_category'], margins = True, normalize = 'columns').style.format('{:.2%}')
pd.crosstab( df['region'], df['product_category'], margins = True, normalize = 'index').style.format('{:.2%}')
By default, crosstab performs the count aggregation function on all numerical columns and returns the result. To explicitly specify the columns we care about and perform aggregation, use the values and aggfunc arguments.
pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean')
By specifying values = df['cost'] and aggfunc = 'mean' , we are telling Pandas to apply the mean function to the cost of all the combinations of the data.
The result will retain 6 decimal places by default. To round the result, we can call round():
pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean').round(2)
You probably notice a NaN value from the previous output. We have got that because there aren't any Tea sales in the South.
Unlike privot_table has a built-in fill_value argument to replace any missing value, crosstab doesn’t support it. We have to use other methods to handle missing values, for example:
pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean',).fillna(0)
However, if the crosstab output includes rows or columns whose entries are all NaN, we could use the argument drop_na=True to drop them.
Honestly, I didn't know this until I read the Pandas Crosstab Explained article [2]. Sometimes, a graph is worth a thousand words and this is a really handy feature to visually summarize the crosstab output. What we need to do is simply pass the crosstab output to a seaborn heatmap:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(8, 6))sns.heatmap( pd.crosstab( df['region'], [df['product_category'], df['market']], rownames=['US Region'], colnames=['Product Category', 'Market'], values = df['cost'], aggfunc = 'mean' ), annot = True)plt.show()
In this article, we have covered 7 use cases about summarizing data with the Pandas crosstab() method. It’s a very useful tool and one of the top favorite methods for Data Summarization during Exploratory Data Analysis.
After reading this article, you should be able to incorporate it in your own data analysis. I hope you enjoyed this article and learned something new and useful.
Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. More tutorials are available from the Github Repo.
[1] Introduction to Data Science: Data summaries
[2] Pandas Crosstab explained from pbpython.com | [
{
"code": null,
"e": 361,
"s": 172,
"text": "The most immediate effect of summarizing data is to take data that may be overwhelming to work with, and reduce it to a few key summary values that can be viewed, often in a table or plot."
},
{
"code": null,
"e": 406,
"s": 361,
"text": "Source from Introduction to Data Science [1]"
},
{
"code": null,
"e": 621,
"s": 406,
"text": "Data summarization is a process to present the summary of generated data in an easily comprehensible and informative manner. Pandas provides several options for summarizing data: groupby, pivot_table, and crosstab."
},
{
"code": null,
"e": 817,
"s": 621,
"text": "We have previously covered the Pandas pivot_table() and groupby(), this article will explore the Pandas crosstab() and how to use it for your data analysis. This article is structured as follows:"
},
{
"code": null,
"e": 1051,
"s": 817,
"text": "Simplest crosstab tableDisplaying multiple rows and columnsShowing total with marginsGetting the percentage of occurs with normalizeSpecifying values and performing aggregationHandling missing valuesVisualization with Seaborn heatmap"
},
{
"code": null,
"e": 1075,
"s": 1051,
"text": "Simplest crosstab table"
},
{
"code": null,
"e": 1112,
"s": 1075,
"text": "Displaying multiple rows and columns"
},
{
"code": null,
"e": 1139,
"s": 1112,
"text": "Showing total with margins"
},
{
"code": null,
"e": 1187,
"s": 1139,
"text": "Getting the percentage of occurs with normalize"
},
{
"code": null,
"e": 1232,
"s": 1187,
"text": "Specifying values and performing aggregation"
},
{
"code": null,
"e": 1256,
"s": 1232,
"text": "Handling missing values"
},
{
"code": null,
"e": 1291,
"s": 1256,
"text": "Visualization with Seaborn heatmap"
},
{
"code": null,
"e": 1385,
"s": 1291,
"text": "Please check out the Notebook for source code. More tutorials are available from Github Repo."
},
{
"code": null,
"e": 1503,
"s": 1385,
"text": "For demonstration, we will be working on coffee sales data. Let’s import some libraries and load data to get started:"
},
{
"code": null,
"e": 1634,
"s": 1503,
"text": "import pandas as pddef load_data(): return pd.read_csv('coffee_sales.csv', parse_dates=['order_date'])df = load_data()df.head()"
},
{
"code": null,
"e": 1922,
"s": 1634,
"text": "When you create a crosstab table, you’ll need to specify what you want on the rows and how to split the columns. By default, it is calculating the number of observations in each combination. In our example, let’s use the region as our row index and split the columns by product_category."
},
{
"code": null,
"e": 1972,
"s": 1922,
"text": "pd.crosstab(df['region'], df['product_category'])"
},
{
"code": null,
"e": 2104,
"s": 1972,
"text": "In some cases, you would prefer a custom label for display purposes. To do that, we can include the specific rownames and colnames:"
},
{
"code": null,
"e": 2225,
"s": 2104,
"text": "pd.crosstab( df['region'], df['product_category'], rownames=['US Region'], colnames=['Product Category'])"
},
{
"code": null,
"e": 2490,
"s": 2225,
"text": "One of the most useful features of crosstab is that you can pass in multiple indexes and columns, and it does all the grouping for us. For example, if we want to see how the data is distributed by market, we can include the market column by including it in a list:"
},
{
"code": null,
"e": 2564,
"s": 2490,
"text": "pd.crosstab( df['region'], [df['product_category'], df['market']])"
},
{
"code": null,
"e": 2725,
"s": 2564,
"text": "Similarly, we can specify a custom label for display purposes. Both rownames and colnames accept a list of labels with each corresponding to the row and column."
},
{
"code": null,
"e": 2871,
"s": 2725,
"text": "pd.crosstab( df['region'], [df['product_category'], df['market']], rownames=['US Region'], colnames=['Product Category', 'Market'])"
},
{
"code": null,
"e": 3018,
"s": 2871,
"text": "Another common display in a crosstab table is to show the subtotals for each row and column. We can add them by setting the margins=True argument:"
},
{
"code": null,
"e": 3084,
"s": 3018,
"text": "pd.crosstab(df['region'], df['product_category'], margins = True)"
},
{
"code": null,
"e": 3209,
"s": 3084,
"text": "By default, the subtotals are displayed with the label “All”. We can specify a custom label using the margins_name argument:"
},
{
"code": null,
"e": 3315,
"s": 3209,
"text": "pd.crosstab( df['region'], df['product_category'], margins = True, margins_name = 'Subtotals')"
},
{
"code": null,
"e": 3467,
"s": 3315,
"text": "One of the common tasks in data analysis is to understand the percentage of occurs. This can be accomplished by setting the normalize argument to True:"
},
{
"code": null,
"e": 3535,
"s": 3467,
"text": "pd.crosstab(df['region'], df['product_category'], normalize = True)"
},
{
"code": null,
"e": 3647,
"s": 3535,
"text": "If we prefer the result to be formatted with a percent sign (%), we can call style.format('{:.2%}') as follows:"
},
{
"code": null,
"e": 3750,
"s": 3647,
"text": "pd.crosstab( df['region'], df['product_category'], normalize = True).style.format('{:.2%}')"
},
{
"code": null,
"e": 3834,
"s": 3750,
"text": "In addition, this calculation is applied to the subtotals when the margins is True:"
},
{
"code": null,
"e": 3957,
"s": 3834,
"text": "pd.crosstab( df['region'], df['product_category'], margins = True, normalize = True).style.format('{:.2%}')"
},
{
"code": null,
"e": 4033,
"s": 3957,
"text": "The normalize argument accepts the other two values 'index' and 'columns' :"
},
{
"code": null,
"e": 4087,
"s": 4033,
"text": "If 'index' is given, it will normalize over each row."
},
{
"code": null,
"e": 4146,
"s": 4087,
"text": "If 'columns' is given, it will normalize over each column."
},
{
"code": null,
"e": 4274,
"s": 4146,
"text": "pd.crosstab( df['region'], df['product_category'], margins = True, normalize = 'columns').style.format('{:.2%}')"
},
{
"code": null,
"e": 4400,
"s": 4274,
"text": "pd.crosstab( df['region'], df['product_category'], margins = True, normalize = 'index').style.format('{:.2%}')"
},
{
"code": null,
"e": 4621,
"s": 4400,
"text": "By default, crosstab performs the count aggregation function on all numerical columns and returns the result. To explicitly specify the columns we care about and perform aggregation, use the values and aggfunc arguments."
},
{
"code": null,
"e": 4725,
"s": 4621,
"text": "pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean')"
},
{
"code": null,
"e": 4880,
"s": 4725,
"text": "By specifying values = df['cost'] and aggfunc = 'mean' , we are telling Pandas to apply the mean function to the cost of all the combinations of the data."
},
{
"code": null,
"e": 4974,
"s": 4880,
"text": "The result will retain 6 decimal places by default. To round the result, we can call round():"
},
{
"code": null,
"e": 5087,
"s": 4974,
"text": "pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean').round(2)"
},
{
"code": null,
"e": 5211,
"s": 5087,
"text": "You probably notice a NaN value from the previous output. We have got that because there aren't any Tea sales in the South."
},
{
"code": null,
"e": 5393,
"s": 5211,
"text": "Unlike privot_table has a built-in fill_value argument to replace any missing value, crosstab doesn’t support it. We have to use other methods to handle missing values, for example:"
},
{
"code": null,
"e": 5508,
"s": 5393,
"text": "pd.crosstab( df['region'], df['product_category'], values = df['cost'], aggfunc = 'mean',).fillna(0)"
},
{
"code": null,
"e": 5645,
"s": 5508,
"text": "However, if the crosstab output includes rows or columns whose entries are all NaN, we could use the argument drop_na=True to drop them."
},
{
"code": null,
"e": 5929,
"s": 5645,
"text": "Honestly, I didn't know this until I read the Pandas Crosstab Explained article [2]. Sometimes, a graph is worth a thousand words and this is a really handy feature to visually summarize the crosstab output. What we need to do is simply pass the crosstab output to a seaborn heatmap:"
},
{
"code": null,
"e": 6308,
"s": 5929,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(8, 6))sns.heatmap( pd.crosstab( df['region'], [df['product_category'], df['market']], rownames=['US Region'], colnames=['Product Category', 'Market'], values = df['cost'], aggfunc = 'mean' ), annot = True)plt.show()"
},
{
"code": null,
"e": 6528,
"s": 6308,
"text": "In this article, we have covered 7 use cases about summarizing data with the Pandas crosstab() method. It’s a very useful tool and one of the top favorite methods for Data Summarization during Exploratory Data Analysis."
},
{
"code": null,
"e": 6690,
"s": 6528,
"text": "After reading this article, you should be able to incorporate it in your own data analysis. I hope you enjoyed this article and learned something new and useful."
},
{
"code": null,
"e": 6893,
"s": 6690,
"text": "Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. More tutorials are available from the Github Repo."
},
{
"code": null,
"e": 6942,
"s": 6893,
"text": "[1] Introduction to Data Science: Data summaries"
}
] |
How to Take a Screenshot in Selenium WebDriver Using Java? - GeeksforGeeks | 23 Jan, 2022
Selenium WebDriver is a collection of open-source APIs which are used to automate the testing of a web application. In order to capture a screenshot in Selenium, one has to utilize the method Takes Screenshot. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used to automate web application testing to verify that it works as expected. It supports many browsers. Here we will be taking the example of chrome.
Syntax:
File file = ((TakesScreenshot) driver) ;
Here, we will learn how to take a screenshot in the selenium web driver and highlight the element using Java Binding.
Screenshots are required for bug analysis especially in the case of test case failure. Whenever a test case fails, we need some attachment to verify that failure. Selenium can automatically take a screenshot during execution, and we can also mark a border to highlight that element.
Steps to take a screenshot in selenium web driver:
1. Take a screenshot and store it in a file format
2. Copy screenshot to a location using CopyFile method
FileUtils.copyFile(File, new File(“location where you want to save the image” +FileName+ “.jpeg”));
3. Create a border around the element: Using the JavaScript executor, we can create a border around the desired element.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.border = '3px solid red'", Element);
Refer to the complete code below for the implementation part
Java
// Java program how to take// a screenshot in Selenium// WebDriver import java.io.*; class GFG { public static void main(String[] args) { // Setting webDriver to chrome System.setProperty("webdriver.chrome.driver", "driver path"); driver = new ChromeDriver(); driver.get("https://www.google.co.in"); WebElement Element = driver.findElement( By.xpath("//input[@name='q']")); // Assignments to webDriver MakeBorder(Element); Thread.sleep(2000); TakeScreenshot("GooglePage"); driver.quit(); } // Function to Take screenshot public static void TakeScreenshot(String FileName) throws IOException { // Creating instance of File File File = ((TakesScreenshot)driver) .getScreenshotAs(OutputType.FILE); FileUtils.copyFile(File, new File("image location" + FileName + ".jpeg")); } // Function to Make border public static void MakeBorder(WebElement Element) { JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript( "arguments[0].style.border = '3px solid red'", Element); }}
Output:
sumitgumber28
selenium
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 24028,
"s": 23557,
"text": "Selenium WebDriver is a collection of open-source APIs which are used to automate the testing of a web application. In order to capture a screenshot in Selenium, one has to utilize the method Takes Screenshot. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used to automate web application testing to verify that it works as expected. It supports many browsers. Here we will be taking the example of chrome."
},
{
"code": null,
"e": 24036,
"s": 24028,
"text": "Syntax:"
},
{
"code": null,
"e": 24077,
"s": 24036,
"text": "File file = ((TakesScreenshot) driver) ;"
},
{
"code": null,
"e": 24195,
"s": 24077,
"text": "Here, we will learn how to take a screenshot in the selenium web driver and highlight the element using Java Binding."
},
{
"code": null,
"e": 24478,
"s": 24195,
"text": "Screenshots are required for bug analysis especially in the case of test case failure. Whenever a test case fails, we need some attachment to verify that failure. Selenium can automatically take a screenshot during execution, and we can also mark a border to highlight that element."
},
{
"code": null,
"e": 24529,
"s": 24478,
"text": "Steps to take a screenshot in selenium web driver:"
},
{
"code": null,
"e": 24580,
"s": 24529,
"text": "1. Take a screenshot and store it in a file format"
},
{
"code": null,
"e": 24637,
"s": 24580,
"text": "2. Copy screenshot to a location using CopyFile method "
},
{
"code": null,
"e": 24739,
"s": 24637,
"text": "FileUtils.copyFile(File, new File(“location where you want to save the image” +FileName+ “.jpeg”)); "
},
{
"code": null,
"e": 24860,
"s": 24739,
"text": "3. Create a border around the element: Using the JavaScript executor, we can create a border around the desired element."
},
{
"code": null,
"e": 24988,
"s": 24860,
"text": "JavascriptExecutor js = (JavascriptExecutor) driver;\n\njs.executeScript(\"arguments[0].style.border = '3px solid red'\", Element);"
},
{
"code": null,
"e": 25049,
"s": 24988,
"text": "Refer to the complete code below for the implementation part"
},
{
"code": null,
"e": 25054,
"s": 25049,
"text": "Java"
},
{
"code": "// Java program how to take// a screenshot in Selenium// WebDriver import java.io.*; class GFG { public static void main(String[] args) { // Setting webDriver to chrome System.setProperty(\"webdriver.chrome.driver\", \"driver path\"); driver = new ChromeDriver(); driver.get(\"https://www.google.co.in\"); WebElement Element = driver.findElement( By.xpath(\"//input[@name='q']\")); // Assignments to webDriver MakeBorder(Element); Thread.sleep(2000); TakeScreenshot(\"GooglePage\"); driver.quit(); } // Function to Take screenshot public static void TakeScreenshot(String FileName) throws IOException { // Creating instance of File File File = ((TakesScreenshot)driver) .getScreenshotAs(OutputType.FILE); FileUtils.copyFile(File, new File(\"image location\" + FileName + \".jpeg\")); } // Function to Make border public static void MakeBorder(WebElement Element) { JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript( \"arguments[0].style.border = '3px solid red'\", Element); }}",
"e": 26329,
"s": 25054,
"text": null
},
{
"code": null,
"e": 26337,
"s": 26329,
"text": "Output:"
},
{
"code": null,
"e": 26351,
"s": 26337,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26360,
"s": 26351,
"text": "selenium"
},
{
"code": null,
"e": 26365,
"s": 26360,
"text": "Java"
},
{
"code": null,
"e": 26370,
"s": 26365,
"text": "Java"
},
{
"code": null,
"e": 26468,
"s": 26370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26477,
"s": 26468,
"text": "Comments"
},
{
"code": null,
"e": 26490,
"s": 26477,
"text": "Old Comments"
},
{
"code": null,
"e": 26520,
"s": 26490,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26535,
"s": 26520,
"text": "Stream In Java"
},
{
"code": null,
"e": 26556,
"s": 26535,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26602,
"s": 26556,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26621,
"s": 26602,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26638,
"s": 26621,
"text": "Generics in Java"
},
{
"code": null,
"e": 26681,
"s": 26638,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26697,
"s": 26681,
"text": "Strings in Java"
},
{
"code": null,
"e": 26746,
"s": 26697,
"text": "How to remove an element from ArrayList in Java?"
}
] |
Function Timeouts using Wrapt Timeout Decorator | Towards Data Science | In this short guide, I will show how to use a handy timeout decorator for Python function to limit the execution times. This guide is based on an example that utilizes Python’s multiprocessing package.
Lately, I’ve been building a script using Beautiful Soup that scrapes similarly structured websites and identifies its chapters. These were 10-K annual reports on the SEC’s website which had to be split according to their 21 sections. To make the script as robust as possible, I’ve used the simple, yet effective, python-constraint module to make sure that the sections were identified in the correct order. This approach worked perfectly in most cases and took less than a second to execute. Unfortunately, for some cases, the constraint function caused the script to run for days until it went through all iterations. By analyzing the execution times of the constraint function, I came to the following conclusion:
Execution time = < 1 second, if there is a solution for the constraint function.
Execution time = hours or days, if there is no solution for the constraint function.
A fix for this issue was simple thanks to the wrapt_timeout_decorator module. The great thing about this module is that it’s easy to use, works great with Python’s multiprocessing module, and has no problem running on Windows.
You can install the wrapt_timeout_decorator module from PyPI using pip.
pip install wrapt_timeout_decorator
If you’re using Conda, I suggest downloading the source files from GitHub (https://github.com/bitranox/wrapt_timeout_decorator) and installing the module manually by running
python setup.py install
within your active environment. You will need Python 3.5 or later for the module to work.
The following example is intended for Windows users. Linux users will have it easier using the wrapt_timeout_decorator because it’s not necessary to put the timeout function in a separate module. For more information on this, see the official documentation here. I haven’t tried this module in a Jupyter notebook, but I assume it will require a workaround similar to the multiprocessing package.
The example below shows how to apply a timeout on a function that is parallelized on multiple threads using the multiprocessing package.
Here is our main program:
# main_program.pyfrom multiprocessing import Poolimport my_functionmy_list = [1,2,3,4,4,3,2,1]if __name__ == ‘__main__’: num_processors = 4 p = Pool(processes = num_processors) p.map_async(my_function.sleep_function, my_list).get()
And here is the function my_function which is parallelized across 4 threads:
# my_function.pyfrom time import sleepdef sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')
The output of this program will be:
The program slept for 1 seconds.The program slept for 2 seconds.The program slept for 3 seconds.The program slept for 4 seconds.The program slept for 4 seconds.The program slept for 3 seconds.The program slept for 2 seconds.The program slept for 1 seconds.
The first for 4 lines will appear 1, 2, 3, and 4 seconds after executing the program respectively. Because we’re using the map_async method, the remaining 4 lines will appear all at once after another 4 seconds have passed. The first thread waits 1 second and then takes the next available element from my_list, which is 4, and waits 4 more seconds (in total 5 seconds). The second thread waits 2 seconds, then takes the next available element from my_list, which is 3, and waits 3 more seconds (again 5 seconds in total) and so on.
Imagine we want to limit the time for which the sleep_function is allowed to run. Let’s say we set this timeout to 2.5 seconds. To do this, we have to make three changes to our program.
Apply a timeout decorator to the sleep_function.Carve out the timed-out sleep_function into a separate module.Change the my_function.py to execute this carved-out module.
Apply a timeout decorator to the sleep_function.
Carve out the timed-out sleep_function into a separate module.
Change the my_function.py to execute this carved-out module.
Here is how the carved-out module of the timed-out function will look like:
# my_timeout_function.pyfrom time import sleepfrom wrapt_timeout_decorator import *@timeout(2.5)def timeout_sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')
Using the @timeout decorator, we’ve set the limit for how long the function can run to 2.5 seconds. Apart from that, the code of the function remains unchanged.
Now we have to go back to our my_function.py module and call the newly created timeout_sleep_function from there:
# my_function.pyimport my_timeout_functiondef sleep_function(num): try: my_timeout_function.timeout_sleep_function(num) except: print('Timeout of 2.5 seconds reached!')
Because we have set a limit of 2.5 seconds for the timeout_sleep_function, the output of our main_program.py will now be:
The program slept for 1 seconds.The program slept for 2 seconds.Timeout of 2.5 seconds reached!Timeout of 2.5 seconds reached!The program slept for 1 seconds.Timeout of 2.5 seconds reached!The program slept for 2 seconds.Timeout of 2.5 seconds reached!
The timeout wrapper has changed the structure of our code as follows:
Main program main_program.py. This initializes the multiprocessing and calls the function sleep_function from the “in-between” module my_function.py. No actual changes to the code were made.The “in-between” module my_function.py. This calls the timed-out function timeout_sleep_function from the module my_timeout_function.py. Having this “in-between” module is necessary for Windows users.The module my_timeout_function.py that has the actual timed-out function timeout_sleep_function.
Main program main_program.py. This initializes the multiprocessing and calls the function sleep_function from the “in-between” module my_function.py. No actual changes to the code were made.
The “in-between” module my_function.py. This calls the timed-out function timeout_sleep_function from the module my_timeout_function.py. Having this “in-between” module is necessary for Windows users.
The module my_timeout_function.py that has the actual timed-out function timeout_sleep_function.
As you can see, using the wrapt_timeout_decorator to limit execution times of functions is relatively simple. I was able to add a timeout to my 10-K annual report section separator quickly without a lot of changes to the original code. This small addition, however, caused a major reduction in execution times.
Here is a final wrap-up of the example using the wrapt_timeout_decorator module:
#----------------------------# main_program.pyfrom multiprocessing import Poolimport my_function_timeoutmy_list = [1,2,3,4,4,3,2,1]if __name__ == '__main__': num_processors = 4 p = Pool(processes = num_processors) p.map_async(my_function.sleep_function, my_list).get()#----------------------------# my_function.pyimport my_timeout_functiondef sleep_function(num): try: my_timeout_function.timeout_sleep_function(num) except: print('Timeout of 2 seconds reached!')#----------------------------# my_timeout_function.pyfrom time import sleepfrom wrapt_timeout_decorator import *@timeout(2.5)def timeout_sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')
I hope this little guide will help you apply timeouts to functions in Python. | [
{
"code": null,
"e": 374,
"s": 172,
"text": "In this short guide, I will show how to use a handy timeout decorator for Python function to limit the execution times. This guide is based on an example that utilizes Python’s multiprocessing package."
},
{
"code": null,
"e": 1091,
"s": 374,
"text": "Lately, I’ve been building a script using Beautiful Soup that scrapes similarly structured websites and identifies its chapters. These were 10-K annual reports on the SEC’s website which had to be split according to their 21 sections. To make the script as robust as possible, I’ve used the simple, yet effective, python-constraint module to make sure that the sections were identified in the correct order. This approach worked perfectly in most cases and took less than a second to execute. Unfortunately, for some cases, the constraint function caused the script to run for days until it went through all iterations. By analyzing the execution times of the constraint function, I came to the following conclusion:"
},
{
"code": null,
"e": 1172,
"s": 1091,
"text": "Execution time = < 1 second, if there is a solution for the constraint function."
},
{
"code": null,
"e": 1257,
"s": 1172,
"text": "Execution time = hours or days, if there is no solution for the constraint function."
},
{
"code": null,
"e": 1484,
"s": 1257,
"text": "A fix for this issue was simple thanks to the wrapt_timeout_decorator module. The great thing about this module is that it’s easy to use, works great with Python’s multiprocessing module, and has no problem running on Windows."
},
{
"code": null,
"e": 1556,
"s": 1484,
"text": "You can install the wrapt_timeout_decorator module from PyPI using pip."
},
{
"code": null,
"e": 1592,
"s": 1556,
"text": "pip install wrapt_timeout_decorator"
},
{
"code": null,
"e": 1766,
"s": 1592,
"text": "If you’re using Conda, I suggest downloading the source files from GitHub (https://github.com/bitranox/wrapt_timeout_decorator) and installing the module manually by running"
},
{
"code": null,
"e": 1790,
"s": 1766,
"text": "python setup.py install"
},
{
"code": null,
"e": 1880,
"s": 1790,
"text": "within your active environment. You will need Python 3.5 or later for the module to work."
},
{
"code": null,
"e": 2276,
"s": 1880,
"text": "The following example is intended for Windows users. Linux users will have it easier using the wrapt_timeout_decorator because it’s not necessary to put the timeout function in a separate module. For more information on this, see the official documentation here. I haven’t tried this module in a Jupyter notebook, but I assume it will require a workaround similar to the multiprocessing package."
},
{
"code": null,
"e": 2413,
"s": 2276,
"text": "The example below shows how to apply a timeout on a function that is parallelized on multiple threads using the multiprocessing package."
},
{
"code": null,
"e": 2439,
"s": 2413,
"text": "Here is our main program:"
},
{
"code": null,
"e": 2680,
"s": 2439,
"text": "# main_program.pyfrom multiprocessing import Poolimport my_functionmy_list = [1,2,3,4,4,3,2,1]if __name__ == ‘__main__’: num_processors = 4 p = Pool(processes = num_processors) p.map_async(my_function.sleep_function, my_list).get()"
},
{
"code": null,
"e": 2757,
"s": 2680,
"text": "And here is the function my_function which is parallelized across 4 threads:"
},
{
"code": null,
"e": 2884,
"s": 2757,
"text": "# my_function.pyfrom time import sleepdef sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')"
},
{
"code": null,
"e": 2920,
"s": 2884,
"text": "The output of this program will be:"
},
{
"code": null,
"e": 3177,
"s": 2920,
"text": "The program slept for 1 seconds.The program slept for 2 seconds.The program slept for 3 seconds.The program slept for 4 seconds.The program slept for 4 seconds.The program slept for 3 seconds.The program slept for 2 seconds.The program slept for 1 seconds."
},
{
"code": null,
"e": 3710,
"s": 3177,
"text": "The first for 4 lines will appear 1, 2, 3, and 4 seconds after executing the program respectively. Because we’re using the map_async method, the remaining 4 lines will appear all at once after another 4 seconds have passed. The first thread waits 1 second and then takes the next available element from my_list, which is 4, and waits 4 more seconds (in total 5 seconds). The second thread waits 2 seconds, then takes the next available element from my_list, which is 3, and waits 3 more seconds (again 5 seconds in total) and so on."
},
{
"code": null,
"e": 3896,
"s": 3710,
"text": "Imagine we want to limit the time for which the sleep_function is allowed to run. Let’s say we set this timeout to 2.5 seconds. To do this, we have to make three changes to our program."
},
{
"code": null,
"e": 4067,
"s": 3896,
"text": "Apply a timeout decorator to the sleep_function.Carve out the timed-out sleep_function into a separate module.Change the my_function.py to execute this carved-out module."
},
{
"code": null,
"e": 4116,
"s": 4067,
"text": "Apply a timeout decorator to the sleep_function."
},
{
"code": null,
"e": 4179,
"s": 4116,
"text": "Carve out the timed-out sleep_function into a separate module."
},
{
"code": null,
"e": 4240,
"s": 4179,
"text": "Change the my_function.py to execute this carved-out module."
},
{
"code": null,
"e": 4316,
"s": 4240,
"text": "Here is how the carved-out module of the timed-out function will look like:"
},
{
"code": null,
"e": 4509,
"s": 4316,
"text": "# my_timeout_function.pyfrom time import sleepfrom wrapt_timeout_decorator import *@timeout(2.5)def timeout_sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')"
},
{
"code": null,
"e": 4670,
"s": 4509,
"text": "Using the @timeout decorator, we’ve set the limit for how long the function can run to 2.5 seconds. Apart from that, the code of the function remains unchanged."
},
{
"code": null,
"e": 4784,
"s": 4670,
"text": "Now we have to go back to our my_function.py module and call the newly created timeout_sleep_function from there:"
},
{
"code": null,
"e": 4973,
"s": 4784,
"text": "# my_function.pyimport my_timeout_functiondef sleep_function(num): try: my_timeout_function.timeout_sleep_function(num) except: print('Timeout of 2.5 seconds reached!')"
},
{
"code": null,
"e": 5095,
"s": 4973,
"text": "Because we have set a limit of 2.5 seconds for the timeout_sleep_function, the output of our main_program.py will now be:"
},
{
"code": null,
"e": 5348,
"s": 5095,
"text": "The program slept for 1 seconds.The program slept for 2 seconds.Timeout of 2.5 seconds reached!Timeout of 2.5 seconds reached!The program slept for 1 seconds.Timeout of 2.5 seconds reached!The program slept for 2 seconds.Timeout of 2.5 seconds reached!"
},
{
"code": null,
"e": 5418,
"s": 5348,
"text": "The timeout wrapper has changed the structure of our code as follows:"
},
{
"code": null,
"e": 5905,
"s": 5418,
"text": "Main program main_program.py. This initializes the multiprocessing and calls the function sleep_function from the “in-between” module my_function.py. No actual changes to the code were made.The “in-between” module my_function.py. This calls the timed-out function timeout_sleep_function from the module my_timeout_function.py. Having this “in-between” module is necessary for Windows users.The module my_timeout_function.py that has the actual timed-out function timeout_sleep_function."
},
{
"code": null,
"e": 6096,
"s": 5905,
"text": "Main program main_program.py. This initializes the multiprocessing and calls the function sleep_function from the “in-between” module my_function.py. No actual changes to the code were made."
},
{
"code": null,
"e": 6297,
"s": 6096,
"text": "The “in-between” module my_function.py. This calls the timed-out function timeout_sleep_function from the module my_timeout_function.py. Having this “in-between” module is necessary for Windows users."
},
{
"code": null,
"e": 6394,
"s": 6297,
"text": "The module my_timeout_function.py that has the actual timed-out function timeout_sleep_function."
},
{
"code": null,
"e": 6705,
"s": 6394,
"text": "As you can see, using the wrapt_timeout_decorator to limit execution times of functions is relatively simple. I was able to add a timeout to my 10-K annual report section separator quickly without a lot of changes to the original code. This small addition, however, caused a major reduction in execution times."
},
{
"code": null,
"e": 6786,
"s": 6705,
"text": "Here is a final wrap-up of the example using the wrapt_timeout_decorator module:"
},
{
"code": null,
"e": 7501,
"s": 6786,
"text": "#----------------------------# main_program.pyfrom multiprocessing import Poolimport my_function_timeoutmy_list = [1,2,3,4,4,3,2,1]if __name__ == '__main__': num_processors = 4 p = Pool(processes = num_processors) p.map_async(my_function.sleep_function, my_list).get()#----------------------------# my_function.pyimport my_timeout_functiondef sleep_function(num): try: my_timeout_function.timeout_sleep_function(num) except: print('Timeout of 2 seconds reached!')#----------------------------# my_timeout_function.pyfrom time import sleepfrom wrapt_timeout_decorator import *@timeout(2.5)def timeout_sleep_function(num): sleep(num) print(f'The program slept for {num} seconds.')"
}
] |
Print all permutations with repetition of characters - GeeksforGeeks | 12 May, 2022
Given a string of length n, print all permutations of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order
Examples:
Input: AB
Output: All permutations of AB with repetition are:
AA
AB
BA
BB
Input: ABC
Output: All permutations of ABC with repetition are:
AAA
AAB
AAC
ABA
...
...
CCB
CCC
For an input string of size n, there will be n^n permutations with repetition allowed. The idea is to fix the first character at first index and recursively call for other subsequent indexes. Once all permutations starting with the first character are printed, fix the second character at first index. Continue these steps till last character. Thanks to PsychoCoder for providing the following C implementation.
C++
C
Java
Python3
C#
Javascript
// C++ program to print all permutations// with repetition of characters#include <bits/stdc++.h>#include<string.h>using namespace std; /* Following function is used bythe library qsort() functionto sort an array of chars */int compare (const void * a, const void * b); /* The main function that recursivelyprints all repeated permutations ofthe given string. It uses data[] to store allpermutations one by one */void allLexicographicRecur (char *str, char* data, int last, int index){ int i, len = strlen(str); // One by one fix all characters at // the given index and recur for // the/ subsequent indexes for ( i = 0; i < len; i++ ) { // Fix the ith character at index // and if this is not the last // index then recursively call // for higher indexes data[index] = str[i] ; // If this is the last index then // print the string stored in // data[] if (index == last) cout << data << endl; else // Recur for higher indexes allLexicographicRecur (str, data, last, index+1); }} /* This function sorts input string,allocate memory for data (neededfor allLexicographicRecur()) andcalls allLexicographicRecur() forprinting all permutations */void allLexicographic(char *str){ int len = strlen (str) ; // Create a temp array that will // be used by allLexicographicRecur() char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\0'; // Sort the input string so that // we get all output strings in // lexicographically sorted order qsort(str, len, sizeof(char), compare); // Now print all permutations allLexicographicRecur (str, data, len-1, 0); // Free data to avoid memory leak free(data);} // Needed for library function qsort()int compare (const void * a, const void * b){ return ( *(char *)a - *(char *)b );} // Driver codeint main(){ char str[] = "ABC"; cout << "All permutations with repetition of "<< str <<" are: "<<endl ; allLexicographic(str); return 0;} // This code is contributed by rathbhupendra
// C program to print all permutations with repetition// of characters#include<stdio.h>#include<stdlib.h>#include<string.h> /* Following function is used by the library qsort() function to sort an array of chars */int compare (const void * a, const void * b); /* The main function that recursively prints all repeated permutations of the given string. It uses data[] to store all permutations one by one */void allLexicographicRecur (char *str, char* data, int last, int index){ int i, len = strlen(str); // One by one fix all characters at the given index and recur for // the/ subsequent indexes for ( i=0; i<len; i++ ) { // Fix the ith character at index and if this is not the last // index then recursively call for higher indexes data[index] = str[i] ; // If this is the last index then print the string stored in // data[] if (index == last) printf("%s\n", data); else // Recur for higher indexes allLexicographicRecur (str, data, last, index+1); }} /* This function sorts input string, allocate memory for data (needed for allLexicographicRecur()) and calls allLexicographicRecur() for printing all permutations */void allLexicographic(char *str){ int len = strlen (str) ; // Create a temp array that will be used by allLexicographicRecur() char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\0'; // Sort the input string so that we get all output strings in // lexicographically sorted order qsort(str, len, sizeof(char), compare); // Now print all permutations allLexicographicRecur (str, data, len-1, 0); // Free data to avoid memory leak free(data);} // Needed for library function qsort()int compare (const void * a, const void * b){ return ( *(char *)a - *(char *)b );} // Driver program to test above functionsint main(){ char str[] = "ABC"; printf("All permutations with repetition of %s are: \n", str); allLexicographic(str); return 0;}
// Java program to print all permutations// with repetition of charactersimport java.util.Arrays; class GFG{ // The main function that recursively prints // all repeated permutations of the given string. // It uses data[] to store all permutations one by one static void allLexicographicRecur(String str, char[] data, int last, int index) { int length = str.length(); // One by one fix all characters at the given index // and recur for the subsequent indexes for (int i = 0; i < length; i++) { // Fix the ith character at index and if // this is not the last index then // recursively call for higher indexes data[index] = str.charAt(i); // If this is the last index then print // the string stored in data[] if (index == last) System.out.println(new String(data)); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for printing all permutations static void allLexicographic(String str) { int length = str.length(); // Create a temp array that will be used by // allLexicographicRecur() char[] data = new char[length + 1]; char[] temp = str.toCharArray(); // Sort the input string so that we get all // output strings in lexicographically sorted order Arrays.sort(temp); str = new String(temp); // Now print all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver Code public static void main(String[] args) { String str = "ABC"; System.out.printf("All permutations with " + "repetition of %s are: \n", str); allLexicographic(str); }} // This code is contributed by// sanjeev2552
# Python program to print all permutations with repetition# of characters def toString(List): return ''.join(List) # The main function that recursively prints all repeated# permutations of the given string. It uses data[] to store# all permutations one by onedef allLexicographicRecur (string, data, last, index): length = len(string) # One by one fix all characters at the given index and # recur for the subsequent indexes for i in range(length): # Fix the ith character at index and if this is not # the last index then recursively call for higher # indexes data[index] = string[i] # If this is the last index then print the string # stored in data[] if index==last: print (toString(data)) else: allLexicographicRecur(string, data, last, index+1) # This function sorts input string, allocate memory for data# (needed for allLexicographicRecur()) and calls# allLexicographicRecur() for printing all permutationsdef allLexicographic(string): length = len(string) # Create a temp array that will be used by # allLexicographicRecur() data = [""] * (length+1) # Sort the input string so that we get all output strings in # lexicographically sorted order string = sorted(string) # Now print all permutations allLexicographicRecur(string, data, length-1, 0) # Driver program to test the above functionsstring = "ABC"print ("All permutations with repetition of " + string + " are:")allLexicographic(string) # This code is contributed to Bhavya Jain
// C# program to print all permutations// with repetition of charactersusing System; public class GFG{ // The main function that recursively prints // all repeated permutations of the given string. // It uses data[] to store all permutations one by one static void allLexicographicRecur(String str, char[] data, int last, int index) { int length = str.Length; // One by one fix all characters at the given index // and recur for the subsequent indexes for (int i = 0; i < length; i++) { // Fix the ith character at index and if // this is not the last index then // recursively call for higher indexes data[index] = str[i]; // If this is the last index then print // the string stored in data[] if (index == last) Console.WriteLine(new String(data)); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for printing all permutations static void allLexicographic(String str) { int length = str.Length; // Create a temp array that will be used by // allLexicographicRecur() char[] data = new char[length + 1]; char[] temp = str.ToCharArray(); // Sort the input string so that we get all // output strings in lexicographically sorted order Array.Sort(temp); str = new String(temp); // Now print all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver Code public static void Main(String[] args) { String str = "ABC"; Console.Write("All permutations with " + "repetition of {0} are: \n", str); allLexicographic(str); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript code to implement the approach // The main function that recursively prlets // all repeated permutations of the given string. // It uses data[] to store all permutations one by one function allLexicographicRecur(str, data, last, index) { let length = str.length; // One by one fix all letacters at the given index // and recur for the subsequent indexes for (let i = 0; i < length; i++) { // Fix the ith letacter at index and if // this is not the last index then // recursively call for higher indexes data[index] = str[i]; // If this is the last index then prlet // the string stored in data[] if (index == last) document.write(new String(data) + "<br/>"); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for prleting all permutations function allLexicographic(str) { let length = str.length; // Create a temp array that will be used by // allLexicographicRecur() let data = new Array(length + 1); let temp = str.split(); // Sort the input string so that we get all // output strings in lexicographically sorted order temp.sort(); str = new String(temp); // Now prlet all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver code let str = "ABC"; document.write("All permutations with " + "repetition of " + str + " are " + "<br/>"); allLexicographic(str); // This code is contributed by sanjoy_62.</script>
Output:
All permutations with repetition of ABC are:
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
Fundamentals of Programming with C Free Online Course By GeeksforGeeksFollowing is recursion tree for input string “AB”. The purpose of recursion tree is to help in understanding the above implementation as it shows values of different variables.
data=""
/ \
/ \
index=0 index=0
i=0 i=1
data="A" data="B"
/ \ / \
/ \ / \
index=1 index=1 index=1 index=1
i=0 i=1 i=0 i=1
data="AA" data="AB" data="BA" data="BB"
In the above implementation, it is assumed that all characters of the input string are different. The implementation can be easily modified to handle the repeated characters. We have to add a preprocessing step to find unique characters (before calling allLexicographicRecur()).Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
sanjeev2552
princiraj1992
Akanksha_Rai
simmytarika5
amartyaghoshgfg
sanjoy_62
permutation
Combinatorial
Strings
Strings
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 26721,
"s": 26693,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26890,
"s": 26721,
"text": "Given a string of length n, print all permutations of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order "
},
{
"code": null,
"e": 26901,
"s": 26890,
"text": "Examples: "
},
{
"code": null,
"e": 27152,
"s": 26901,
"text": "Input: AB\nOutput: All permutations of AB with repetition are:\n AA\n AB\n BA\n BB\n\nInput: ABC\nOutput: All permutations of ABC with repetition are:\n AAA\n AAB\n AAC\n ABA\n ...\n ...\n CCB\n CCC"
},
{
"code": null,
"e": 27566,
"s": 27152,
"text": "For an input string of size n, there will be n^n permutations with repetition allowed. The idea is to fix the first character at first index and recursively call for other subsequent indexes. Once all permutations starting with the first character are printed, fix the second character at first index. Continue these steps till last character. Thanks to PsychoCoder for providing the following C implementation. "
},
{
"code": null,
"e": 27570,
"s": 27566,
"text": "C++"
},
{
"code": null,
"e": 27572,
"s": 27570,
"text": "C"
},
{
"code": null,
"e": 27577,
"s": 27572,
"text": "Java"
},
{
"code": null,
"e": 27585,
"s": 27577,
"text": "Python3"
},
{
"code": null,
"e": 27588,
"s": 27585,
"text": "C#"
},
{
"code": null,
"e": 27599,
"s": 27588,
"text": "Javascript"
},
{
"code": "// C++ program to print all permutations// with repetition of characters#include <bits/stdc++.h>#include<string.h>using namespace std; /* Following function is used bythe library qsort() functionto sort an array of chars */int compare (const void * a, const void * b); /* The main function that recursivelyprints all repeated permutations ofthe given string. It uses data[] to store allpermutations one by one */void allLexicographicRecur (char *str, char* data, int last, int index){ int i, len = strlen(str); // One by one fix all characters at // the given index and recur for // the/ subsequent indexes for ( i = 0; i < len; i++ ) { // Fix the ith character at index // and if this is not the last // index then recursively call // for higher indexes data[index] = str[i] ; // If this is the last index then // print the string stored in // data[] if (index == last) cout << data << endl; else // Recur for higher indexes allLexicographicRecur (str, data, last, index+1); }} /* This function sorts input string,allocate memory for data (neededfor allLexicographicRecur()) andcalls allLexicographicRecur() forprinting all permutations */void allLexicographic(char *str){ int len = strlen (str) ; // Create a temp array that will // be used by allLexicographicRecur() char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\\0'; // Sort the input string so that // we get all output strings in // lexicographically sorted order qsort(str, len, sizeof(char), compare); // Now print all permutations allLexicographicRecur (str, data, len-1, 0); // Free data to avoid memory leak free(data);} // Needed for library function qsort()int compare (const void * a, const void * b){ return ( *(char *)a - *(char *)b );} // Driver codeint main(){ char str[] = \"ABC\"; cout << \"All permutations with repetition of \"<< str <<\" are: \"<<endl ; allLexicographic(str); return 0;} // This code is contributed by rathbhupendra",
"e": 29756,
"s": 27599,
"text": null
},
{
"code": "// C program to print all permutations with repetition// of characters#include<stdio.h>#include<stdlib.h>#include<string.h> /* Following function is used by the library qsort() function to sort an array of chars */int compare (const void * a, const void * b); /* The main function that recursively prints all repeated permutations of the given string. It uses data[] to store all permutations one by one */void allLexicographicRecur (char *str, char* data, int last, int index){ int i, len = strlen(str); // One by one fix all characters at the given index and recur for // the/ subsequent indexes for ( i=0; i<len; i++ ) { // Fix the ith character at index and if this is not the last // index then recursively call for higher indexes data[index] = str[i] ; // If this is the last index then print the string stored in // data[] if (index == last) printf(\"%s\\n\", data); else // Recur for higher indexes allLexicographicRecur (str, data, last, index+1); }} /* This function sorts input string, allocate memory for data (needed for allLexicographicRecur()) and calls allLexicographicRecur() for printing all permutations */void allLexicographic(char *str){ int len = strlen (str) ; // Create a temp array that will be used by allLexicographicRecur() char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\\0'; // Sort the input string so that we get all output strings in // lexicographically sorted order qsort(str, len, sizeof(char), compare); // Now print all permutations allLexicographicRecur (str, data, len-1, 0); // Free data to avoid memory leak free(data);} // Needed for library function qsort()int compare (const void * a, const void * b){ return ( *(char *)a - *(char *)b );} // Driver program to test above functionsint main(){ char str[] = \"ABC\"; printf(\"All permutations with repetition of %s are: \\n\", str); allLexicographic(str); return 0;}",
"e": 31795,
"s": 29756,
"text": null
},
{
"code": "// Java program to print all permutations// with repetition of charactersimport java.util.Arrays; class GFG{ // The main function that recursively prints // all repeated permutations of the given string. // It uses data[] to store all permutations one by one static void allLexicographicRecur(String str, char[] data, int last, int index) { int length = str.length(); // One by one fix all characters at the given index // and recur for the subsequent indexes for (int i = 0; i < length; i++) { // Fix the ith character at index and if // this is not the last index then // recursively call for higher indexes data[index] = str.charAt(i); // If this is the last index then print // the string stored in data[] if (index == last) System.out.println(new String(data)); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for printing all permutations static void allLexicographic(String str) { int length = str.length(); // Create a temp array that will be used by // allLexicographicRecur() char[] data = new char[length + 1]; char[] temp = str.toCharArray(); // Sort the input string so that we get all // output strings in lexicographically sorted order Arrays.sort(temp); str = new String(temp); // Now print all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver Code public static void main(String[] args) { String str = \"ABC\"; System.out.printf(\"All permutations with \" + \"repetition of %s are: \\n\", str); allLexicographic(str); }} // This code is contributed by// sanjeev2552",
"e": 33858,
"s": 31795,
"text": null
},
{
"code": "# Python program to print all permutations with repetition# of characters def toString(List): return ''.join(List) # The main function that recursively prints all repeated# permutations of the given string. It uses data[] to store# all permutations one by onedef allLexicographicRecur (string, data, last, index): length = len(string) # One by one fix all characters at the given index and # recur for the subsequent indexes for i in range(length): # Fix the ith character at index and if this is not # the last index then recursively call for higher # indexes data[index] = string[i] # If this is the last index then print the string # stored in data[] if index==last: print (toString(data)) else: allLexicographicRecur(string, data, last, index+1) # This function sorts input string, allocate memory for data# (needed for allLexicographicRecur()) and calls# allLexicographicRecur() for printing all permutationsdef allLexicographic(string): length = len(string) # Create a temp array that will be used by # allLexicographicRecur() data = [\"\"] * (length+1) # Sort the input string so that we get all output strings in # lexicographically sorted order string = sorted(string) # Now print all permutations allLexicographicRecur(string, data, length-1, 0) # Driver program to test the above functionsstring = \"ABC\"print (\"All permutations with repetition of \" + string + \" are:\")allLexicographic(string) # This code is contributed to Bhavya Jain",
"e": 35428,
"s": 33858,
"text": null
},
{
"code": " // C# program to print all permutations// with repetition of charactersusing System; public class GFG{ // The main function that recursively prints // all repeated permutations of the given string. // It uses data[] to store all permutations one by one static void allLexicographicRecur(String str, char[] data, int last, int index) { int length = str.Length; // One by one fix all characters at the given index // and recur for the subsequent indexes for (int i = 0; i < length; i++) { // Fix the ith character at index and if // this is not the last index then // recursively call for higher indexes data[index] = str[i]; // If this is the last index then print // the string stored in data[] if (index == last) Console.WriteLine(new String(data)); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for printing all permutations static void allLexicographic(String str) { int length = str.Length; // Create a temp array that will be used by // allLexicographicRecur() char[] data = new char[length + 1]; char[] temp = str.ToCharArray(); // Sort the input string so that we get all // output strings in lexicographically sorted order Array.Sort(temp); str = new String(temp); // Now print all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver Code public static void Main(String[] args) { String str = \"ABC\"; Console.Write(\"All permutations with \" + \"repetition of {0} are: \\n\", str); allLexicographic(str); }} // This code is contributed by PrinciRaj1992",
"e": 37483,
"s": 35428,
"text": null
},
{
"code": "<script> // JavaScript code to implement the approach // The main function that recursively prlets // all repeated permutations of the given string. // It uses data[] to store all permutations one by one function allLexicographicRecur(str, data, last, index) { let length = str.length; // One by one fix all letacters at the given index // and recur for the subsequent indexes for (let i = 0; i < length; i++) { // Fix the ith letacter at index and if // this is not the last index then // recursively call for higher indexes data[index] = str[i]; // If this is the last index then prlet // the string stored in data[] if (index == last) document.write(new String(data) + \"<br/>\"); else allLexicographicRecur(str, data, last, index + 1); } } // This function sorts input string, allocate memory // for data(needed for allLexicographicRecur()) and calls // allLexicographicRecur() for prleting all permutations function allLexicographic(str) { let length = str.length; // Create a temp array that will be used by // allLexicographicRecur() let data = new Array(length + 1); let temp = str.split(); // Sort the input string so that we get all // output strings in lexicographically sorted order temp.sort(); str = new String(temp); // Now prlet all permutations allLexicographicRecur(str, data, length - 1, 0); } // Driver code let str = \"ABC\"; document.write(\"All permutations with \" + \"repetition of \" + str + \" are \" + \"<br/>\"); allLexicographic(str); // This code is contributed by sanjoy_62.</script>",
"e": 39355,
"s": 37483,
"text": null
},
{
"code": null,
"e": 39364,
"s": 39355,
"text": "Output: "
},
{
"code": null,
"e": 39518,
"s": 39364,
"text": "All permutations with repetition of ABC are: \nAAA\nAAB\nAAC\nABA\nABB\nABC\nACA\nACB\nACC\nBAA\nBAB\nBAC\nBBA\nBBB\nBBC\nBCA\nBCB\nBCC\nCAA\nCAB\nCAC\nCBA\nCBB\nCBC\nCCA\nCCB\nCCC"
},
{
"code": null,
"e": 39766,
"s": 39518,
"text": "Fundamentals of Programming with C Free Online Course By GeeksforGeeksFollowing is recursion tree for input string “AB”. The purpose of recursion tree is to help in understanding the above implementation as it shows values of different variables. "
},
{
"code": null,
"e": 40268,
"s": 39766,
"text": " data=\"\" \n / \\\n / \\ \n index=0 index=0\n i=0 i=1 \n data=\"A\" data=\"B\"\n / \\ / \\\n / \\ / \\\n index=1 index=1 index=1 index=1 \n i=0 i=1 i=0 i=1 \n data=\"AA\" data=\"AB\" data=\"BA\" data=\"BB\""
},
{
"code": null,
"e": 40672,
"s": 40268,
"text": "In the above implementation, it is assumed that all characters of the input string are different. The implementation can be easily modified to handle the repeated characters. We have to add a preprocessing step to find unique characters (before calling allLexicographicRecur()).Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40686,
"s": 40672,
"text": "rathbhupendra"
},
{
"code": null,
"e": 40698,
"s": 40686,
"text": "sanjeev2552"
},
{
"code": null,
"e": 40712,
"s": 40698,
"text": "princiraj1992"
},
{
"code": null,
"e": 40725,
"s": 40712,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 40738,
"s": 40725,
"text": "simmytarika5"
},
{
"code": null,
"e": 40754,
"s": 40738,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 40764,
"s": 40754,
"text": "sanjoy_62"
},
{
"code": null,
"e": 40776,
"s": 40764,
"text": "permutation"
},
{
"code": null,
"e": 40790,
"s": 40776,
"text": "Combinatorial"
},
{
"code": null,
"e": 40798,
"s": 40790,
"text": "Strings"
},
{
"code": null,
"e": 40806,
"s": 40798,
"text": "Strings"
},
{
"code": null,
"e": 40818,
"s": 40806,
"text": "permutation"
},
{
"code": null,
"e": 40832,
"s": 40818,
"text": "Combinatorial"
},
{
"code": null,
"e": 40930,
"s": 40832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41002,
"s": 40930,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 41065,
"s": 41002,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 41095,
"s": 41065,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 41134,
"s": 41095,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 41212,
"s": 41134,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 41258,
"s": 41212,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 41283,
"s": 41258,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 41298,
"s": 41283,
"text": "C++ Data Types"
},
{
"code": null,
"e": 41332,
"s": 41298,
"text": "Longest Common Subsequence | DP-4"
}
] |
Create a Cycle Graph using Networkx in Python - GeeksforGeeks | 03 Jan, 2021
A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified.
Number of nodes in a Cycle Graph(Cn) are equal to N.
Number of edges in a Cycle Graph(Cn) are equal to N.
Every node is connected to 2 edges hence degree of each node is 2.
It is a Hamiltonian Graph.
It is a Connected Graph.
Even after removal of one edge it remains connected as it is cyclic.
We can simply obtain cycle graph by joining the initial an final node of a path graph.
We will use the networkx module for realizing a Cycle graph. This module in python is used for visualizing and analyzing different kind of graphs for most of which the generators are predefined in this library.
It comes with an inbuilt function networkx.cycle_graph() and can be illustrated using the networkx.draw() method.
draw()-This function is used to draw the required graph using networkx module.
Syntax:
networkx.draw(G, node_size, node_color)
Parameters:
G: It refers to the Cycle graph object it is passed so that draw method knows exactly which graph is to be printed.
node_size: It refers to the size of nodes.
node_color: It refers to color of the nodes.
cycle_graph()- This function is used to create a cycle graph, it gives all the required information for creating one.
Syntax:
networkx.cycle_graph(n)
Parameters:
n: This parameter is used to specify the number of nodes in the cycle graph.
Returns:
This method returns Cn (Cycle graph with n nodes). Therefore it is used to initialize the graph object G.
Import module
Create cycle graph object using cycle_graph() constructor
Use nx.draw() function
Display plot
Program:
Python3
# import required moduleimport networkx # create objectG = networkx.cycle_graph(8) # illustrate graphnetworkx.draw(G, node_size=150, node_color='green')
OUTPUT:
Output
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Path in a Directed Acyclic Graph
Best First Search (Informed Search)
Graph Coloring | Set 2 (Greedy Algorithm)
Maximum Bipartite Matching
Graph Coloring | Set 1 (Introduction and Applications)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 26311,
"s": 26283,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 26471,
"s": 26311,
"text": "A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified."
},
{
"code": null,
"e": 26524,
"s": 26471,
"text": "Number of nodes in a Cycle Graph(Cn) are equal to N."
},
{
"code": null,
"e": 26577,
"s": 26524,
"text": "Number of edges in a Cycle Graph(Cn) are equal to N."
},
{
"code": null,
"e": 26644,
"s": 26577,
"text": "Every node is connected to 2 edges hence degree of each node is 2."
},
{
"code": null,
"e": 26671,
"s": 26644,
"text": "It is a Hamiltonian Graph."
},
{
"code": null,
"e": 26696,
"s": 26671,
"text": "It is a Connected Graph."
},
{
"code": null,
"e": 26765,
"s": 26696,
"text": "Even after removal of one edge it remains connected as it is cyclic."
},
{
"code": null,
"e": 26852,
"s": 26765,
"text": "We can simply obtain cycle graph by joining the initial an final node of a path graph."
},
{
"code": null,
"e": 27063,
"s": 26852,
"text": "We will use the networkx module for realizing a Cycle graph. This module in python is used for visualizing and analyzing different kind of graphs for most of which the generators are predefined in this library."
},
{
"code": null,
"e": 27177,
"s": 27063,
"text": "It comes with an inbuilt function networkx.cycle_graph() and can be illustrated using the networkx.draw() method."
},
{
"code": null,
"e": 27256,
"s": 27177,
"text": "draw()-This function is used to draw the required graph using networkx module."
},
{
"code": null,
"e": 27264,
"s": 27256,
"text": "Syntax:"
},
{
"code": null,
"e": 27304,
"s": 27264,
"text": "networkx.draw(G, node_size, node_color)"
},
{
"code": null,
"e": 27316,
"s": 27304,
"text": "Parameters:"
},
{
"code": null,
"e": 27432,
"s": 27316,
"text": "G: It refers to the Cycle graph object it is passed so that draw method knows exactly which graph is to be printed."
},
{
"code": null,
"e": 27475,
"s": 27432,
"text": "node_size: It refers to the size of nodes."
},
{
"code": null,
"e": 27520,
"s": 27475,
"text": "node_color: It refers to color of the nodes."
},
{
"code": null,
"e": 27638,
"s": 27520,
"text": "cycle_graph()- This function is used to create a cycle graph, it gives all the required information for creating one."
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Syntax:"
},
{
"code": null,
"e": 27670,
"s": 27646,
"text": "networkx.cycle_graph(n)"
},
{
"code": null,
"e": 27682,
"s": 27670,
"text": "Parameters:"
},
{
"code": null,
"e": 27759,
"s": 27682,
"text": "n: This parameter is used to specify the number of nodes in the cycle graph."
},
{
"code": null,
"e": 27768,
"s": 27759,
"text": "Returns:"
},
{
"code": null,
"e": 27874,
"s": 27768,
"text": "This method returns Cn (Cycle graph with n nodes). Therefore it is used to initialize the graph object G."
},
{
"code": null,
"e": 27888,
"s": 27874,
"text": "Import module"
},
{
"code": null,
"e": 27946,
"s": 27888,
"text": "Create cycle graph object using cycle_graph() constructor"
},
{
"code": null,
"e": 27969,
"s": 27946,
"text": "Use nx.draw() function"
},
{
"code": null,
"e": 27982,
"s": 27969,
"text": "Display plot"
},
{
"code": null,
"e": 27991,
"s": 27982,
"text": "Program:"
},
{
"code": null,
"e": 27999,
"s": 27991,
"text": "Python3"
},
{
"code": "# import required moduleimport networkx # create objectG = networkx.cycle_graph(8) # illustrate graphnetworkx.draw(G, node_size=150, node_color='green')",
"e": 28154,
"s": 27999,
"text": null
},
{
"code": null,
"e": 28162,
"s": 28154,
"text": "OUTPUT:"
},
{
"code": null,
"e": 28169,
"s": 28162,
"text": "Output"
},
{
"code": null,
"e": 28175,
"s": 28169,
"text": "Graph"
},
{
"code": null,
"e": 28182,
"s": 28175,
"text": "Python"
},
{
"code": null,
"e": 28188,
"s": 28182,
"text": "Graph"
},
{
"code": null,
"e": 28286,
"s": 28188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28327,
"s": 28286,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 28363,
"s": 28327,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 28405,
"s": 28363,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 28432,
"s": 28405,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 28487,
"s": 28432,
"text": "Graph Coloring | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 28515,
"s": 28487,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28565,
"s": 28515,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28587,
"s": 28565,
"text": "Python map() function"
}
] |
Encrypt and Decrypt Files using Python - GeeksforGeeks | 13 Jan, 2021
Encryption is the act of decoding the message so that intended users can only see it. We encrypt data because we don’t want anyone to see or access it.
We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric algorithm, we use the same key to encrypt and decrypt the file. The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plain text into cipher text, and decryption of cipher text into plain text using the encrypt() and decrypt() methods respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read without the key.
We are going to use the nba.csv file to perform all operations.
The cryptography library can be installed using the below command:
pip install cryptography
In the cryptography library, there is a cryptography algorithm called fernet. We will use the fernet module to encrypt the file.
Python3
# import required modulefrom cryptography.fernet import Fernet
Generating the key and saving it:
Python3
# key generationkey = Fernet.generate_key() # string the key in a filewith open('filekey.key', 'wb') as filekey: filekey.write(key)
Above code will generate a file with the name filekey.key. The file will contain one line, which is a string acting as a key i.e. J64ZHFpCWFlS9zT7y5zxuQN1Gb09y7cucne_EhuWyDM=
Now we have an encrypted key and file to be encrypted. Now write code to encrypt this file:
Open the file that contains the key.Initialize the Fernet object and store it in the fernet variable.Read the original file.Encrypt the file and store it into an object.Then write the encrypted data into the same file nba.csv.
Open the file that contains the key.
Initialize the Fernet object and store it in the fernet variable.
Read the original file.
Encrypt the file and store it into an object.
Then write the encrypted data into the same file nba.csv.
Python3
# opening the keywith open('filekey.key', 'rb') as filekey: key = filekey.read() # using the generated keyfernet = Fernet(key) # opening the original file to encryptwith open('nba.csv', 'rb') as file: original = file.read() # encrypting the fileencrypted = fernet.encrypt(original) # opening the file in write mode and # writing the encrypted datawith open('nba.csv', 'wb') as encrypted_file: encrypted_file.write(encrypted)
The nba.csv file before executing the above program:
The nba.csv file after executing the above program:
We have to use the same key to decrypt the file:
Initialize the Fernet object and store it in the fernet variable.Read the encrypted file.Decrypt the file and store it into an object.Then write the decrypted data into the same file nba.csv.
Initialize the Fernet object and store it in the fernet variable.
Read the encrypted file.
Decrypt the file and store it into an object.
Then write the decrypted data into the same file nba.csv.
Python3
# using the keyfernet = Fernet(key) # opening the encrypted filewith open('nba.csv', 'rb') as enc_file: encrypted = enc_file.read() # decrypting the filedecrypted = fernet.decrypt(encrypted) # opening the file in write mode and# writing the decrypted datawith open('nba.csv', 'wb') as dec_file: dec_file.write(decrypted)
The nba.csv file before executing the above program:
The nba.csv file after executing the above program:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 25713,
"s": 25561,
"text": "Encryption is the act of decoding the message so that intended users can only see it. We encrypt data because we don’t want anyone to see or access it."
},
{
"code": null,
"e": 26281,
"s": 25713,
"text": "We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric algorithm, we use the same key to encrypt and decrypt the file. The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plain text into cipher text, and decryption of cipher text into plain text using the encrypt() and decrypt() methods respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read without the key. "
},
{
"code": null,
"e": 26345,
"s": 26281,
"text": "We are going to use the nba.csv file to perform all operations."
},
{
"code": null,
"e": 26412,
"s": 26345,
"text": "The cryptography library can be installed using the below command:"
},
{
"code": null,
"e": 26437,
"s": 26412,
"text": "pip install cryptography"
},
{
"code": null,
"e": 26566,
"s": 26437,
"text": "In the cryptography library, there is a cryptography algorithm called fernet. We will use the fernet module to encrypt the file."
},
{
"code": null,
"e": 26574,
"s": 26566,
"text": "Python3"
},
{
"code": "# import required modulefrom cryptography.fernet import Fernet",
"e": 26637,
"s": 26574,
"text": null
},
{
"code": null,
"e": 26671,
"s": 26637,
"text": "Generating the key and saving it:"
},
{
"code": null,
"e": 26679,
"s": 26671,
"text": "Python3"
},
{
"code": "# key generationkey = Fernet.generate_key() # string the key in a filewith open('filekey.key', 'wb') as filekey: filekey.write(key)",
"e": 26814,
"s": 26679,
"text": null
},
{
"code": null,
"e": 26989,
"s": 26814,
"text": "Above code will generate a file with the name filekey.key. The file will contain one line, which is a string acting as a key i.e. J64ZHFpCWFlS9zT7y5zxuQN1Gb09y7cucne_EhuWyDM="
},
{
"code": null,
"e": 27081,
"s": 26989,
"text": "Now we have an encrypted key and file to be encrypted. Now write code to encrypt this file:"
},
{
"code": null,
"e": 27308,
"s": 27081,
"text": "Open the file that contains the key.Initialize the Fernet object and store it in the fernet variable.Read the original file.Encrypt the file and store it into an object.Then write the encrypted data into the same file nba.csv."
},
{
"code": null,
"e": 27345,
"s": 27308,
"text": "Open the file that contains the key."
},
{
"code": null,
"e": 27411,
"s": 27345,
"text": "Initialize the Fernet object and store it in the fernet variable."
},
{
"code": null,
"e": 27435,
"s": 27411,
"text": "Read the original file."
},
{
"code": null,
"e": 27481,
"s": 27435,
"text": "Encrypt the file and store it into an object."
},
{
"code": null,
"e": 27539,
"s": 27481,
"text": "Then write the encrypted data into the same file nba.csv."
},
{
"code": null,
"e": 27547,
"s": 27539,
"text": "Python3"
},
{
"code": "# opening the keywith open('filekey.key', 'rb') as filekey: key = filekey.read() # using the generated keyfernet = Fernet(key) # opening the original file to encryptwith open('nba.csv', 'rb') as file: original = file.read() # encrypting the fileencrypted = fernet.encrypt(original) # opening the file in write mode and # writing the encrypted datawith open('nba.csv', 'wb') as encrypted_file: encrypted_file.write(encrypted)",
"e": 27989,
"s": 27547,
"text": null
},
{
"code": null,
"e": 28042,
"s": 27989,
"text": "The nba.csv file before executing the above program:"
},
{
"code": null,
"e": 28094,
"s": 28042,
"text": "The nba.csv file after executing the above program:"
},
{
"code": null,
"e": 28143,
"s": 28094,
"text": "We have to use the same key to decrypt the file:"
},
{
"code": null,
"e": 28335,
"s": 28143,
"text": "Initialize the Fernet object and store it in the fernet variable.Read the encrypted file.Decrypt the file and store it into an object.Then write the decrypted data into the same file nba.csv."
},
{
"code": null,
"e": 28401,
"s": 28335,
"text": "Initialize the Fernet object and store it in the fernet variable."
},
{
"code": null,
"e": 28426,
"s": 28401,
"text": "Read the encrypted file."
},
{
"code": null,
"e": 28472,
"s": 28426,
"text": "Decrypt the file and store it into an object."
},
{
"code": null,
"e": 28530,
"s": 28472,
"text": "Then write the decrypted data into the same file nba.csv."
},
{
"code": null,
"e": 28538,
"s": 28530,
"text": "Python3"
},
{
"code": "# using the keyfernet = Fernet(key) # opening the encrypted filewith open('nba.csv', 'rb') as enc_file: encrypted = enc_file.read() # decrypting the filedecrypted = fernet.decrypt(encrypted) # opening the file in write mode and# writing the decrypted datawith open('nba.csv', 'wb') as dec_file: dec_file.write(decrypted)",
"e": 28868,
"s": 28538,
"text": null
},
{
"code": null,
"e": 28921,
"s": 28868,
"text": "The nba.csv file before executing the above program:"
},
{
"code": null,
"e": 28973,
"s": 28921,
"text": "The nba.csv file after executing the above program:"
},
{
"code": null,
"e": 28980,
"s": 28973,
"text": "Picked"
},
{
"code": null,
"e": 28995,
"s": 28980,
"text": "python-utility"
},
{
"code": null,
"e": 29002,
"s": 28995,
"text": "Python"
},
{
"code": null,
"e": 29100,
"s": 29002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29122,
"s": 29100,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29154,
"s": 29122,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29170,
"s": 29154,
"text": "Deque in Python"
},
{
"code": null,
"e": 29193,
"s": 29170,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 29235,
"s": 29193,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29265,
"s": 29235,
"text": "Python math function | sqrt()"
},
{
"code": null,
"e": 29292,
"s": 29265,
"text": "Python | Output Formatting"
},
{
"code": null,
"e": 29327,
"s": 29292,
"text": "Python - Pandas dataframe.append()"
},
{
"code": null,
"e": 29383,
"s": 29327,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Print elements of an array according to the order defined by another array | set 2 - GeeksforGeeks | 28 Jun, 2021
Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at last in sorted order. It is also given that the number of elements in a2[] is smaller than or equal to the number of elements in a1[], and a2[] has all distinct elements.Example:
Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} a2[] = {2, 1, 8, 3} Output: 2 2 1 1 8 8 3 5 6 7 9Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} a2[] = {1, 10, 11} Output: 1 1 2 2 3 5 6 7 8 8 9
Simple Approach: We create a temporary array and a visited array where the temporary array is used to copy contents of a1[] to it and visited array is used to mark those elements in the temporary array which are copied to a1[]. Then sorting the temporary array and doing a binary search for every element of a2[] in a1[]. You can find the solution here.Efficient Approach: We can print the elements of a1[] according to the order defined by a2[] using map in c++ in O(mlog(n)) time. We traverse through a1[] and store the frequency of every number in a map. Then we traverse through a2[] and check if the number is present in the map. If the number is present, then print it that many times and erase the number from the map. Print the rest of the numbers present in the map sequentially as numbers are stored in the map in sorted order.Below is the implementation of the above approach:
C++
Python3
// A C++ program to print an array according// to the order defined by another array#include <bits/stdc++.h>using namespace std; // Function to print an array according// to the order defined by another arrayvoid print_in_order(int a1[], int a2[], int n, int m){ // Declaring map and iterator map<int, int> mp; map<int, int>::iterator itr; // Store the frequency of each // number of a1[] int the map for (int i = 0; i < n; i++) mp[a1[i]]++; // Traverse through a2[] for (int i = 0; i < m; i++) { // Check whether number // is present in map or not if (mp.find(a2[i]) != mp.end()) { itr = mp.find(a2[i]); // Print that number that // many times of its frequency for (int j = 0; j < itr->second; j++) cout << itr->first << " "; mp.erase(a2[i]); } } // Print those numbers that are not // present in a2[] for (itr = mp.begin(); itr != mp.end(); itr++) { for (int j = 0; j < itr->second; j++) cout << itr->first << " "; } cout << endl;} // Driver codeint main(){ int a1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int a2[] = { 2, 1, 8, 3 }; int n = sizeof(a1) / sizeof(a1[0]); int m = sizeof(a2) / sizeof(a2[0]); print_in_order(a1, a2, n, m); return 0;}
# A Python3 program to print an array according# to the order defined by another array # Function to print an array according# to the order defined by another arraydef print_in_order(a1, a2, n, m) : # Declaring map and iterator mp = dict.fromkeys(a1,0); # Store the frequency of each # number of a1[] int the map for i in range(n) : mp[a1[i]] += 1; # Traverse through a2[] for i in range(m) : # Check whether number # is present in map or not if a2[i] in mp.keys() : # Print that number that # many times of its frequency for j in range(mp[a2[i]]) : print(a2[i],end=" "); del(mp[a2[i]]); # Print those numbers that are not # present in a2[] for key,value in mp.items() : for j in range(value) : print(key,end=" "); print(); # Driver codeif __name__ == "__main__" : a1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ]; a2 = [ 2, 1, 8, 3 ]; n =len(a1); m = len(a2); print_in_order(a1, a2, n, m); # This code is contributed by AnkitRai01
2 2 1 1 8 8 3 5 6 7 9
ankthon
surinderdawra388
cpp-map
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Bridge and Torch problem
Window Sliding Technique
Binary Tree (Array implementation)
Segment Tree | Set 1 (Sum of given range)
MSD( Most Significant Digit ) Radix Sort | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26548,
"s": 26067,
"text": "Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at last in sorted order. It is also given that the number of elements in a2[] is smaller than or equal to the number of elements in a1[], and a2[] has all distinct elements.Example: "
},
{
"code": null,
"e": 26744,
"s": 26548,
"text": "Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} a2[] = {2, 1, 8, 3} Output: 2 2 1 1 8 8 3 5 6 7 9Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} a2[] = {1, 10, 11} Output: 1 1 2 2 3 5 6 7 8 8 9 "
},
{
"code": null,
"e": 27636,
"s": 26746,
"text": "Simple Approach: We create a temporary array and a visited array where the temporary array is used to copy contents of a1[] to it and visited array is used to mark those elements in the temporary array which are copied to a1[]. Then sorting the temporary array and doing a binary search for every element of a2[] in a1[]. You can find the solution here.Efficient Approach: We can print the elements of a1[] according to the order defined by a2[] using map in c++ in O(mlog(n)) time. We traverse through a1[] and store the frequency of every number in a map. Then we traverse through a2[] and check if the number is present in the map. If the number is present, then print it that many times and erase the number from the map. Print the rest of the numbers present in the map sequentially as numbers are stored in the map in sorted order.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27640,
"s": 27636,
"text": "C++"
},
{
"code": null,
"e": 27648,
"s": 27640,
"text": "Python3"
},
{
"code": "// A C++ program to print an array according// to the order defined by another array#include <bits/stdc++.h>using namespace std; // Function to print an array according// to the order defined by another arrayvoid print_in_order(int a1[], int a2[], int n, int m){ // Declaring map and iterator map<int, int> mp; map<int, int>::iterator itr; // Store the frequency of each // number of a1[] int the map for (int i = 0; i < n; i++) mp[a1[i]]++; // Traverse through a2[] for (int i = 0; i < m; i++) { // Check whether number // is present in map or not if (mp.find(a2[i]) != mp.end()) { itr = mp.find(a2[i]); // Print that number that // many times of its frequency for (int j = 0; j < itr->second; j++) cout << itr->first << \" \"; mp.erase(a2[i]); } } // Print those numbers that are not // present in a2[] for (itr = mp.begin(); itr != mp.end(); itr++) { for (int j = 0; j < itr->second; j++) cout << itr->first << \" \"; } cout << endl;} // Driver codeint main(){ int a1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 }; int a2[] = { 2, 1, 8, 3 }; int n = sizeof(a1) / sizeof(a1[0]); int m = sizeof(a2) / sizeof(a2[0]); print_in_order(a1, a2, n, m); return 0;}",
"e": 28987,
"s": 27648,
"text": null
},
{
"code": "# A Python3 program to print an array according# to the order defined by another array # Function to print an array according# to the order defined by another arraydef print_in_order(a1, a2, n, m) : # Declaring map and iterator mp = dict.fromkeys(a1,0); # Store the frequency of each # number of a1[] int the map for i in range(n) : mp[a1[i]] += 1; # Traverse through a2[] for i in range(m) : # Check whether number # is present in map or not if a2[i] in mp.keys() : # Print that number that # many times of its frequency for j in range(mp[a2[i]]) : print(a2[i],end=\" \"); del(mp[a2[i]]); # Print those numbers that are not # present in a2[] for key,value in mp.items() : for j in range(value) : print(key,end=\" \"); print(); # Driver codeif __name__ == \"__main__\" : a1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ]; a2 = [ 2, 1, 8, 3 ]; n =len(a1); m = len(a2); print_in_order(a1, a2, n, m); # This code is contributed by AnkitRai01",
"e": 30099,
"s": 28987,
"text": null
},
{
"code": null,
"e": 30121,
"s": 30099,
"text": "2 2 1 1 8 8 3 5 6 7 9"
},
{
"code": null,
"e": 30131,
"s": 30123,
"text": "ankthon"
},
{
"code": null,
"e": 30148,
"s": 30131,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30156,
"s": 30148,
"text": "cpp-map"
},
{
"code": null,
"e": 30163,
"s": 30156,
"text": "Arrays"
},
{
"code": null,
"e": 30171,
"s": 30163,
"text": "Sorting"
},
{
"code": null,
"e": 30178,
"s": 30171,
"text": "Arrays"
},
{
"code": null,
"e": 30186,
"s": 30178,
"text": "Sorting"
},
{
"code": null,
"e": 30284,
"s": 30186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30321,
"s": 30284,
"text": "Program for Bridge and Torch problem"
},
{
"code": null,
"e": 30346,
"s": 30321,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30381,
"s": 30346,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 30423,
"s": 30381,
"text": "Segment Tree | Set 1 (Sum of given range)"
}
] |
Check if two given strings are isomorphic to each other - GeeksforGeeks | 02 May, 2022
Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to the same character in ‘str2’.
Examples:
Input: str1 = "aab", str2 = "xxy"
Output: True
'a' is mapped to 'x' and 'b' is mapped to 'y'.
Input: str1 = "aab", str2 = "xyz"
Output: False
One occurrence of 'a' in str1 has 'x' in str2 and
other occurrence of 'a' has 'y'.
A Simple Solution is to consider every character of ‘str1’ and check if all occurrences of it map to the same character in ‘str2’. The time complexity of this solution is O(n*n).
An Efficient Solution can solve this problem in O(n) time. The idea is to create an array to store mappings of processed characters.
1) If lengths of str1 and str2 are not same, return false.
2) Do following for every character in str1 and str2
a) If this character is seen first time in str1,
then current of str2 must have not appeared before.
(i) If current character of str2 is seen, return false.
Mark current character of str2 as visited.
(ii) Store mapping of current characters.
b) Else check if previous occurrence of str1[i] mapped
to same character.
Below is the implementation of above idea :
C++
Java
Python
C#
Javascript
// C++ program to check if two strings are isomorphic#include <bits/stdc++.h>using namespace std;#define MAX_CHARS 256 // This function returns true if str1 and str2 are isomorphicbool areIsomorphic(string str1, string str2){ int m = str1.length(), n = str2.length(); // Length of both strings must be same for one to one // correspondence if (m != n) return false; // To mark visited characters in str2 bool marked[MAX_CHARS] = { false }; // To store mapping of every character from str1 to // that of str2. Initialize all entries of map as -1. int map[MAX_CHARS]; memset(map, -1, sizeof(map)); // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is seen first // time in it. if (map[str1[i]] == -1) { // If current character of str2 is already // seen, one to one mapping not possible if (marked[str2[i]] == true) return false; // Mark current character of str2 as visited marked[str2[i]] = true; // Store mapping of current characters map[str1[i]] = str2[i]; } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i]] != str2[i]) return false; } return true;} // Driver programint main(){ cout << areIsomorphic("aab", "xxy") << endl; cout << areIsomorphic("aab", "xyz") << endl; return 0;}
// Java program to check if two strings are isomorphicimport java.io.*;import java.util.*;class Isomorphic { static int size = 256; // Function returns true if str1 and str2 are isomorphic static boolean areIsomorphic(String str1, String str2) { int m = str1.length(); int n = str2.length(); // Length of both strings must be same for one to // one correspondence if (m != n) return false; // To mark visited characters in str2 Boolean[] marked = new Boolean[size]; Arrays.fill(marked, Boolean.FALSE); // To store mapping of every character from str1 to // that of str2. Initialize all entries of map as // -1. int[] map = new int[size]; Arrays.fill(map, -1); // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is seen first // time in it. if (map[str1.charAt(i)] == -1) { // If current character of str2 is already // seen, one to one mapping not possible if (marked[str2.charAt(i)] == true) return false; // Mark current character of str2 as visited marked[str2.charAt(i)] = true; // Store mapping of current characters map[str1.charAt(i)] = str2.charAt(i); } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1.charAt(i)] != str2.charAt(i)) return false; } return true; } // driver program public static void main(String[] args) { boolean res = areIsomorphic("aab", "xxy"); System.out.println(res); res = areIsomorphic("aab", "xyz"); System.out.println(res); }}
# Python program to check if two strings are isomorphicMAX_CHARS = 256 # This function returns true if str1 and str2 are isomorphic def areIsomorphic(string1, string2): m = len(string1) n = len(string2) # Length of both strings must be same for one to one # correspondence if m != n: return False # To mark visited characters in str2 marked = [False] * MAX_CHARS # To store mapping of every character from str1 to # that of str2. Initialize all entries of map as -1 map = [-1] * MAX_CHARS # Process all characters one by one for i in xrange(n): # if current character of str1 is seen first # time in it. if map[ord(string1[i])] == -1: # if current character of st2 is already # seen, one to one mapping not possible if marked[ord(string2[i])] == True: return False # Mark current character of str2 as visited marked[ord(string2[i])] = True # Store mapping of current characters map[ord(string1[i])] = string2[i] # If this is not first appearance of current # character in str1, then check if previous # appearance mapped to same character of str2 elif map[ord(string1[i])] != string2[i]: return False return True # Driver programprint areIsomorphic("aab", "xxy")print areIsomorphic("aab", "xyz")# This code is contributed by Bhavya Jain
// C# program to check if two// strings are isomorphicusing System; class GFG { static int size = 256; // Function returns true if str1 // and str2 are isomorphic static bool areIsomorphic(String str1, String str2) { int m = str1.Length; int n = str2.Length; // Length of both strings must be same // for one to one correspondence if (m != n) return false; // To mark visited characters in str2 bool[] marked = new bool[size]; for (int i = 0; i < size; i++) marked[i] = false; // To store mapping of every character // from str1 to that of str2 and // Initialize all entries of map as -1. int[] map = new int[size]; for (int i = 0; i < size; i++) map[i] = -1; // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is // seen first time in it. if (map[str1[i]] == -1) { // If current character of str2 // is already seen, one to // one mapping not possible if (marked[str2[i]] == true) return false; // Mark current character of // str2 as visited marked[str2[i]] = true; // Store mapping of current characters map[str1[i]] = str2[i]; } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i]] != str2[i]) return false; } return true; } // Driver code public static void Main() { bool res = areIsomorphic("aab", "xxy"); Console.WriteLine(res); res = areIsomorphic("aab", "xyz"); Console.WriteLine(res); }} // This code is contributed by Sam007.
<script> // Javascript program to check if two // strings are isomorphic let size = 256; // Function returns true if str1 // and str2 are isomorphic function areIsomorphic(str1, str2) { let m = str1.length; let n = str2.length; // Length of both strings must be same // for one to one correspondence if(m != n) return false; // To mark visited characters in str2 let marked = new Array(size); for(let i = 0; i < size; i++) marked[i]= false; // To store mapping of every character // from str1 to that of str2 and // Initialize all entries of map as -1. let map = new Array(size); map.fill(0); for(let i = 0; i < size; i++) map[i]= -1; // Process all characters one by on for (let i = 0; i < n; i++) { // If current character of str1 is // seen first time in it. if (map[str1[i].charCodeAt()] == -1) { // If current character of str2 // is already seen, one to // one mapping not possible if (marked[str2[i].charCodeAt()] == true) return false; // Mark current character of // str2 as visited marked[str2[i].charCodeAt()] = true; // Store mapping of current characters map[str1[i].charCodeAt()] = str2[i].charCodeAt(); } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i].charCodeAt()] != str2[i].charCodeAt()) return 0; } return 1; } let res = areIsomorphic("aab", "xxy"); document.write(res + "</br>"); res = areIsomorphic("aab", "xyz"); document.write(res); // This code is contributed by decode2207.</script>
Output:
1
0
Another Approach:
In this approach, we will count the number of occurrences of a particular character in both the string using two arrays, while we will compare the two arrays if at any moment with the loop the count of the current character in both strings becomes different we return false, else after the loop ends we return true.Follow the code given below you will understand everything.
In this approach, we will count the number of occurrences of a particular character in both the string using two arrays, while we will compare the two arrays if at any moment with the loop the count of the current character in both strings becomes different we return false, else after the loop ends we return true.
Follow the code given below you will understand everything.
Note: There is no need to create here array of 256 characters. We can reduce it to only 26 characters
by storing count of ch-'a' (ch is the ith character of the string) in count array .This gives the same
result as string consists of only small case characters.
Below is the implementation of the above idea :
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define MAX_CHARS 26 // This function returns true if// str1 and str2 are isomorphicbool areIsomorphic(string str1, string str2){ int n = str1.length(), m = str2.length(); // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances of character in // both the strings int count[MAX_CHARS] = { 0 }; int dcount[MAX_CHARS] = { 0 }; // Process all characters one by one for (int i = 0; i < n; i++) { count[str1[i] - 'a']++; dcount[str2[i] - 'a']++; } // For string to be isomorphic the previous counts // of appearances of // current character in both string must be same if // it is not same we return false. //before it was not working for the test case mentioned below(wrong output) // str1 = "aba" , str2 = "xyy" for(int i= 0; i < n; i++) { if (count[str1[i] - 'a'] != dcount[str2[i] - 'a']) { return false; } } return true;} // Driver Codeint main(){ cout << areIsomorphic("aab", "xxy") << endl; cout << areIsomorphic("aba", "xyy") << endl; return 0;}
// Java program for the above approachimport java.io.*; class GFG { static final int CHAR = 26; // This function returns true if // str1 and str2 are isomorphic static boolean isoMorphic(String str1, String str2) { int n = str1.length(); int m = str2.length(); // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings int[] countChars1 = new int[CHAR]; int[] countChars2 = new int[CHAR]; // Process all characters one by one for (int i = 0; i < n; i++) { countChars1[str1.charAt(i) - 'a']++; countChars2[str2.charAt(i) - 'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. //before it was not working for the test case mentioned below(wrong output) // str1 = "aba" , str2 = "xyy" for(int i= 0; i < n; i++) { if (countChars1[str1.charAt(i) - 'a'] != countChars2[str2.charAt(i) - 'a']) { return false; } } return true; } // Driver Code public static void main(String[] args) { System.out.println(isoMorphic("aab", "xxy") ? 1 : 0); System.out.println(isoMorphic("aba", "xyy") ? 1 : 0); }} // This code is contributed by rohansharma1808
# Python3 program for the above approachCHAR = 26 # This function returns true if# str1 and str2 are isomorphicdef isoMorphic(str1, str2): n = len(str1) m = len(str2) # Length of both strings must be # same for one to one correspondence if n != m: return False # for counting the previous appearances of character # in both the strings countChars1 = [0] * CHAR countChars2 = [0] * CHAR # Process all characters one by one for i in range(n): countChars1[ord(str1[i]) - ord('a')] += 1 countChars2[ord(str2[i]) - ord('a')] += 1 # For string to be isomorphice the # previous counts of appearances of # current character in both string # must be same if it is not same # we return false for i in range(n): if countChars1[ord(str1[i]) - ord('a')] != countChars2[ord(str2[i]) - ord('a')]: return False return True # Driver Codeprint(int(isoMorphic("aab", "xxy")))print(int(isoMorphic("aab", "xyz"))) # This code is contributed by phasing17
// C# program for the above approachusing System;class GFG { static int CHAR = 26; // This function returns true if // str1 and str2 are isomorphic static bool isoMorphic(string str1, string str2) { int n = str1.Length; int m = str2.Length; // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings int[] countChars1 = new int[CHAR]; int[] countChars2 = new int[CHAR]; // Process all characters one by one for (int i = 0; i < n; i++) { countChars1[str1[i] - 'a']++; countChars2[str2[i] - 'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. //before it was not working for the test case mentioned below(wrong output) // str1 = "aba" , str2 = "xyy" for (int i = 0; i < n; i++) { if (countChars1[str1[i] - 'a'] != countChars2[str2[i] - 'a']) { return false; } } return true; } // Driver Code public static void Main(string[] args) { Console.WriteLine(isoMorphic("aab", "xxy") ? 1 : 0); Console.WriteLine(isoMorphic("aab", "xyz") ? 1 : 0); }} // This code is contributed by ukasp.
<script> // Javascript program for the above approach let CHAR = 26; // This function returns true if // str1 and str2 are isomorphic function isoMorphic(str1, str2) { let n = str1.length; let m = str2.length; // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings let countChars1 = new Array(CHAR); countChars1.fill(0); let countChars2 = new Array(CHAR); countChars2.fill(0); // Process all characters one by one for(let i = 0; i < n; i++) { countChars1[str1[i].charCodeAt()-'a']++; countChars2[str2[i].charCodeAt()-'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. for(let i = 0; i < n; i++) { if (countChars1[str1[i].charCodeAt()-'a'] != countChars2[str2[i].charCodeAt()-'a']) { return false; } } return true; } document.write(isoMorphic("aab", "xxy") ? 1 + "</br>" : 0 + "</br>"); document.write(isoMorphic("aab", "xyz") ? 1 : 0); </script>
1
0
Time Complexity: O(n)
Another Approach:
1) In this approach we will use just a single dictionary for a Key value pair for the respective characters in the first and second string.
2) If the Key repeats we check if the value matches in the respective index.
C#
// C# program to check if two strings// areIsIsomorphic using System;using System.Collections.Generic; public class GFG { static bool areIsomorphic(char[] str1, char[] str2) { Dictionary<char, char> charCount = new Dictionary<char, char>(); char c = 'a'; for (int i = 0; i < str1.Length; i++) { if (charCount.ContainsKey(str1[i]) && charCount.TryGetValue(str1[i], out c)) { if (c != str2[i]) return false; } else if (!charCount.ContainsValue(str2[i])) { charCount.Add(str1[i], str2[i]); } else { return false; } } return true; } /* Driver code*/ public static void Main() { string str1 = "aac"; string str2 = "xxy"; // Function Call if (str1.Length == str2.Length && areIsomorphic(str1.ToCharArray(), str2.ToCharArray())) Console.WriteLine(1); else Console.WriteLine(0); Console.ReadLine(); }}
1
YouTubeGeeksforGeeks507K subscribersCheck if two given strings are isomorphic to each other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7fWTI6AOydo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Thanks to Gaurav and Utkarsh for suggesting the above approach.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
us19018
rohansharma1808
decode2207
suresh07
ukasp
clintra
reddybharathab426
harshgupta597
akshaysingh98088
anirudhpathak18
simmytarika5
phasing17
Hike
Strings
Hike
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters | [
{
"code": null,
"e": 25985,
"s": 25957,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 26217,
"s": 25985,
"text": "Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to the same character in ‘str2’."
},
{
"code": null,
"e": 26228,
"s": 26217,
"text": "Examples: "
},
{
"code": null,
"e": 26457,
"s": 26228,
"text": "Input: str1 = \"aab\", str2 = \"xxy\"\nOutput: True\n'a' is mapped to 'x' and 'b' is mapped to 'y'.\n\nInput: str1 = \"aab\", str2 = \"xyz\"\nOutput: False\nOne occurrence of 'a' in str1 has 'x' in str2 and \nother occurrence of 'a' has 'y'."
},
{
"code": null,
"e": 26636,
"s": 26457,
"text": "A Simple Solution is to consider every character of ‘str1’ and check if all occurrences of it map to the same character in ‘str2’. The time complexity of this solution is O(n*n)."
},
{
"code": null,
"e": 26770,
"s": 26636,
"text": "An Efficient Solution can solve this problem in O(n) time. The idea is to create an array to store mappings of processed characters. "
},
{
"code": null,
"e": 27239,
"s": 26770,
"text": "1) If lengths of str1 and str2 are not same, return false.\n2) Do following for every character in str1 and str2\n a) If this character is seen first time in str1, \n then current of str2 must have not appeared before.\n (i) If current character of str2 is seen, return false.\n Mark current character of str2 as visited.\n (ii) Store mapping of current characters.\n b) Else check if previous occurrence of str1[i] mapped\n to same character."
},
{
"code": null,
"e": 27285,
"s": 27239,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 27289,
"s": 27285,
"text": "C++"
},
{
"code": null,
"e": 27294,
"s": 27289,
"text": "Java"
},
{
"code": null,
"e": 27301,
"s": 27294,
"text": "Python"
},
{
"code": null,
"e": 27304,
"s": 27301,
"text": "C#"
},
{
"code": null,
"e": 27315,
"s": 27304,
"text": "Javascript"
},
{
"code": "// C++ program to check if two strings are isomorphic#include <bits/stdc++.h>using namespace std;#define MAX_CHARS 256 // This function returns true if str1 and str2 are isomorphicbool areIsomorphic(string str1, string str2){ int m = str1.length(), n = str2.length(); // Length of both strings must be same for one to one // correspondence if (m != n) return false; // To mark visited characters in str2 bool marked[MAX_CHARS] = { false }; // To store mapping of every character from str1 to // that of str2. Initialize all entries of map as -1. int map[MAX_CHARS]; memset(map, -1, sizeof(map)); // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is seen first // time in it. if (map[str1[i]] == -1) { // If current character of str2 is already // seen, one to one mapping not possible if (marked[str2[i]] == true) return false; // Mark current character of str2 as visited marked[str2[i]] = true; // Store mapping of current characters map[str1[i]] = str2[i]; } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i]] != str2[i]) return false; } return true;} // Driver programint main(){ cout << areIsomorphic(\"aab\", \"xxy\") << endl; cout << areIsomorphic(\"aab\", \"xyz\") << endl; return 0;}",
"e": 28883,
"s": 27315,
"text": null
},
{
"code": "// Java program to check if two strings are isomorphicimport java.io.*;import java.util.*;class Isomorphic { static int size = 256; // Function returns true if str1 and str2 are isomorphic static boolean areIsomorphic(String str1, String str2) { int m = str1.length(); int n = str2.length(); // Length of both strings must be same for one to // one correspondence if (m != n) return false; // To mark visited characters in str2 Boolean[] marked = new Boolean[size]; Arrays.fill(marked, Boolean.FALSE); // To store mapping of every character from str1 to // that of str2. Initialize all entries of map as // -1. int[] map = new int[size]; Arrays.fill(map, -1); // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is seen first // time in it. if (map[str1.charAt(i)] == -1) { // If current character of str2 is already // seen, one to one mapping not possible if (marked[str2.charAt(i)] == true) return false; // Mark current character of str2 as visited marked[str2.charAt(i)] = true; // Store mapping of current characters map[str1.charAt(i)] = str2.charAt(i); } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1.charAt(i)] != str2.charAt(i)) return false; } return true; } // driver program public static void main(String[] args) { boolean res = areIsomorphic(\"aab\", \"xxy\"); System.out.println(res); res = areIsomorphic(\"aab\", \"xyz\"); System.out.println(res); }}",
"e": 30821,
"s": 28883,
"text": null
},
{
"code": "# Python program to check if two strings are isomorphicMAX_CHARS = 256 # This function returns true if str1 and str2 are isomorphic def areIsomorphic(string1, string2): m = len(string1) n = len(string2) # Length of both strings must be same for one to one # correspondence if m != n: return False # To mark visited characters in str2 marked = [False] * MAX_CHARS # To store mapping of every character from str1 to # that of str2. Initialize all entries of map as -1 map = [-1] * MAX_CHARS # Process all characters one by one for i in xrange(n): # if current character of str1 is seen first # time in it. if map[ord(string1[i])] == -1: # if current character of st2 is already # seen, one to one mapping not possible if marked[ord(string2[i])] == True: return False # Mark current character of str2 as visited marked[ord(string2[i])] = True # Store mapping of current characters map[ord(string1[i])] = string2[i] # If this is not first appearance of current # character in str1, then check if previous # appearance mapped to same character of str2 elif map[ord(string1[i])] != string2[i]: return False return True # Driver programprint areIsomorphic(\"aab\", \"xxy\")print areIsomorphic(\"aab\", \"xyz\")# This code is contributed by Bhavya Jain",
"e": 32268,
"s": 30821,
"text": null
},
{
"code": "// C# program to check if two// strings are isomorphicusing System; class GFG { static int size = 256; // Function returns true if str1 // and str2 are isomorphic static bool areIsomorphic(String str1, String str2) { int m = str1.Length; int n = str2.Length; // Length of both strings must be same // for one to one correspondence if (m != n) return false; // To mark visited characters in str2 bool[] marked = new bool[size]; for (int i = 0; i < size; i++) marked[i] = false; // To store mapping of every character // from str1 to that of str2 and // Initialize all entries of map as -1. int[] map = new int[size]; for (int i = 0; i < size; i++) map[i] = -1; // Process all characters one by on for (int i = 0; i < n; i++) { // If current character of str1 is // seen first time in it. if (map[str1[i]] == -1) { // If current character of str2 // is already seen, one to // one mapping not possible if (marked[str2[i]] == true) return false; // Mark current character of // str2 as visited marked[str2[i]] = true; // Store mapping of current characters map[str1[i]] = str2[i]; } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i]] != str2[i]) return false; } return true; } // Driver code public static void Main() { bool res = areIsomorphic(\"aab\", \"xxy\"); Console.WriteLine(res); res = areIsomorphic(\"aab\", \"xyz\"); Console.WriteLine(res); }} // This code is contributed by Sam007.",
"e": 34243,
"s": 32268,
"text": null
},
{
"code": "<script> // Javascript program to check if two // strings are isomorphic let size = 256; // Function returns true if str1 // and str2 are isomorphic function areIsomorphic(str1, str2) { let m = str1.length; let n = str2.length; // Length of both strings must be same // for one to one correspondence if(m != n) return false; // To mark visited characters in str2 let marked = new Array(size); for(let i = 0; i < size; i++) marked[i]= false; // To store mapping of every character // from str1 to that of str2 and // Initialize all entries of map as -1. let map = new Array(size); map.fill(0); for(let i = 0; i < size; i++) map[i]= -1; // Process all characters one by on for (let i = 0; i < n; i++) { // If current character of str1 is // seen first time in it. if (map[str1[i].charCodeAt()] == -1) { // If current character of str2 // is already seen, one to // one mapping not possible if (marked[str2[i].charCodeAt()] == true) return false; // Mark current character of // str2 as visited marked[str2[i].charCodeAt()] = true; // Store mapping of current characters map[str1[i].charCodeAt()] = str2[i].charCodeAt(); } // If this is not first appearance of current // character in str1, then check if previous // appearance mapped to same character of str2 else if (map[str1[i].charCodeAt()] != str2[i].charCodeAt()) return 0; } return 1; } let res = areIsomorphic(\"aab\", \"xxy\"); document.write(res + \"</br>\"); res = areIsomorphic(\"aab\", \"xyz\"); document.write(res); // This code is contributed by decode2207.</script>",
"e": 36378,
"s": 34243,
"text": null
},
{
"code": null,
"e": 36387,
"s": 36378,
"text": "Output: "
},
{
"code": null,
"e": 36391,
"s": 36387,
"text": "1\n0"
},
{
"code": null,
"e": 36409,
"s": 36391,
"text": "Another Approach:"
},
{
"code": null,
"e": 36784,
"s": 36409,
"text": "In this approach, we will count the number of occurrences of a particular character in both the string using two arrays, while we will compare the two arrays if at any moment with the loop the count of the current character in both strings becomes different we return false, else after the loop ends we return true.Follow the code given below you will understand everything."
},
{
"code": null,
"e": 37100,
"s": 36784,
"text": "In this approach, we will count the number of occurrences of a particular character in both the string using two arrays, while we will compare the two arrays if at any moment with the loop the count of the current character in both strings becomes different we return false, else after the loop ends we return true."
},
{
"code": null,
"e": 37160,
"s": 37100,
"text": "Follow the code given below you will understand everything."
},
{
"code": null,
"e": 37424,
"s": 37160,
"text": "Note: There is no need to create here array of 256 characters. We can reduce it to only 26 characters \nby storing count of ch-'a' (ch is the ith character of the string) in count array .This gives the same \nresult as string consists of only small case characters."
},
{
"code": null,
"e": 37473,
"s": 37424,
"text": "Below is the implementation of the above idea : "
},
{
"code": null,
"e": 37477,
"s": 37473,
"text": "C++"
},
{
"code": null,
"e": 37482,
"s": 37477,
"text": "Java"
},
{
"code": null,
"e": 37490,
"s": 37482,
"text": "Python3"
},
{
"code": null,
"e": 37493,
"s": 37490,
"text": "C#"
},
{
"code": null,
"e": 37504,
"s": 37493,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define MAX_CHARS 26 // This function returns true if// str1 and str2 are isomorphicbool areIsomorphic(string str1, string str2){ int n = str1.length(), m = str2.length(); // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances of character in // both the strings int count[MAX_CHARS] = { 0 }; int dcount[MAX_CHARS] = { 0 }; // Process all characters one by one for (int i = 0; i < n; i++) { count[str1[i] - 'a']++; dcount[str2[i] - 'a']++; } // For string to be isomorphic the previous counts // of appearances of // current character in both string must be same if // it is not same we return false. //before it was not working for the test case mentioned below(wrong output) // str1 = \"aba\" , str2 = \"xyy\" for(int i= 0; i < n; i++) { if (count[str1[i] - 'a'] != dcount[str2[i] - 'a']) { return false; } } return true;} // Driver Codeint main(){ cout << areIsomorphic(\"aab\", \"xxy\") << endl; cout << areIsomorphic(\"aba\", \"xyy\") << endl; return 0;}",
"e": 38777,
"s": 37504,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG { static final int CHAR = 26; // This function returns true if // str1 and str2 are isomorphic static boolean isoMorphic(String str1, String str2) { int n = str1.length(); int m = str2.length(); // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings int[] countChars1 = new int[CHAR]; int[] countChars2 = new int[CHAR]; // Process all characters one by one for (int i = 0; i < n; i++) { countChars1[str1.charAt(i) - 'a']++; countChars2[str2.charAt(i) - 'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. //before it was not working for the test case mentioned below(wrong output) // str1 = \"aba\" , str2 = \"xyy\" for(int i= 0; i < n; i++) { if (countChars1[str1.charAt(i) - 'a'] != countChars2[str2.charAt(i) - 'a']) { return false; } } return true; } // Driver Code public static void main(String[] args) { System.out.println(isoMorphic(\"aab\", \"xxy\") ? 1 : 0); System.out.println(isoMorphic(\"aba\", \"xyy\") ? 1 : 0); }} // This code is contributed by rohansharma1808",
"e": 40482,
"s": 38777,
"text": null
},
{
"code": "# Python3 program for the above approachCHAR = 26 # This function returns true if# str1 and str2 are isomorphicdef isoMorphic(str1, str2): n = len(str1) m = len(str2) # Length of both strings must be # same for one to one correspondence if n != m: return False # for counting the previous appearances of character # in both the strings countChars1 = [0] * CHAR countChars2 = [0] * CHAR # Process all characters one by one for i in range(n): countChars1[ord(str1[i]) - ord('a')] += 1 countChars2[ord(str2[i]) - ord('a')] += 1 # For string to be isomorphice the # previous counts of appearances of # current character in both string # must be same if it is not same # we return false for i in range(n): if countChars1[ord(str1[i]) - ord('a')] != countChars2[ord(str2[i]) - ord('a')]: return False return True # Driver Codeprint(int(isoMorphic(\"aab\", \"xxy\")))print(int(isoMorphic(\"aab\", \"xyz\"))) # This code is contributed by phasing17",
"e": 41542,
"s": 40482,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG { static int CHAR = 26; // This function returns true if // str1 and str2 are isomorphic static bool isoMorphic(string str1, string str2) { int n = str1.Length; int m = str2.Length; // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings int[] countChars1 = new int[CHAR]; int[] countChars2 = new int[CHAR]; // Process all characters one by one for (int i = 0; i < n; i++) { countChars1[str1[i] - 'a']++; countChars2[str2[i] - 'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. //before it was not working for the test case mentioned below(wrong output) // str1 = \"aba\" , str2 = \"xyy\" for (int i = 0; i < n; i++) { if (countChars1[str1[i] - 'a'] != countChars2[str2[i] - 'a']) { return false; } } return true; } // Driver Code public static void Main(string[] args) { Console.WriteLine(isoMorphic(\"aab\", \"xxy\") ? 1 : 0); Console.WriteLine(isoMorphic(\"aab\", \"xyz\") ? 1 : 0); }} // This code is contributed by ukasp.",
"e": 43085,
"s": 41542,
"text": null
},
{
"code": "<script> // Javascript program for the above approach let CHAR = 26; // This function returns true if // str1 and str2 are isomorphic function isoMorphic(str1, str2) { let n = str1.length; let m = str2.length; // Length of both strings must be // same for one to one // correspondence if (n != m) return false; // For counting the previous appearances // of character in both the strings let countChars1 = new Array(CHAR); countChars1.fill(0); let countChars2 = new Array(CHAR); countChars2.fill(0); // Process all characters one by one for(let i = 0; i < n; i++) { countChars1[str1[i].charCodeAt()-'a']++; countChars2[str2[i].charCodeAt()-'a']++; } // For string to be isomorphic the // previous counts of appearances of // current character in both string // must be same if it is not same we // return false. for(let i = 0; i < n; i++) { if (countChars1[str1[i].charCodeAt()-'a'] != countChars2[str2[i].charCodeAt()-'a']) { return false; } } return true; } document.write(isoMorphic(\"aab\", \"xxy\") ? 1 + \"</br>\" : 0 + \"</br>\"); document.write(isoMorphic(\"aab\", \"xyz\") ? 1 : 0); </script>",
"e": 44507,
"s": 43085,
"text": null
},
{
"code": null,
"e": 44514,
"s": 44510,
"text": "1\n0"
},
{
"code": null,
"e": 44538,
"s": 44516,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 44558,
"s": 44540,
"text": "Another Approach:"
},
{
"code": null,
"e": 44701,
"s": 44560,
"text": "1) In this approach we will use just a single dictionary for a Key value pair for the respective characters in the first and second string."
},
{
"code": null,
"e": 44780,
"s": 44703,
"text": "2) If the Key repeats we check if the value matches in the respective index."
},
{
"code": null,
"e": 44785,
"s": 44782,
"text": "C#"
},
{
"code": "// C# program to check if two strings// areIsIsomorphic using System;using System.Collections.Generic; public class GFG { static bool areIsomorphic(char[] str1, char[] str2) { Dictionary<char, char> charCount = new Dictionary<char, char>(); char c = 'a'; for (int i = 0; i < str1.Length; i++) { if (charCount.ContainsKey(str1[i]) && charCount.TryGetValue(str1[i], out c)) { if (c != str2[i]) return false; } else if (!charCount.ContainsValue(str2[i])) { charCount.Add(str1[i], str2[i]); } else { return false; } } return true; } /* Driver code*/ public static void Main() { string str1 = \"aac\"; string str2 = \"xxy\"; // Function Call if (str1.Length == str2.Length && areIsomorphic(str1.ToCharArray(), str2.ToCharArray())) Console.WriteLine(1); else Console.WriteLine(0); Console.ReadLine(); }}",
"e": 45900,
"s": 44785,
"text": null
},
{
"code": null,
"e": 45905,
"s": 45903,
"text": "1"
},
{
"code": null,
"e": 46761,
"s": 45907,
"text": "YouTubeGeeksforGeeks507K subscribersCheck if two given strings are isomorphic to each other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7fWTI6AOydo\" 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": 46951,
"s": 46763,
"text": "Thanks to Gaurav and Utkarsh for suggesting the above approach.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 46960,
"s": 46953,
"text": "Sam007"
},
{
"code": null,
"e": 46968,
"s": 46960,
"text": "us19018"
},
{
"code": null,
"e": 46984,
"s": 46968,
"text": "rohansharma1808"
},
{
"code": null,
"e": 46995,
"s": 46984,
"text": "decode2207"
},
{
"code": null,
"e": 47004,
"s": 46995,
"text": "suresh07"
},
{
"code": null,
"e": 47010,
"s": 47004,
"text": "ukasp"
},
{
"code": null,
"e": 47018,
"s": 47010,
"text": "clintra"
},
{
"code": null,
"e": 47036,
"s": 47018,
"text": "reddybharathab426"
},
{
"code": null,
"e": 47050,
"s": 47036,
"text": "harshgupta597"
},
{
"code": null,
"e": 47067,
"s": 47050,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 47083,
"s": 47067,
"text": "anirudhpathak18"
},
{
"code": null,
"e": 47096,
"s": 47083,
"text": "simmytarika5"
},
{
"code": null,
"e": 47106,
"s": 47096,
"text": "phasing17"
},
{
"code": null,
"e": 47111,
"s": 47106,
"text": "Hike"
},
{
"code": null,
"e": 47119,
"s": 47111,
"text": "Strings"
},
{
"code": null,
"e": 47124,
"s": 47119,
"text": "Hike"
},
{
"code": null,
"e": 47132,
"s": 47124,
"text": "Strings"
},
{
"code": null,
"e": 47230,
"s": 47132,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47305,
"s": 47230,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 47362,
"s": 47305,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 47398,
"s": 47362,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 47445,
"s": 47398,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 47498,
"s": 47445,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 47534,
"s": 47498,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 47572,
"s": 47534,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 47602,
"s": 47572,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 47647,
"s": 47602,
"text": "Top 50 String Coding Problems for Interviews"
}
] |
Different ways of Method Overloading in Java - GeeksforGeeks | 08 Mar, 2022
Method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.
Java can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, the order of the parameters, and data types of the parameters) within the same class.
Geeks, now you would be up to why do we need method overloading?
If we need to do some kind of operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many meaningful names for a single action.
Method overloading can be done by changing:
The number of parameters in two methods.The data types of the parameters of methods.The Order of the parameters of methods.
The number of parameters in two methods.
The data types of the parameters of methods.
The Order of the parameters of methods.
Let us propose examples in order to illustrate each way while overloading methods. They are as follows:
Method 1: By changing the number of parameters.
Java
// Java Program to Illustrate Method Overloading// By Changing the Number of Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Method 1 // Adding two integer values public int add(int a, int b) { int sum = a + b; return sum; } // Method 2 // Adding three integer values public int add(int a, int b, int c) { int sum = a + b + c; return sum; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of above class inside main() // method Addition ob = new Addition(); // Calling method to add 3 numbers int sum1 = ob.add(1, 2); // Printing sum of 2 numbers System.out.println("sum of the two integer value :" + sum1); // Calling method to add 3 numbers int sum2 = ob.add(1, 2, 3); // Printing sum of 3 numbers System.out.println( "sum of the three integer value :" + sum2); }}
sum of the two integer value :3
sum of the three integer value :6
Method 2: By changing the Data types of the parameters
Java
// Java Program to Illustrate Method Overloading// By Changing Data Types of the Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Adding three integer values public int add(int a, int b, int c) { int sum = a + b + c; return sum; } // adding three double values. public double add(double a, double b, double c) { double sum = a + b + c; return sum; }} class GFG { public static void main(String[] args) { Addition ob = new Addition(); int sum2 = ob.add(1, 2, 3); System.out.println( "sum of the three integer value :" + sum2); double sum3 = ob.add(1.0, 2.0, 3.0); System.out.println("sum of the three double value :" + sum3); }}
sum of the three integer value :6
sum of the three double value :6.0
Method 3: By changing the Order of the parameters
Java
// Java Program to Illustrate Method Overloading// By changing the Order of the Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Geek { // Method 1 public void geekIdentity(String name, int id) { // Printing name and id of person System.out.println("geekName :" + name + " " + "Id :" + id); } // Method 2 public void geekIdentity(int id, String name) { // Again printing name and id of person System.out.println("Id :" + id + " " + "geekName :" + name); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of above class Geek geek = new Geek(); // Passing name and id // Note: Reversing order geek.geekIdentity("Mohit", 1); geek.geekIdentity(2, "shubham"); }}
geekName :Mohit Id :1
geekName :shubham Id :2
Note: Now geeks you must be wondering what will happen when the method signature is the same and the return type is different?
Here the compiler will give an error as the return value alone is not sufficient for the compiler to figure out which function it has to call. Only if both methods have different parameter types (so, they have a different signature), then Method overloading is possible.
Example 4
Java
// Java Program to Illustrate Error Thrown in// Method Overloading When Method Signature is Same and// ReturnType is Different // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Method 1 // Adding two integer value public int add(int a, int b) { // Summing up int sum = a + b; // Returning the sum return sum; } // Method 2 // Adding three integer value public double add(int a, int b) { double sum = a + b + 0.0; return sum; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of above class Addition ob = new Addition(); // Calling method 1 to sum 2 numbers int sum1 = ob.add(1, 2); // Printing sum of two numbers System.out.println( "sum of the two integer value :" + sum1); // Calling method 2 to sum 3 numbers int sum2 = ob.add(1, 2); // Printing sum of three numbers System.out.println( "sum of the three integer value :" + sum2); } // Catch block to handle exceptions catch (Exception e) { // Display the exceptions on console System.out.println(e); } }}
Output:
Related Articles:
Method Overloading and Null error in Java
Can we Overload or Override static methods in java?
This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Arijit Nath 1
aadarsh baid
fi8drqq5elpfvbbzadzdhux0oxuo4sl5x97ysnhm
sumitgumber28
surinderdawra388
simmytarika5
Java-Overloading
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Stream In Java
How to iterate any Map in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 30196,
"s": 30168,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 30749,
"s": 30196,
"text": "Method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible."
},
{
"code": null,
"e": 31014,
"s": 30749,
"text": "Java can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, the order of the parameters, and data types of the parameters) within the same class. "
},
{
"code": null,
"e": 31079,
"s": 31014,
"text": "Geeks, now you would be up to why do we need method overloading?"
},
{
"code": null,
"e": 31317,
"s": 31079,
"text": "If we need to do some kind of operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many meaningful names for a single action. "
},
{
"code": null,
"e": 31362,
"s": 31317,
"text": "Method overloading can be done by changing: "
},
{
"code": null,
"e": 31486,
"s": 31362,
"text": "The number of parameters in two methods.The data types of the parameters of methods.The Order of the parameters of methods."
},
{
"code": null,
"e": 31527,
"s": 31486,
"text": "The number of parameters in two methods."
},
{
"code": null,
"e": 31572,
"s": 31527,
"text": "The data types of the parameters of methods."
},
{
"code": null,
"e": 31612,
"s": 31572,
"text": "The Order of the parameters of methods."
},
{
"code": null,
"e": 31719,
"s": 31612,
"text": "Let us propose examples in order to illustrate each way while overloading methods. They are as follows: "
},
{
"code": null,
"e": 31768,
"s": 31719,
"text": "Method 1: By changing the number of parameters. "
},
{
"code": null,
"e": 31773,
"s": 31768,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Method Overloading// By Changing the Number of Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Method 1 // Adding two integer values public int add(int a, int b) { int sum = a + b; return sum; } // Method 2 // Adding three integer values public int add(int a, int b, int c) { int sum = a + b + c; return sum; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of above class inside main() // method Addition ob = new Addition(); // Calling method to add 3 numbers int sum1 = ob.add(1, 2); // Printing sum of 2 numbers System.out.println(\"sum of the two integer value :\" + sum1); // Calling method to add 3 numbers int sum2 = ob.add(1, 2, 3); // Printing sum of 3 numbers System.out.println( \"sum of the three integer value :\" + sum2); }}",
"e": 32859,
"s": 31773,
"text": null
},
{
"code": null,
"e": 32925,
"s": 32859,
"text": "sum of the two integer value :3\nsum of the three integer value :6"
},
{
"code": null,
"e": 32981,
"s": 32925,
"text": "Method 2: By changing the Data types of the parameters "
},
{
"code": null,
"e": 32986,
"s": 32981,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Method Overloading// By Changing Data Types of the Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Adding three integer values public int add(int a, int b, int c) { int sum = a + b + c; return sum; } // adding three double values. public double add(double a, double b, double c) { double sum = a + b + c; return sum; }} class GFG { public static void main(String[] args) { Addition ob = new Addition(); int sum2 = ob.add(1, 2, 3); System.out.println( \"sum of the three integer value :\" + sum2); double sum3 = ob.add(1.0, 2.0, 3.0); System.out.println(\"sum of the three double value :\" + sum3); }}",
"e": 33815,
"s": 32986,
"text": null
},
{
"code": null,
"e": 33884,
"s": 33815,
"text": "sum of the three integer value :6\nsum of the three double value :6.0"
},
{
"code": null,
"e": 33935,
"s": 33884,
"text": "Method 3: By changing the Order of the parameters "
},
{
"code": null,
"e": 33940,
"s": 33935,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Method Overloading// By changing the Order of the Parameters // Importing required classesimport java.io.*; // Class 1// Helper classclass Geek { // Method 1 public void geekIdentity(String name, int id) { // Printing name and id of person System.out.println(\"geekName :\" + name + \" \" + \"Id :\" + id); } // Method 2 public void geekIdentity(int id, String name) { // Again printing name and id of person System.out.println(\"Id :\" + id + \" \" + \"geekName :\" + name); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of above class Geek geek = new Geek(); // Passing name and id // Note: Reversing order geek.geekIdentity(\"Mohit\", 1); geek.geekIdentity(2, \"shubham\"); }}",
"e": 34873,
"s": 33940,
"text": null
},
{
"code": null,
"e": 34919,
"s": 34873,
"text": "geekName :Mohit Id :1\ngeekName :shubham Id :2"
},
{
"code": null,
"e": 35046,
"s": 34919,
"text": "Note: Now geeks you must be wondering what will happen when the method signature is the same and the return type is different?"
},
{
"code": null,
"e": 35319,
"s": 35046,
"text": "Here the compiler will give an error as the return value alone is not sufficient for the compiler to figure out which function it has to call. Only if both methods have different parameter types (so, they have a different signature), then Method overloading is possible. "
},
{
"code": null,
"e": 35330,
"s": 35319,
"text": "Example 4 "
},
{
"code": null,
"e": 35335,
"s": 35330,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Error Thrown in// Method Overloading When Method Signature is Same and// ReturnType is Different // Importing required classesimport java.io.*; // Class 1// Helper classclass Addition { // Method 1 // Adding two integer value public int add(int a, int b) { // Summing up int sum = a + b; // Returning the sum return sum; } // Method 2 // Adding three integer value public double add(int a, int b) { double sum = a + b + 0.0; return sum; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of above class Addition ob = new Addition(); // Calling method 1 to sum 2 numbers int sum1 = ob.add(1, 2); // Printing sum of two numbers System.out.println( \"sum of the two integer value :\" + sum1); // Calling method 2 to sum 3 numbers int sum2 = ob.add(1, 2); // Printing sum of three numbers System.out.println( \"sum of the three integer value :\" + sum2); } // Catch block to handle exceptions catch (Exception e) { // Display the exceptions on console System.out.println(e); } }}",
"e": 36751,
"s": 35335,
"text": null
},
{
"code": null,
"e": 36759,
"s": 36751,
"text": "Output:"
},
{
"code": null,
"e": 36777,
"s": 36759,
"text": "Related Articles:"
},
{
"code": null,
"e": 36819,
"s": 36777,
"text": "Method Overloading and Null error in Java"
},
{
"code": null,
"e": 36871,
"s": 36819,
"text": "Can we Overload or Override static methods in java?"
},
{
"code": null,
"e": 37293,
"s": 36871,
"text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 37307,
"s": 37293,
"text": "Arijit Nath 1"
},
{
"code": null,
"e": 37320,
"s": 37307,
"text": "aadarsh baid"
},
{
"code": null,
"e": 37361,
"s": 37320,
"text": "fi8drqq5elpfvbbzadzdhux0oxuo4sl5x97ysnhm"
},
{
"code": null,
"e": 37375,
"s": 37361,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37392,
"s": 37375,
"text": "surinderdawra388"
},
{
"code": null,
"e": 37405,
"s": 37392,
"text": "simmytarika5"
},
{
"code": null,
"e": 37422,
"s": 37405,
"text": "Java-Overloading"
},
{
"code": null,
"e": 37427,
"s": 37422,
"text": "Java"
},
{
"code": null,
"e": 37446,
"s": 37427,
"text": "School Programming"
},
{
"code": null,
"e": 37451,
"s": 37446,
"text": "Java"
},
{
"code": null,
"e": 37549,
"s": 37451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37593,
"s": 37549,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37629,
"s": 37593,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37654,
"s": 37629,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37669,
"s": 37654,
"text": "Stream In Java"
},
{
"code": null,
"e": 37700,
"s": 37669,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 37718,
"s": 37700,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37734,
"s": 37718,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37753,
"s": 37734,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 37778,
"s": 37753,
"text": "Reverse a string in Java"
}
] |
Introduction to pygame - GeeksforGeeks | 08 Oct, 2020
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.
Installing pygame: Pygame requires Python; if you don’t already have it, you can download it from python.org. Use python 3.6.1 or greater, because it is much friendlier to newbies, and additionally runs faster.The best way to install pygame is with the pip tool (which python uses to install packages). Note, this comes with python in recent versions. We use the –user flag to tell it to install into the home directory, rather than globally.
python3 -m pip install -U pygame --user
To see if it works, run one of the included examples:
python3 -m pygame.examples.aliens
If it works, we are ready to go!Once you have installed pygame, you’re ready to create your very first pygame instance.
Python3
# import the pygame moduleimport pygame # import pygame.locals for easier# access to key coordinatesfrom pygame.locals import * # Define our square object and call super to# give it all the properties and methods of pygame.sprite.Sprite# Define the class for our square objectsclass Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() # Define the dimension of the surface # Here we are making squares of side 25px self.surf = pygame.Surface((25, 25)) # Define the color of the surface using RGB color coding. self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect() # initialize pygamepygame.init() # Define the dimensions of screen objectscreen = pygame.display.set_mode((800, 600)) # instantiate all square objectssquare1 = Square()square2 = Square()square3 = Square()square4 = Square() # Variable to keep our game loop runninggameOn = True # Our game loopwhile gameOn: # for loop through the event queue for event in pygame.event.get(): # Check for KEYDOWN event if event.type == KEYDOWN: # If the Backspace key has been pressed set # running to false to exit the main loop if event.key == K_BACKSPACE: gameOn = False # Check for QUIT event elif event.type == QUIT: gameOn = False # Define where the squares will appear on the screen # Use blit to draw them on the screen surface screen.blit(square1.surf, (40, 40)) screen.blit(square2.surf, (40, 530)) screen.blit(square3.surf, (730, 40)) screen.blit(square4.surf, (730, 530)) # Update the display using flip pygame.display.flip()
The above Python code is a simple pygame script to draw four cyan color squares.
Output:
Don’t worry! We will learn a lot more about how to make an object move, how to add animation effects, buttons, music and much more in the next few articles but for now let’s understand this basic code which contains all the necessary pygame elements.
import pygame
from pygame.locals import *
In the first few lines, we import pygame and pygame.locals which is necessary to do before using any module in python.
Sprite: Sprite is just a 2d object that we draw on the screen. We can use them by extending the sprite class. Surf: Surfaces are like blank sheets of paper on which we draw. Our screen object is also a Surface. They can hold images as well. Rects: Rectangular area that we define on a surface.
Python3
class Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect()
Note: We are using RGB format of color coding in which we can form different colors by giving Red, Blue, and Green color values in the range of 0-255. A tuple of (0, 0, 0) is the color black as there is no color present and a tuple of (255, 255, 255) is the color white.In our code, we are extending the sprite class so that we can use surfs and rects to draw our squares. We have made a surface of dimension 25x25px and filled it will a color: (0, 200, 255)
Python3
pygame.init() screen = pygame.display.set_mode((800, 600)) square1 = Square()square2 = Square()square3 = Square()square4 = Square()
The above lines of code initialize pygame using the command pygame.init() which is necessary to use the pygame module commands. After that, we define our screen object and its dimensions in pixels. Then in the next lines, we initialize our four squares.
Python3
while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: running = False elif event.type == QUIT: running = False
The most important part of the game development code is the game loop. This loop continuously runs in the background until the user ends the game or the game is over. Right now our game loop is not much to look forward to. It only tracks two basic events. We can add more events according to the game state, user inputs, and much more but the point to remember here is that the game loop must end after some condition else the user will be stuck in the game loop forever.
Blit: Blit keyword is used to draw a surface on another surface. In simple words when we draw a surface we just blit it onto some other surface.Flip: It is used to update the entire screen after everything is drawn. Remember that the flip only works after drawing all the necessary surfaces otherwise, it will update nothing.
Python3
screen.blit(square1.surf, (40, 40))screen.blit(square2.surf, (40, 530))screen.blit(square3.surf, (730, 40))screen.blit(square4.surf, (730, 530)) pygame.display.flip()
In the above lines of code first, we blit four squares on the screen, and then we flip to make them appear.
pulkitagarwal03pulkit
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25687,
"s": 25659,
"text": "\n08 Oct, 2020"
},
{
"code": null,
"e": 25995,
"s": 25687,
"text": "Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. "
},
{
"code": null,
"e": 26440,
"s": 25995,
"text": "Installing pygame: Pygame requires Python; if you don’t already have it, you can download it from python.org. Use python 3.6.1 or greater, because it is much friendlier to newbies, and additionally runs faster.The best way to install pygame is with the pip tool (which python uses to install packages). Note, this comes with python in recent versions. We use the –user flag to tell it to install into the home directory, rather than globally. "
},
{
"code": null,
"e": 26483,
"s": 26440,
"text": "python3 -m pip install -U pygame --user\n\n\n"
},
{
"code": null,
"e": 26539,
"s": 26483,
"text": "To see if it works, run one of the included examples: "
},
{
"code": null,
"e": 26576,
"s": 26539,
"text": "python3 -m pygame.examples.aliens\n\n\n"
},
{
"code": null,
"e": 26698,
"s": 26576,
"text": "If it works, we are ready to go!Once you have installed pygame, you’re ready to create your very first pygame instance. "
},
{
"code": null,
"e": 26706,
"s": 26698,
"text": "Python3"
},
{
"code": "# import the pygame moduleimport pygame # import pygame.locals for easier# access to key coordinatesfrom pygame.locals import * # Define our square object and call super to# give it all the properties and methods of pygame.sprite.Sprite# Define the class for our square objectsclass Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() # Define the dimension of the surface # Here we are making squares of side 25px self.surf = pygame.Surface((25, 25)) # Define the color of the surface using RGB color coding. self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect() # initialize pygamepygame.init() # Define the dimensions of screen objectscreen = pygame.display.set_mode((800, 600)) # instantiate all square objectssquare1 = Square()square2 = Square()square3 = Square()square4 = Square() # Variable to keep our game loop runninggameOn = True # Our game loopwhile gameOn: # for loop through the event queue for event in pygame.event.get(): # Check for KEYDOWN event if event.type == KEYDOWN: # If the Backspace key has been pressed set # running to false to exit the main loop if event.key == K_BACKSPACE: gameOn = False # Check for QUIT event elif event.type == QUIT: gameOn = False # Define where the squares will appear on the screen # Use blit to draw them on the screen surface screen.blit(square1.surf, (40, 40)) screen.blit(square2.surf, (40, 530)) screen.blit(square3.surf, (730, 40)) screen.blit(square4.surf, (730, 530)) # Update the display using flip pygame.display.flip()",
"e": 28455,
"s": 26706,
"text": null
},
{
"code": null,
"e": 28536,
"s": 28455,
"text": "The above Python code is a simple pygame script to draw four cyan color squares."
},
{
"code": null,
"e": 28544,
"s": 28536,
"text": "Output:"
},
{
"code": null,
"e": 28797,
"s": 28544,
"text": "Don’t worry! We will learn a lot more about how to make an object move, how to add animation effects, buttons, music and much more in the next few articles but for now let’s understand this basic code which contains all the necessary pygame elements. "
},
{
"code": null,
"e": 28841,
"s": 28797,
"text": "import pygame\n\nfrom pygame.locals import *\n"
},
{
"code": null,
"e": 28961,
"s": 28841,
"text": "In the first few lines, we import pygame and pygame.locals which is necessary to do before using any module in python. "
},
{
"code": null,
"e": 29257,
"s": 28961,
"text": "Sprite: Sprite is just a 2d object that we draw on the screen. We can use them by extending the sprite class. Surf: Surfaces are like blank sheets of paper on which we draw. Our screen object is also a Surface. They can hold images as well. Rects: Rectangular area that we define on a surface. "
},
{
"code": null,
"e": 29265,
"s": 29257,
"text": "Python3"
},
{
"code": "class Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect()",
"e": 29484,
"s": 29265,
"text": null
},
{
"code": null,
"e": 29945,
"s": 29484,
"text": "Note: We are using RGB format of color coding in which we can form different colors by giving Red, Blue, and Green color values in the range of 0-255. A tuple of (0, 0, 0) is the color black as there is no color present and a tuple of (255, 255, 255) is the color white.In our code, we are extending the sprite class so that we can use surfs and rects to draw our squares. We have made a surface of dimension 25x25px and filled it will a color: (0, 200, 255) "
},
{
"code": null,
"e": 29953,
"s": 29945,
"text": "Python3"
},
{
"code": "pygame.init() screen = pygame.display.set_mode((800, 600)) square1 = Square()square2 = Square()square3 = Square()square4 = Square()",
"e": 30085,
"s": 29953,
"text": null
},
{
"code": null,
"e": 30340,
"s": 30085,
"text": "The above lines of code initialize pygame using the command pygame.init() which is necessary to use the pygame module commands. After that, we define our screen object and its dimensions in pixels. Then in the next lines, we initialize our four squares. "
},
{
"code": null,
"e": 30348,
"s": 30340,
"text": "Python3"
},
{
"code": "while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: running = False elif event.type == QUIT: running = False",
"e": 30562,
"s": 30348,
"text": null
},
{
"code": null,
"e": 31036,
"s": 30562,
"text": "The most important part of the game development code is the game loop. This loop continuously runs in the background until the user ends the game or the game is over. Right now our game loop is not much to look forward to. It only tracks two basic events. We can add more events according to the game state, user inputs, and much more but the point to remember here is that the game loop must end after some condition else the user will be stuck in the game loop forever. "
},
{
"code": null,
"e": 31364,
"s": 31036,
"text": "Blit: Blit keyword is used to draw a surface on another surface. In simple words when we draw a surface we just blit it onto some other surface.Flip: It is used to update the entire screen after everything is drawn. Remember that the flip only works after drawing all the necessary surfaces otherwise, it will update nothing. "
},
{
"code": null,
"e": 31372,
"s": 31364,
"text": "Python3"
},
{
"code": "screen.blit(square1.surf, (40, 40))screen.blit(square2.surf, (40, 530))screen.blit(square3.surf, (730, 40))screen.blit(square4.surf, (730, 530)) pygame.display.flip()",
"e": 31539,
"s": 31372,
"text": null
},
{
"code": null,
"e": 31649,
"s": 31539,
"text": "In the above lines of code first, we blit four squares on the screen, and then we flip to make them appear. "
},
{
"code": null,
"e": 31671,
"s": 31649,
"text": "pulkitagarwal03pulkit"
},
{
"code": null,
"e": 31685,
"s": 31671,
"text": "Python-PyGame"
},
{
"code": null,
"e": 31692,
"s": 31685,
"text": "Python"
},
{
"code": null,
"e": 31790,
"s": 31692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31808,
"s": 31790,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31843,
"s": 31808,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31875,
"s": 31843,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31897,
"s": 31875,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31939,
"s": 31897,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31969,
"s": 31939,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31995,
"s": 31969,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32024,
"s": 31995,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 32068,
"s": 32024,
"text": "Reading and Writing to text files in Python"
}
] |
Solidity - Abstract Contract - GeeksforGeeks | 11 May, 2022
Abstract contracts are contracts that have at least one function without its implementation. An instance of an abstract cannot be created. Abstract contracts are used as base contracts so that the child contract can inherit and utilize its functions. The abstract contract defines the structure of the contract and any derived contract inherited from it should provide an implementation for the incomplete functions, and if the derived contract is also not implementing the incomplete functions then that derived contract will also be marked as abstract. In Solidity there is no abstract keyword for creating an abstract contract, a contract itself becomes abstract if it has unimplemented functions.
Example: In the below example, an abstract contract is created which is inherited by another contract that has implemented all the functions of the abstract contract. Abstract contract instance is created in the calling contract and an object of child contract is created. Using the object of child contract all the abstract functions that are implemented in the child contract are invoked.
Solidity
// Solidity program to // demonstrate // Abstract contractpragma solidity 0.4.19; // Creating an abstract contractcontract abstractContract { // Declaring functions function getStr( string _strIn) public view returns( string memory); function setValue(uint _in1, uint _in2) public; function add() public returns(uint);} // Child contract inheriting // an abstract parent // contract 'abstractContract'contract derivedContract is abstractContract{ // Declaring private // variables uint private num1; uint private num2; // Defining functions inherited // from abstract parent contract function getStr( string _strIn) public view returns( string memory){ return _strIn; } function setValue( uint _in1, uint _in2) public{ num1 = _in1; num2 = _in2; } function add() public returns(uint){ return (num2 + num1); } } // Caller contractcontract call{ // Creating an instance of // an abstract contract abstractContract abs; // Creating an object of // child contract function call(){ abs = new derivedContract(); } // Calling functions inherited // from abstract contract function getValues( ) public returns (uint){ abs.setValue(10, 16); abs.getStr("GeeksForGeeks"); return abs.add(); } }
Output :
Here, abstractContract contract is an abstract contract that has some functions without their implementation, and derivedContract is its child contract. The getStr() and setValues() functions takes string and values, while the add() function adds the values of setValues() function. abs is an object of abstractContract which creates an instance of derivedContract in call contract that uses the variables of the contract and calls the functions.
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Storage vs Memory in Solidity
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
How to connect ReactJS with MetaMask ?
How to Become a Blockchain Developer?
Proof of Work (PoW) Consensus
Storage vs Memory in Solidity
Solidity - Inheritance
Mathematical Operations in Solidity
How to Install Solidity in Windows?
Introduction to Solidity | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26382,
"s": 25681,
"text": "Abstract contracts are contracts that have at least one function without its implementation. An instance of an abstract cannot be created. Abstract contracts are used as base contracts so that the child contract can inherit and utilize its functions. The abstract contract defines the structure of the contract and any derived contract inherited from it should provide an implementation for the incomplete functions, and if the derived contract is also not implementing the incomplete functions then that derived contract will also be marked as abstract. In Solidity there is no abstract keyword for creating an abstract contract, a contract itself becomes abstract if it has unimplemented functions."
},
{
"code": null,
"e": 26773,
"s": 26382,
"text": "Example: In the below example, an abstract contract is created which is inherited by another contract that has implemented all the functions of the abstract contract. Abstract contract instance is created in the calling contract and an object of child contract is created. Using the object of child contract all the abstract functions that are implemented in the child contract are invoked."
},
{
"code": null,
"e": 26782,
"s": 26773,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate // Abstract contractpragma solidity 0.4.19; // Creating an abstract contractcontract abstractContract { // Declaring functions function getStr( string _strIn) public view returns( string memory); function setValue(uint _in1, uint _in2) public; function add() public returns(uint);} // Child contract inheriting // an abstract parent // contract 'abstractContract'contract derivedContract is abstractContract{ // Declaring private // variables uint private num1; uint private num2; // Defining functions inherited // from abstract parent contract function getStr( string _strIn) public view returns( string memory){ return _strIn; } function setValue( uint _in1, uint _in2) public{ num1 = _in1; num2 = _in2; } function add() public returns(uint){ return (num2 + num1); } } // Caller contractcontract call{ // Creating an instance of // an abstract contract abstractContract abs; // Creating an object of // child contract function call(){ abs = new derivedContract(); } // Calling functions inherited // from abstract contract function getValues( ) public returns (uint){ abs.setValue(10, 16); abs.getStr(\"GeeksForGeeks\"); return abs.add(); } }",
"e": 28169,
"s": 26782,
"text": null
},
{
"code": null,
"e": 28182,
"s": 28171,
"text": "Output : "
},
{
"code": null,
"e": 28629,
"s": 28182,
"text": "Here, abstractContract contract is an abstract contract that has some functions without their implementation, and derivedContract is its child contract. The getStr() and setValues() functions takes string and values, while the add() function adds the values of setValues() function. abs is an object of abstractContract which creates an instance of derivedContract in call contract that uses the variables of the contract and calls the functions."
},
{
"code": null,
"e": 28640,
"s": 28629,
"text": "Blockchain"
},
{
"code": null,
"e": 28649,
"s": 28640,
"text": "Solidity"
},
{
"code": null,
"e": 28747,
"s": 28649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28777,
"s": 28747,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 28849,
"s": 28777,
"text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network"
},
{
"code": null,
"e": 28888,
"s": 28849,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 28926,
"s": 28888,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 28956,
"s": 28926,
"text": "Proof of Work (PoW) Consensus"
},
{
"code": null,
"e": 28986,
"s": 28956,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 29009,
"s": 28986,
"text": "Solidity - Inheritance"
},
{
"code": null,
"e": 29045,
"s": 29009,
"text": "Mathematical Operations in Solidity"
},
{
"code": null,
"e": 29081,
"s": 29045,
"text": "How to Install Solidity in Windows?"
}
] |
C++ Library - <exception> | It is a standard exception class. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type by reference.
Following is the declaration for std::exception.
class exception;
In below example for std::exception.
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n) {
for (int cnt = 0; cnt < 100; ++cnt) {
while (lock.test_and_set(std::memory_order_acquire))
;
std::cout << "Output from thread " << n << '\n';
lock.clear(std::memory_order_release);
}
}
int main() {
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2808,
"s": 2603,
"text": "It is a standard exception class. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type by reference."
},
{
"code": null,
"e": 2857,
"s": 2808,
"text": "Following is the declaration for std::exception."
},
{
"code": null,
"e": 2874,
"s": 2857,
"text": "class exception;"
},
{
"code": null,
"e": 2911,
"s": 2874,
"text": "In below example for std::exception."
},
{
"code": null,
"e": 3424,
"s": 2911,
"text": "#include <thread>\n#include <vector>\n#include <iostream>\n#include <atomic>\n \nstd::atomic_flag lock = ATOMIC_FLAG_INIT;\n \nvoid f(int n) {\n for (int cnt = 0; cnt < 100; ++cnt) {\n while (lock.test_and_set(std::memory_order_acquire))\n ;\n std::cout << \"Output from thread \" << n << '\\n';\n lock.clear(std::memory_order_release);\n }\n}\n \nint main() {\n std::vector<std::thread> v;\n for (int n = 0; n < 10; ++n) {\n v.emplace_back(f, n);\n }\n for (auto& t : v) {\n t.join();\n }\n}"
},
{
"code": null,
"e": 3431,
"s": 3424,
"text": " Print"
},
{
"code": null,
"e": 3442,
"s": 3431,
"text": " Add Notes"
}
] |
Basic System Controls with Terminal in Linux - GeeksforGeeks | 16 Jul, 2020
Sometimes some of the basic services of the system stop working or starts malfunctioning. And it becomes really difficult to solve the problem through Graphical User Interface so here is the list of Terminal Command to solve the problem and to control the basic services manually.
Installing the required packages
To control the basic system services, install the basic required tools. For Debian based systems use the following command to install the required tools.
sudo apt-get install Bluetooth bluez bluez-tools rfkill
Check whether the Bluetooth device is blocked or not using the following command.
sudo rfkill list
It will display the status of the Bluetooth device.
Unblocking the blocked service
If the service is blocked execute the following command to unblock the services. To unblock Bluetooth enter the following command.
sudo rfkill unblock bluetooth
To unblock wifi enter the following command.
sudo rfkill unblock wifi
Starting Bluetooth service
To start the Bluetooth services enter the following command.
sudo service bluetooth start
Stopping Bluetooth service
To stop the Bluetooth services enter the following command.
sudo service bluetooth stop
Executing the above command will output the following results.
Starting Wi-Fi service
To start wifi services enter the following command.
nmcli radio wifi on
Stopping Wi-Fi service
To stop wifi services enter the following command.
nmcli radio wifi off
Executing the above command will output the following results.
Enter the following command to lock the screen.
gnome-screensaver-command -l
Executing the above command will output the following results.
Shutting down system
To shut down, the system instantly enters the following command.
shutdown 0
Shutting down at specific time
To shut down the system at 13:30 enters the following command.
shutdown -h 13:30
Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results.
Rebooting system
To reboot the system instantly, enter the following command.
shutdown -r now
Rebooting at specific time
To reboot the system at 13:30 enter the following command.
shutdown -r 13:30
Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results.
linux
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
'crontab' in Linux with Examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
ps command in Linux with Examples | [
{
"code": null,
"e": 24247,
"s": 24219,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24528,
"s": 24247,
"text": "Sometimes some of the basic services of the system stop working or starts malfunctioning. And it becomes really difficult to solve the problem through Graphical User Interface so here is the list of Terminal Command to solve the problem and to control the basic services manually."
},
{
"code": null,
"e": 24561,
"s": 24528,
"text": "Installing the required packages"
},
{
"code": null,
"e": 24715,
"s": 24561,
"text": "To control the basic system services, install the basic required tools. For Debian based systems use the following command to install the required tools."
},
{
"code": null,
"e": 24771,
"s": 24715,
"text": "sudo apt-get install Bluetooth bluez bluez-tools rfkill"
},
{
"code": null,
"e": 24853,
"s": 24771,
"text": "Check whether the Bluetooth device is blocked or not using the following command."
},
{
"code": null,
"e": 24870,
"s": 24853,
"text": "sudo rfkill list"
},
{
"code": null,
"e": 24922,
"s": 24870,
"text": "It will display the status of the Bluetooth device."
},
{
"code": null,
"e": 24953,
"s": 24922,
"text": "Unblocking the blocked service"
},
{
"code": null,
"e": 25084,
"s": 24953,
"text": "If the service is blocked execute the following command to unblock the services. To unblock Bluetooth enter the following command."
},
{
"code": null,
"e": 25114,
"s": 25084,
"text": "sudo rfkill unblock bluetooth"
},
{
"code": null,
"e": 25159,
"s": 25114,
"text": "To unblock wifi enter the following command."
},
{
"code": null,
"e": 25184,
"s": 25159,
"text": "sudo rfkill unblock wifi"
},
{
"code": null,
"e": 25211,
"s": 25184,
"text": "Starting Bluetooth service"
},
{
"code": null,
"e": 25272,
"s": 25211,
"text": "To start the Bluetooth services enter the following command."
},
{
"code": null,
"e": 25301,
"s": 25272,
"text": "sudo service bluetooth start"
},
{
"code": null,
"e": 25328,
"s": 25301,
"text": "Stopping Bluetooth service"
},
{
"code": null,
"e": 25388,
"s": 25328,
"text": "To stop the Bluetooth services enter the following command."
},
{
"code": null,
"e": 25416,
"s": 25388,
"text": "sudo service bluetooth stop"
},
{
"code": null,
"e": 25479,
"s": 25416,
"text": "Executing the above command will output the following results."
},
{
"code": null,
"e": 25502,
"s": 25479,
"text": "Starting Wi-Fi service"
},
{
"code": null,
"e": 25554,
"s": 25502,
"text": "To start wifi services enter the following command."
},
{
"code": null,
"e": 25574,
"s": 25554,
"text": "nmcli radio wifi on"
},
{
"code": null,
"e": 25597,
"s": 25574,
"text": "Stopping Wi-Fi service"
},
{
"code": null,
"e": 25648,
"s": 25597,
"text": "To stop wifi services enter the following command."
},
{
"code": null,
"e": 25669,
"s": 25648,
"text": "nmcli radio wifi off"
},
{
"code": null,
"e": 25732,
"s": 25669,
"text": "Executing the above command will output the following results."
},
{
"code": null,
"e": 25780,
"s": 25732,
"text": "Enter the following command to lock the screen."
},
{
"code": null,
"e": 25809,
"s": 25780,
"text": "gnome-screensaver-command -l"
},
{
"code": null,
"e": 25872,
"s": 25809,
"text": "Executing the above command will output the following results."
},
{
"code": null,
"e": 25893,
"s": 25872,
"text": "Shutting down system"
},
{
"code": null,
"e": 25958,
"s": 25893,
"text": "To shut down, the system instantly enters the following command."
},
{
"code": null,
"e": 25969,
"s": 25958,
"text": "shutdown 0"
},
{
"code": null,
"e": 26000,
"s": 25969,
"text": "Shutting down at specific time"
},
{
"code": null,
"e": 26063,
"s": 26000,
"text": "To shut down the system at 13:30 enters the following command."
},
{
"code": null,
"e": 26081,
"s": 26063,
"text": "shutdown -h 13:30"
},
{
"code": null,
"e": 26205,
"s": 26081,
"text": "Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results."
},
{
"code": null,
"e": 26222,
"s": 26205,
"text": "Rebooting system"
},
{
"code": null,
"e": 26283,
"s": 26222,
"text": "To reboot the system instantly, enter the following command."
},
{
"code": null,
"e": 26299,
"s": 26283,
"text": "shutdown -r now"
},
{
"code": null,
"e": 26326,
"s": 26299,
"text": "Rebooting at specific time"
},
{
"code": null,
"e": 26385,
"s": 26326,
"text": "To reboot the system at 13:30 enter the following command."
},
{
"code": null,
"e": 26403,
"s": 26385,
"text": "shutdown -r 13:30"
},
{
"code": null,
"e": 26527,
"s": 26403,
"text": "Change 13:30 with the time you want to shut the system down. Executing the above command will output the following results."
},
{
"code": null,
"e": 26533,
"s": 26527,
"text": "linux"
},
{
"code": null,
"e": 26547,
"s": 26533,
"text": "linux-command"
},
{
"code": null,
"e": 26558,
"s": 26547,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26656,
"s": 26558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26665,
"s": 26656,
"text": "Comments"
},
{
"code": null,
"e": 26678,
"s": 26665,
"text": "Old Comments"
},
{
"code": null,
"e": 26713,
"s": 26678,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26751,
"s": 26713,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26786,
"s": 26751,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26819,
"s": 26786,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 26856,
"s": 26819,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 26892,
"s": 26856,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 26911,
"s": 26892,
"text": "Compiling with g++"
},
{
"code": null,
"e": 26947,
"s": 26911,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26991,
"s": 26947,
"text": "Mutex lock for Linux Thread Synchronization"
}
] |
Java program to print the factorial of the given number | Factorial of a positive integer n is the product of all values from n to 1. For example, the factorial of 3 is (3 * 2 * 1 = 6).
1. Take integer variable A
2. Assign a value to the variable
3. From value, A up to 1 multiply each digit and store
4. The final stored value is factorial of A
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
int i, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
for(i = 1; i<=number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial of the given number is:: "+factorial);
}
}
Enter the number to which you need to find the factorial:
25
Factorial of the given number is:: 2076180480 | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "Factorial of a positive integer n is the product of all values from n to 1. For example, the factorial of 3 is (3 * 2 * 1 = 6). "
},
{
"code": null,
"e": 1351,
"s": 1191,
"text": "1. Take integer variable A\n2. Assign a value to the variable\n3. From value, A up to 1 multiply each digit and store\n4. The final stored value is factorial of A"
},
{
"code": null,
"e": 1836,
"s": 1351,
"text": "import java.util.Scanner;\n public class Factorial {\n public static void main(String args[]){\n int i, factorial=1, number;\n System.out.println(\"Enter the number to which you need to find the factorial:\");\n Scanner sc = new Scanner(System.in);\n number = sc.nextInt();\n\n for(i = 1; i<=number; i++) {\n factorial = factorial * i;\n }\n System.out.println(\"Factorial of the given number is:: \"+factorial);\n }\n }"
},
{
"code": null,
"e": 1943,
"s": 1836,
"text": "Enter the number to which you need to find the factorial:\n25\nFactorial of the given number is:: 2076180480"
}
] |
Matplotlib.axes.Axes.xcorr() in Python - GeeksforGeeks | 21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.xcorr() function in axes module of matplotlib library is used to plot the cross correlation between x and y.
Syntax: Axes.xcorr(self, x, y, normed=True, detrend=, usevlines=True, maxlags=10, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x, y : These parameter are the sequence of scalar.
detrend: This parameter is an optional parameter. Its default value is mlab.detrend_none
normed: This parameter is also an optional parameter and contains the bool value. Its default value is True
usevlines: This parameter is also an optional parameter and contains the bool value. Its default value is True
maxlags: This parameter is also an optional parameter and contains the integer value. Its default value is 10
linestyle: This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False.
marker: This parameter is also an optional parameter and contains the string. Its default value is ‘o’
Returns: This method returns the following:
lags:This method returns the lag vector
c:This method returns the auto correlation vector.
line : Added LineCollection if usevlines is True, otherwise add Line2D.
b: This method returns the horizontal line at 0 if usevlines is True, otherwise None.
The resultant is (lags, c, line, b).
Below examples illustrate the matplotlib.axes.Axes.xcorr() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # Time series datageeksx = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) geeksy = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) # Plot autocorrelationfig, ax = plt.subplots()ax.xcorr(geeksx, geeksy, maxlags = 9, color ="green") # Add labels to autocorrelation # plotax.xlabel('X-axis')ax.set_ylabel('Y-axis')ax.set_xlabel('X-axis') ax.set_title('matplotlib.axes.Axes.xcorr() Example') plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # Fixing random state for# reproducibilitynp.random.seed(10**7)geeksx = np.random.randn(100)geeksy = np.random.randn(100) fig, ax = plt.subplots()ax.xcorr(geeksx, geeksy, usevlines = True, normed = True, maxlags = 80, color ="green") ax.grid(True) ax.set_title('matplotlib.axes.Axes.xcorr() Example') plt.show()
Output:
Python-matplotlib
Python
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": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24201,
"s": 23901,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 24319,
"s": 24201,
"text": "The Axes.xcorr() function in axes module of matplotlib library is used to plot the cross correlation between x and y."
},
{
"code": null,
"e": 24425,
"s": 24319,
"text": "Syntax: Axes.xcorr(self, x, y, normed=True, detrend=, usevlines=True, maxlags=10, *, data=None, **kwargs)"
},
{
"code": null,
"e": 24507,
"s": 24425,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 24558,
"s": 24507,
"text": "x, y : These parameter are the sequence of scalar."
},
{
"code": null,
"e": 24647,
"s": 24558,
"text": "detrend: This parameter is an optional parameter. Its default value is mlab.detrend_none"
},
{
"code": null,
"e": 24755,
"s": 24647,
"text": "normed: This parameter is also an optional parameter and contains the bool value. Its default value is True"
},
{
"code": null,
"e": 24866,
"s": 24755,
"text": "usevlines: This parameter is also an optional parameter and contains the bool value. Its default value is True"
},
{
"code": null,
"e": 24976,
"s": 24866,
"text": "maxlags: This parameter is also an optional parameter and contains the integer value. Its default value is 10"
},
{
"code": null,
"e": 25101,
"s": 24976,
"text": "linestyle: This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False."
},
{
"code": null,
"e": 25204,
"s": 25101,
"text": "marker: This parameter is also an optional parameter and contains the string. Its default value is ‘o’"
},
{
"code": null,
"e": 25248,
"s": 25204,
"text": "Returns: This method returns the following:"
},
{
"code": null,
"e": 25288,
"s": 25248,
"text": "lags:This method returns the lag vector"
},
{
"code": null,
"e": 25339,
"s": 25288,
"text": "c:This method returns the auto correlation vector."
},
{
"code": null,
"e": 25411,
"s": 25339,
"text": "line : Added LineCollection if usevlines is True, otherwise add Line2D."
},
{
"code": null,
"e": 25497,
"s": 25411,
"text": "b: This method returns the horizontal line at 0 if usevlines is True, otherwise None."
},
{
"code": null,
"e": 25534,
"s": 25497,
"text": "The resultant is (lags, c, line, b)."
},
{
"code": null,
"e": 25622,
"s": 25534,
"text": "Below examples illustrate the matplotlib.axes.Axes.xcorr() function in matplotlib.axes:"
},
{
"code": null,
"e": 25633,
"s": 25622,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # Time series datageeksx = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) geeksy = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) # Plot autocorrelationfig, ax = plt.subplots()ax.xcorr(geeksx, geeksy, maxlags = 9, color =\"green\") # Add labels to autocorrelation # plotax.xlabel('X-axis')ax.set_ylabel('Y-axis')ax.set_xlabel('X-axis') ax.set_title('matplotlib.axes.Axes.xcorr() Example') plt.show()",
"e": 26319,
"s": 25633,
"text": null
},
{
"code": null,
"e": 26327,
"s": 26319,
"text": "Output:"
},
{
"code": null,
"e": 26338,
"s": 26327,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # Fixing random state for# reproducibilitynp.random.seed(10**7)geeksx = np.random.randn(100)geeksy = np.random.randn(100) fig, ax = plt.subplots()ax.xcorr(geeksx, geeksy, usevlines = True, normed = True, maxlags = 80, color =\"green\") ax.grid(True) ax.set_title('matplotlib.axes.Axes.xcorr() Example') plt.show()",
"e": 26764,
"s": 26338,
"text": null
},
{
"code": null,
"e": 26772,
"s": 26764,
"text": "Output:"
},
{
"code": null,
"e": 26790,
"s": 26772,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26797,
"s": 26790,
"text": "Python"
},
{
"code": null,
"e": 26895,
"s": 26797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26904,
"s": 26895,
"text": "Comments"
},
{
"code": null,
"e": 26917,
"s": 26904,
"text": "Old Comments"
},
{
"code": null,
"e": 26953,
"s": 26917,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26976,
"s": 26953,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27015,
"s": 26976,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27048,
"s": 27015,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 27097,
"s": 27048,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27138,
"s": 27097,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 27154,
"s": 27138,
"text": "loops in python"
},
{
"code": null,
"e": 27205,
"s": 27154,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 27237,
"s": 27205,
"text": "Python Dictionary keys() method"
}
] |
How do I programmatically “restart” an Android app? | There are some situations, we need to restart whole application programmatically. This example demonstrates how do I programmatically “restart” an Android app.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "28sp"
android:textAlignment = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view. When the user clicks on text view, it will restart the whole application.
package com.example.andy.myapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textview;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textview = findViewById(R.id.text);
textview.setText("Click here to restart activity");
textview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
}
});
}
}
In the above code, we have taken text view, when a user clicks on text view, it will restart the whole application as shown below -
Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
When you click on text view, it will restart application again after some time.
Click here to download the project code | [
{
"code": null,
"e": 1222,
"s": 1062,
"text": "There are some situations, we need to restart whole application programmatically. This example demonstrates how do I programmatically “restart” an Android app."
},
{
"code": null,
"e": 1351,
"s": 1222,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1416,
"s": 1351,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2024,
"s": 1416,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"28sp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2144,
"s": 2024,
"text": "In the above code, we have taken a text view. When the user clicks on text view, it will restart the whole application."
},
{
"code": null,
"e": 3572,
"s": 2144,
"text": "package com.example.andy.myapplication;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textview;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textview = findViewById(R.id.text);\n textview.setText(\"Click here to restart activity\");\n textview.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);\n int mPendingIntentId = 123456;\n PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);\n AlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);\n mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);\nSystem.exit(0);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3704,
"s": 3572,
"text": "In the above code, we have taken text view, when a user clicks on text view, it will restart the whole application as shown below -"
},
{
"code": null,
"e": 4141,
"s": 3704,
"text": "Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);\nint mPendingIntentId = 123456;\nPendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);\nAlarmManager mgr = (AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);\nmgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);\nSystem.exit(0);"
},
{
"code": null,
"e": 4488,
"s": 4141,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4568,
"s": 4488,
"text": "When you click on text view, it will restart application again after some time."
},
{
"code": null,
"e": 4608,
"s": 4568,
"text": "Click here to download the project code"
}
] |
How to change the permission of a directory using Python? | On a platform with the chmod command available, you could call the chmod command like this:
>>> import subprocess
>>> subprocess.call(['chmod', '-R', '+w', 'my_folder'])
If you want to use the os module, you'll have to recursively write it:
Using os:
import os
def change_permissions_recursive(path, mode):
for root, dirs, files in os.walk(path, topdown=False):
for dir in [os.path.join(root,d) for d in dirs]:
os.chmod(dir, mode)
for file in [os.path.join(root, f) for f in files]:
os.chmod(file, mode)
change_permissions_recursive('my_folder', 0o777)
This will change the permissions of my_folder, all its files and subfolders to 0o777. | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "On a platform with the chmod command available, you could call the chmod command like this:"
},
{
"code": null,
"e": 1232,
"s": 1154,
"text": ">>> import subprocess\n>>> subprocess.call(['chmod', '-R', '+w', 'my_folder'])"
},
{
"code": null,
"e": 1303,
"s": 1232,
"text": "If you want to use the os module, you'll have to recursively write it:"
},
{
"code": null,
"e": 1655,
"s": 1303,
"text": "Using os:\nimport os\ndef change_permissions_recursive(path, mode):\n for root, dirs, files in os.walk(path, topdown=False):\n for dir in [os.path.join(root,d) for d in dirs]:\n os.chmod(dir, mode)\n for file in [os.path.join(root, f) for f in files]:\n os.chmod(file, mode)\nchange_permissions_recursive('my_folder', 0o777)"
},
{
"code": null,
"e": 1742,
"s": 1655,
"text": " This will change the permissions of my_folder, all its files and subfolders to 0o777."
}
] |
How to Implement Priority Queue in Python? | The queue module provides a first-in, first-out (FIFO), Last-in, First out (LIFO) data structure suitable for multi-threaded programming. Queues can be used to pass data or any wide range of information e.g. session details, paths, variables,.. between creator and consumer threads safely. Locking is generally handled for the caller.
Note : This discussion assumes you already understand the general nature of a queue. If you do not, you may want to read some of the references before continuing.
1. Let us implement a basic FIFO Queue.
import queue
fifo = queue.Queue()
# put numbers into queue
for i in range(5):
fifo.put(i)
# if not empty get the numbers from queue
print(f"Ouput \n")
while not fifo.empty():
print(f" {fifo.get()} ")
0
1
2
3
4
2. The above example uses a single thread to show how the elements are removed from the queue in the same order in which they are inserted.
3. Let us implement a basic LIFO Queue.
import queue
lifo = queue.LifoQueue()
# put numbers into queue
for i in range(5):
lifo.put(i)
print(f"Ouput \n")
# if not empty get the numbers from queue
while not lifo.empty():
print(f" {lifo.get()} ")
4
3
2
1
0
4. The above example shows, that the most recently put into the queue is removed by get.
5. Finally, we will see how to implement priority queue.
Sometimes the processing order of the items in a queue needs to be based on priority of those items, rather than just the order they are created or added to the queue. For instance, a business critical job running in producton requires highest CPU and precedence over a print something job that a developer wants to print. PriorityQueue uses the sort order of the contents of the queue to decide which item to retrieve.
import queue
import threading
# Class to get the priority and description and validate the priority
class Job:
def __init__(self, priority, description):
self.priority = priority
self.description = description
print('New job:', description)
return
def __eq__(self, other):
try:
return self.priority == other.priority
except AttributeError:
return NotImplemented
def __lt__(self, other):
try:
return self.priority < other.priority
except AttributeError:
return NotImplemented
# create a priority queue and define the priority
q = queue.PriorityQueue()
q.put(Job(90, 'Developer-Print job'))
q.put(Job(2, 'Business-Report job'))
q.put(Job(1, 'Business-Critical Job'))
# process the job
def process_job(q):
while True:
next_job = q.get()
print(f" *** Now, Processing the job - {next_job.description}")
q.task_done()
# define the threads
workers = [
threading.Thread(target=process_job, args=(q,)),
threading.Thread(target=process_job, args=(q,)), ]
# call the threads and join them.
for w in workers:
w.setDaemon(True)
w.start()
q.join()
job: Developer-Print job
New job: Business-Report job
New job: Business-Critical Job
*** Now, Processing the job - Business-Critical Job
*** Now, Processing the job - Business-Report job
*** Now, Processing the job - Developer-Print job
6. This example has multiple threads consuming the jobs, which are processed based on the priority of items in the queue at the time get() was called. The order of processing is based on the business criticallity irrespective of what order they have been added. | [
{
"code": null,
"e": 1397,
"s": 1062,
"text": "The queue module provides a first-in, first-out (FIFO), Last-in, First out (LIFO) data structure suitable for multi-threaded programming. Queues can be used to pass data or any wide range of information e.g. session details, paths, variables,.. between creator and consumer threads safely. Locking is generally handled for the caller."
},
{
"code": null,
"e": 1560,
"s": 1397,
"text": "Note : This discussion assumes you already understand the general nature of a queue. If you do not, you may want to read some of the references before continuing."
},
{
"code": null,
"e": 1600,
"s": 1560,
"text": "1. Let us implement a basic FIFO Queue."
},
{
"code": null,
"e": 1802,
"s": 1600,
"text": "import queue\nfifo = queue.Queue()\n\n# put numbers into queue\nfor i in range(5):\nfifo.put(i)\n\n# if not empty get the numbers from queue\nprint(f\"Ouput \\n\")\nwhile not fifo.empty():\nprint(f\" {fifo.get()} \")"
},
{
"code": null,
"e": 1812,
"s": 1802,
"text": "0\n1\n2\n3\n4"
},
{
"code": null,
"e": 1952,
"s": 1812,
"text": "2. The above example uses a single thread to show how the elements are removed from the queue in the same order in which they are inserted."
},
{
"code": null,
"e": 1992,
"s": 1952,
"text": "3. Let us implement a basic LIFO Queue."
},
{
"code": null,
"e": 2198,
"s": 1992,
"text": "import queue\nlifo = queue.LifoQueue()\n\n# put numbers into queue\nfor i in range(5):\nlifo.put(i)\n\nprint(f\"Ouput \\n\")\n# if not empty get the numbers from queue\nwhile not lifo.empty():\nprint(f\" {lifo.get()} \")"
},
{
"code": null,
"e": 2208,
"s": 2198,
"text": "4\n3\n2\n1\n0"
},
{
"code": null,
"e": 2297,
"s": 2208,
"text": "4. The above example shows, that the most recently put into the queue is removed by get."
},
{
"code": null,
"e": 2354,
"s": 2297,
"text": "5. Finally, we will see how to implement priority queue."
},
{
"code": null,
"e": 2774,
"s": 2354,
"text": "Sometimes the processing order of the items in a queue needs to be based on priority of those items, rather than just the order they are created or added to the queue. For instance, a business critical job running in producton requires highest CPU and precedence over a print something job that a developer wants to print. PriorityQueue uses the sort order of the contents of the queue to decide which item to retrieve."
},
{
"code": null,
"e": 3816,
"s": 2774,
"text": "import queue\nimport threading\n\n# Class to get the priority and description and validate the priority\nclass Job:\ndef __init__(self, priority, description):\nself.priority = priority\nself.description = description\nprint('New job:', description)\nreturn\n\ndef __eq__(self, other):\ntry:\nreturn self.priority == other.priority\nexcept AttributeError:\nreturn NotImplemented\n\ndef __lt__(self, other):\ntry:\nreturn self.priority < other.priority\nexcept AttributeError:\nreturn NotImplemented\n\n# create a priority queue and define the priority\nq = queue.PriorityQueue()\nq.put(Job(90, 'Developer-Print job'))\nq.put(Job(2, 'Business-Report job'))\nq.put(Job(1, 'Business-Critical Job'))\n\n# process the job\ndef process_job(q):\nwhile True:\nnext_job = q.get()\nprint(f\" *** Now, Processing the job - {next_job.description}\")\nq.task_done()\n\n# define the threads\nworkers = [\nthreading.Thread(target=process_job, args=(q,)),\nthreading.Thread(target=process_job, args=(q,)), ]\n\n# call the threads and join them.\nfor w in workers:\nw.setDaemon(True)\nw.start()\n\nq.join()"
},
{
"code": null,
"e": 3901,
"s": 3816,
"text": "job: Developer-Print job\nNew job: Business-Report job\nNew job: Business-Critical Job"
},
{
"code": null,
"e": 4053,
"s": 3901,
"text": "*** Now, Processing the job - Business-Critical Job\n*** Now, Processing the job - Business-Report job\n*** Now, Processing the job - Developer-Print job"
},
{
"code": null,
"e": 4315,
"s": 4053,
"text": "6. This example has multiple threads consuming the jobs, which are processed based on the priority of items in the queue at the time get() was called. The order of processing is based on the business criticallity irrespective of what order they have been added."
}
] |
Loss Function (Part II): Logistic Regression | by Shuyu Luo | Towards Data Science | This series aims to explain loss functions of a few widely-used supervised learning models, and some options of optimization algorithms. In part I, I walked through the optimization process of Linear Regression in details by using Gradient Descent and using Least Squared Error as loss function. In this part, I will move to Logistic Regression.
Remember the hypothesis of linear regression is:
Call this hypothesis of linear regression the raw model output. Logistic regression just has a transformation based on it. For logistic regression, focusing on binary classification here, we have class 0 and class 1. To compare with the target, we want to constrain predictions to some values between 0 and 1. That’s why Sigmoid Function is applied on the raw model output and provides the ability to predict with probability.
What hypothesis function returns is the probability that y = 1, given x, parameterized by θ, written as: h(x) = P(y = 1|x; θ). Decision boundary can be described as: Predict 1, if θTx ≥ 0 → h(x) ≥ 0.5; Predict 0, if θTx < 0 → h(x) < 0.5.
Linear regression uses Least Squared Error as loss function that gives a convex graph and then we can complete the optimization by finding its vertex as global minimum. However, it’s not an option for logistic regression anymore. Since the hypothesis is changed, Least Squared Error will result in a non-convex graph with local minimums by calculating with sigmoid function applied on raw model output.
Intuitively, we want to assign more punishment when predicting 1 while the actual is 0 and when predict 0 while the actual is 1. The loss function of logistic regression is doing this exactly which is called Logistic Loss. See as below. If y = 1, looking at the plot below on left, when prediction = 1, the cost = 0, when prediction = 0, the learning algorithm is punished by a very large cost. Similarly, if y = 0, the plot on right shows, predicting 0 has no punishment but predicting 1 has a large value of cost.
Another advantage of this loss function is that although we are looking at it by y = 1 and y = 0 separately, it can be written as one single formula which brings convenience for calculation:
So the cost function of the model is the summation from all training data samples:
Before fitting the parameters to training data with this cost function, let’s talk about Regularization briefly. There are two commonly used regularization types, L1(Lasso) and L2(Ridge). Instead of optimizing above cost function directly, with regularization, we add a constraint on how big the coefficients can get in order to prevent overfitting. L1 and L2 adapts different ways of setting upper bounds of coefficients, which determines that L1 has the ability to do feature selection by making coefficients 0 for less important features and mitigate the issue of multicollinearity, while L2 also penalizes very large coefficients but does’t make any to 0. There also exists a parameter that controls the weight of the constraint, λ, so that coefficients won’t be punished too hard resulting in underfitting.
In terms of why L1 an L2 have different capabilities due to ‘squared’ and ‘absolute’ value, and how λ effects the weight of regularized term and original fit term, is a very interesting topic. We won’t really dive into it here, but it’s definitely worth your study and research. Following shows how to update original cost function to regularized cost function.
With the right learning algorithm, we can start to fit by minimizing J(θ) as a function of θ to find optimal parameters. We can still apply Gradient Descent as the optimization algorithm. It takes partial derivative of J with respect to θ (the slope of J), and updates θ via each iteration with a selected learning rate α until the Gradient Descent has converged. See the python query below for optimizing L2 regularized logistic regression. There is a good article here that explains vectorized implementation of optimization process in great details.
## Vectorized Implementation of Optimization Using Gradient Descent# Define Cost functiondef cost(t, h, l=l, X=X, y=y, m=m): cost = np.transpose(-y)@np.log(h) - np.transpose(1-y)@np.log(1-h) + (l/2)*np.transpose(t[1:])@t[1:] cost = (1/m)*cost return cost# Define first derivative of cost functiondef cost_dev(j, t, X=X, y=y, m=m): dev = X[:, j]@(1/(1 + np.exp(-X@theta)) - y) dev = (1/m)*dev return dev# Define iterationscost_list = []theta_temp = np.zeros(theta.shape)theta_list = []for i in range(1000000): for j in range(len(theta)): if j == 0: theta_temp[j] = theta[j] - a*cost_dev(j, theta) else: theta_temp[j] = theta[j]*(1 - (a*lmbd)/m) - a*cost_dev(j, theta) theta = theta_temp hypo = 1/(1 + np.exp(-X@theta)) theta_list.append(list(theta)) cost_val = cost(theta, hypo) cost_list.append(cost_val)
I would like to talk a little about another popular optimization algorithm, Newton’s Method, that applies different approach to reach the global minimum of cost function. Similar to Gradient Descent, we firstly take the partial derivative of J(θ) that is the slope of J(θ), and note it as f(θ). Instead of decreasing θ by a certain chosen learning rate α multiplied with f(θ) , Newton’s Method gets an updated θ at the point of intersection of the tangent line of f(θ) at previous θ and x axis. After amount of iterations, Newton’s Method will converge at f(θ) = 0.
See the simplified plot above, Starting from the right, the yellow dotted line is the tangent of f(θ) at the θ0. It determines the position of θ1, and the distance from the θ0 to θ1 is Δ. This process repeats until finding the optimal θ that subjects to f(θ) = 0, which is θ3 in this plot. See the equations of updating θ as below.
Obviously Newton’s Method doesn’t need a chosen fixed learning rate, and the step size of each iteration is larger and varying as well, so that it usually converges faster and pretty efficient with a proper size of features and samples.
To be continued... | [
{
"code": null,
"e": 518,
"s": 172,
"text": "This series aims to explain loss functions of a few widely-used supervised learning models, and some options of optimization algorithms. In part I, I walked through the optimization process of Linear Regression in details by using Gradient Descent and using Least Squared Error as loss function. In this part, I will move to Logistic Regression."
},
{
"code": null,
"e": 567,
"s": 518,
"text": "Remember the hypothesis of linear regression is:"
},
{
"code": null,
"e": 994,
"s": 567,
"text": "Call this hypothesis of linear regression the raw model output. Logistic regression just has a transformation based on it. For logistic regression, focusing on binary classification here, we have class 0 and class 1. To compare with the target, we want to constrain predictions to some values between 0 and 1. That’s why Sigmoid Function is applied on the raw model output and provides the ability to predict with probability."
},
{
"code": null,
"e": 1232,
"s": 994,
"text": "What hypothesis function returns is the probability that y = 1, given x, parameterized by θ, written as: h(x) = P(y = 1|x; θ). Decision boundary can be described as: Predict 1, if θTx ≥ 0 → h(x) ≥ 0.5; Predict 0, if θTx < 0 → h(x) < 0.5."
},
{
"code": null,
"e": 1635,
"s": 1232,
"text": "Linear regression uses Least Squared Error as loss function that gives a convex graph and then we can complete the optimization by finding its vertex as global minimum. However, it’s not an option for logistic regression anymore. Since the hypothesis is changed, Least Squared Error will result in a non-convex graph with local minimums by calculating with sigmoid function applied on raw model output."
},
{
"code": null,
"e": 2151,
"s": 1635,
"text": "Intuitively, we want to assign more punishment when predicting 1 while the actual is 0 and when predict 0 while the actual is 1. The loss function of logistic regression is doing this exactly which is called Logistic Loss. See as below. If y = 1, looking at the plot below on left, when prediction = 1, the cost = 0, when prediction = 0, the learning algorithm is punished by a very large cost. Similarly, if y = 0, the plot on right shows, predicting 0 has no punishment but predicting 1 has a large value of cost."
},
{
"code": null,
"e": 2342,
"s": 2151,
"text": "Another advantage of this loss function is that although we are looking at it by y = 1 and y = 0 separately, it can be written as one single formula which brings convenience for calculation:"
},
{
"code": null,
"e": 2425,
"s": 2342,
"text": "So the cost function of the model is the summation from all training data samples:"
},
{
"code": null,
"e": 3237,
"s": 2425,
"text": "Before fitting the parameters to training data with this cost function, let’s talk about Regularization briefly. There are two commonly used regularization types, L1(Lasso) and L2(Ridge). Instead of optimizing above cost function directly, with regularization, we add a constraint on how big the coefficients can get in order to prevent overfitting. L1 and L2 adapts different ways of setting upper bounds of coefficients, which determines that L1 has the ability to do feature selection by making coefficients 0 for less important features and mitigate the issue of multicollinearity, while L2 also penalizes very large coefficients but does’t make any to 0. There also exists a parameter that controls the weight of the constraint, λ, so that coefficients won’t be punished too hard resulting in underfitting."
},
{
"code": null,
"e": 3599,
"s": 3237,
"text": "In terms of why L1 an L2 have different capabilities due to ‘squared’ and ‘absolute’ value, and how λ effects the weight of regularized term and original fit term, is a very interesting topic. We won’t really dive into it here, but it’s definitely worth your study and research. Following shows how to update original cost function to regularized cost function."
},
{
"code": null,
"e": 4152,
"s": 3599,
"text": "With the right learning algorithm, we can start to fit by minimizing J(θ) as a function of θ to find optimal parameters. We can still apply Gradient Descent as the optimization algorithm. It takes partial derivative of J with respect to θ (the slope of J), and updates θ via each iteration with a selected learning rate α until the Gradient Descent has converged. See the python query below for optimizing L2 regularized logistic regression. There is a good article here that explains vectorized implementation of optimization process in great details."
},
{
"code": null,
"e": 5050,
"s": 4152,
"text": "## Vectorized Implementation of Optimization Using Gradient Descent# Define Cost functiondef cost(t, h, l=l, X=X, y=y, m=m): cost = np.transpose(-y)@np.log(h) - np.transpose(1-y)@np.log(1-h) + (l/2)*np.transpose(t[1:])@t[1:] cost = (1/m)*cost return cost# Define first derivative of cost functiondef cost_dev(j, t, X=X, y=y, m=m): dev = X[:, j]@(1/(1 + np.exp(-X@theta)) - y) dev = (1/m)*dev return dev# Define iterationscost_list = []theta_temp = np.zeros(theta.shape)theta_list = []for i in range(1000000): for j in range(len(theta)): if j == 0: theta_temp[j] = theta[j] - a*cost_dev(j, theta) else: theta_temp[j] = theta[j]*(1 - (a*lmbd)/m) - a*cost_dev(j, theta) theta = theta_temp hypo = 1/(1 + np.exp(-X@theta)) theta_list.append(list(theta)) cost_val = cost(theta, hypo) cost_list.append(cost_val)"
},
{
"code": null,
"e": 5616,
"s": 5050,
"text": "I would like to talk a little about another popular optimization algorithm, Newton’s Method, that applies different approach to reach the global minimum of cost function. Similar to Gradient Descent, we firstly take the partial derivative of J(θ) that is the slope of J(θ), and note it as f(θ). Instead of decreasing θ by a certain chosen learning rate α multiplied with f(θ) , Newton’s Method gets an updated θ at the point of intersection of the tangent line of f(θ) at previous θ and x axis. After amount of iterations, Newton’s Method will converge at f(θ) = 0."
},
{
"code": null,
"e": 5948,
"s": 5616,
"text": "See the simplified plot above, Starting from the right, the yellow dotted line is the tangent of f(θ) at the θ0. It determines the position of θ1, and the distance from the θ0 to θ1 is Δ. This process repeats until finding the optimal θ that subjects to f(θ) = 0, which is θ3 in this plot. See the equations of updating θ as below."
},
{
"code": null,
"e": 6185,
"s": 5948,
"text": "Obviously Newton’s Method doesn’t need a chosen fixed learning rate, and the step size of each iteration is larger and varying as well, so that it usually converges faster and pretty efficient with a proper size of features and samples."
}
] |
Fetch all the ids of MongoDB documents? | To fetch all the ids, simply use find() in MongoDB. Let us create a collection with documents −
> db.demo169.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e36975e9e4f06af551997d7")
}
> db.demo169.insertOne({"StudentName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3697629e4f06af551997d8")
}
> db.demo169.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3697679e4f06af551997d9")
}
Display all documents from a collection with the help of find() method −
> db.demo169.find();
This will produce the following output −
{ "_id" : ObjectId("5e36975e9e4f06af551997d7"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e3697629e4f06af551997d8"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e3697679e4f06af551997d9"), "StudentName" : "David" }
Following is the query to get document ids of all the MongoDB documents in a collection −
> var iterator=db.demo169.find({},{"StudentName":0});
Display all documents from a collection with the help of find() method −
> iterator;
This will produce the following output −
{ "_id" : ObjectId("5e36975e9e4f06af551997d7") }
{ "_id" : ObjectId("5e3697629e4f06af551997d8") }
{ "_id" : ObjectId("5e3697679e4f06af551997d9") } | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To fetch all the ids, simply use find() in MongoDB. Let us create a collection with documents −"
},
{
"code": null,
"e": 1558,
"s": 1158,
"text": "> db.demo169.insertOne({\"StudentName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e36975e9e4f06af551997d7\")\n}\n> db.demo169.insertOne({\"StudentName\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3697629e4f06af551997d8\")\n}\n> db.demo169.insertOne({\"StudentName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3697679e4f06af551997d9\")\n}"
},
{
"code": null,
"e": 1631,
"s": 1558,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1652,
"s": 1631,
"text": "> db.demo169.find();"
},
{
"code": null,
"e": 1693,
"s": 1652,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1913,
"s": 1693,
"text": "{ \"_id\" : ObjectId(\"5e36975e9e4f06af551997d7\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e3697629e4f06af551997d8\"), \"StudentName\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e3697679e4f06af551997d9\"), \"StudentName\" : \"David\" }"
},
{
"code": null,
"e": 2003,
"s": 1913,
"text": "Following is the query to get document ids of all the MongoDB documents in a collection −"
},
{
"code": null,
"e": 2057,
"s": 2003,
"text": "> var iterator=db.demo169.find({},{\"StudentName\":0});"
},
{
"code": null,
"e": 2130,
"s": 2057,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2142,
"s": 2130,
"text": "> iterator;"
},
{
"code": null,
"e": 2183,
"s": 2142,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2330,
"s": 2183,
"text": "{ \"_id\" : ObjectId(\"5e36975e9e4f06af551997d7\") }\n{ \"_id\" : ObjectId(\"5e3697629e4f06af551997d8\") }\n{ \"_id\" : ObjectId(\"5e3697679e4f06af551997d9\") }"
}
] |
SQL | Advanced Functions - GeeksforGeeks | 07 Nov, 2019
Following are some of the advanced functions defined in SQL:
BIN(): It converts a decimal number to a binary number.Syntax:SELECT BIN(18);
Output:BINARY(): It converts a value to a binary stringSyntax:SELECT BINARY "GeeksforGeeks";Output:COALESCE(): It returns the first non-null expression in a list.Syntax:SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');
Output:CONNECTION_ID(): It returns the unique connection ID for the current connection.Syntax:SELECT CONNECTION_ID();
Output:CURRENT_USER(): It returns the user name and host name for the MySQL account used by the server to authenticate the current client.Syntax:SELECT CURRENT_USER();
Output:DATABASE(): It returns the name of the default database.Syntax:SELECT DATABASE();
Output:IF(): It returns one value if a condition is TRUE, or another value if a condition is FALSE.Syntax:SELECT IF(200<500, "YES", "NO");
Output:LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement.Syntax:SELECT LAST_INSERT_ID();
Output:NULLIF(): It returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.Syntax:SELECT NULLIF(25.11, 25);
Output:Syntax:SELECT NULLIF(115, 115);
Output:SESSION_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SESSION_USER();Output:SYSTEM_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SYSTEM_USER();
Output:USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT USER();
Output:VERSION(): It returns the version of the MySQL database.Syntax:SELECT VERSION();
Output:
BIN(): It converts a decimal number to a binary number.Syntax:SELECT BIN(18);
Output:
SELECT BIN(18);
Output:
BINARY(): It converts a value to a binary stringSyntax:SELECT BINARY "GeeksforGeeks";Output:
SELECT BINARY "GeeksforGeeks";
Output:
COALESCE(): It returns the first non-null expression in a list.Syntax:SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');
Output:
SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');
Output:
CONNECTION_ID(): It returns the unique connection ID for the current connection.Syntax:SELECT CONNECTION_ID();
Output:
SELECT CONNECTION_ID();
Output:
CURRENT_USER(): It returns the user name and host name for the MySQL account used by the server to authenticate the current client.Syntax:SELECT CURRENT_USER();
Output:
SELECT CURRENT_USER();
Output:
DATABASE(): It returns the name of the default database.Syntax:SELECT DATABASE();
Output:
SELECT DATABASE();
Output:
IF(): It returns one value if a condition is TRUE, or another value if a condition is FALSE.Syntax:SELECT IF(200<500, "YES", "NO");
Output:
SELECT IF(200<500, "YES", "NO");
Output:
LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement.Syntax:SELECT LAST_INSERT_ID();
Output:
SELECT LAST_INSERT_ID();
Output:
NULLIF(): It returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.Syntax:SELECT NULLIF(25.11, 25);
Output:Syntax:SELECT NULLIF(115, 115);
Output:
Syntax:SELECT NULLIF(25.11, 25);
Output:
SELECT NULLIF(25.11, 25);
Output:
Syntax:SELECT NULLIF(115, 115);
Output:
SELECT NULLIF(115, 115);
Output:
SESSION_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SESSION_USER();Output:
SELECT SESSION_USER();
Output:
SYSTEM_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SYSTEM_USER();
Output:
SELECT SYSTEM_USER();
Output:
USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT USER();
Output:
SELECT USER();
Output:
VERSION(): It returns the version of the MySQL database.Syntax:SELECT VERSION();
Output:
SELECT VERSION();
Output:
mariodod
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter | [
{
"code": null,
"e": 23899,
"s": 23871,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 23960,
"s": 23899,
"text": "Following are some of the advanced functions defined in SQL:"
},
{
"code": null,
"e": 25623,
"s": 23960,
"text": "BIN(): It converts a decimal number to a binary number.Syntax:SELECT BIN(18);\nOutput:BINARY(): It converts a value to a binary stringSyntax:SELECT BINARY \"GeeksforGeeks\";Output:COALESCE(): It returns the first non-null expression in a list.Syntax:SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');\nOutput:CONNECTION_ID(): It returns the unique connection ID for the current connection.Syntax:SELECT CONNECTION_ID();\nOutput:CURRENT_USER(): It returns the user name and host name for the MySQL account used by the server to authenticate the current client.Syntax:SELECT CURRENT_USER();\nOutput:DATABASE(): It returns the name of the default database.Syntax:SELECT DATABASE();\nOutput:IF(): It returns one value if a condition is TRUE, or another value if a condition is FALSE.Syntax:SELECT IF(200<500, \"YES\", \"NO\");\nOutput:LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement.Syntax:SELECT LAST_INSERT_ID();\nOutput:NULLIF(): It returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.Syntax:SELECT NULLIF(25.11, 25);\nOutput:Syntax:SELECT NULLIF(115, 115);\nOutput:SESSION_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SESSION_USER();Output:SYSTEM_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SYSTEM_USER();\nOutput:USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT USER();\nOutput:VERSION(): It returns the version of the MySQL database.Syntax:SELECT VERSION();\nOutput:"
},
{
"code": null,
"e": 25709,
"s": 25623,
"text": "BIN(): It converts a decimal number to a binary number.Syntax:SELECT BIN(18);\nOutput:"
},
{
"code": null,
"e": 25726,
"s": 25709,
"text": "SELECT BIN(18);\n"
},
{
"code": null,
"e": 25734,
"s": 25726,
"text": "Output:"
},
{
"code": null,
"e": 25827,
"s": 25734,
"text": "BINARY(): It converts a value to a binary stringSyntax:SELECT BINARY \"GeeksforGeeks\";Output:"
},
{
"code": null,
"e": 25858,
"s": 25827,
"text": "SELECT BINARY \"GeeksforGeeks\";"
},
{
"code": null,
"e": 25866,
"s": 25858,
"text": "Output:"
},
{
"code": null,
"e": 26001,
"s": 25866,
"text": "COALESCE(): It returns the first non-null expression in a list.Syntax:SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');\nOutput:"
},
{
"code": null,
"e": 26059,
"s": 26001,
"text": "SELECT COALESCE(NULL,NULL,'GeeksforGeeks',NULL,'Geeks');\n"
},
{
"code": null,
"e": 26067,
"s": 26059,
"text": "Output:"
},
{
"code": null,
"e": 26186,
"s": 26067,
"text": "CONNECTION_ID(): It returns the unique connection ID for the current connection.Syntax:SELECT CONNECTION_ID();\nOutput:"
},
{
"code": null,
"e": 26211,
"s": 26186,
"text": "SELECT CONNECTION_ID();\n"
},
{
"code": null,
"e": 26219,
"s": 26211,
"text": "Output:"
},
{
"code": null,
"e": 26388,
"s": 26219,
"text": "CURRENT_USER(): It returns the user name and host name for the MySQL account used by the server to authenticate the current client.Syntax:SELECT CURRENT_USER();\nOutput:"
},
{
"code": null,
"e": 26412,
"s": 26388,
"text": "SELECT CURRENT_USER();\n"
},
{
"code": null,
"e": 26420,
"s": 26412,
"text": "Output:"
},
{
"code": null,
"e": 26510,
"s": 26420,
"text": "DATABASE(): It returns the name of the default database.Syntax:SELECT DATABASE();\nOutput:"
},
{
"code": null,
"e": 26530,
"s": 26510,
"text": "SELECT DATABASE();\n"
},
{
"code": null,
"e": 26538,
"s": 26530,
"text": "Output:"
},
{
"code": null,
"e": 26678,
"s": 26538,
"text": "IF(): It returns one value if a condition is TRUE, or another value if a condition is FALSE.Syntax:SELECT IF(200<500, \"YES\", \"NO\");\nOutput:"
},
{
"code": null,
"e": 26712,
"s": 26678,
"text": "SELECT IF(200<500, \"YES\", \"NO\");\n"
},
{
"code": null,
"e": 26720,
"s": 26712,
"text": "Output:"
},
{
"code": null,
"e": 26879,
"s": 26720,
"text": "LAST_INSERT_ID(): It returns the first AUTO_INCREMENT value that was set by the most recent INSERT or UPDATE statement.Syntax:SELECT LAST_INSERT_ID();\nOutput:"
},
{
"code": null,
"e": 26905,
"s": 26879,
"text": "SELECT LAST_INSERT_ID();\n"
},
{
"code": null,
"e": 26913,
"s": 26905,
"text": "Output:"
},
{
"code": null,
"e": 27167,
"s": 26913,
"text": "NULLIF(): It returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.Syntax:SELECT NULLIF(25.11, 25);\nOutput:Syntax:SELECT NULLIF(115, 115);\nOutput:"
},
{
"code": null,
"e": 27208,
"s": 27167,
"text": "Syntax:SELECT NULLIF(25.11, 25);\nOutput:"
},
{
"code": null,
"e": 27235,
"s": 27208,
"text": "SELECT NULLIF(25.11, 25);\n"
},
{
"code": null,
"e": 27243,
"s": 27235,
"text": "Output:"
},
{
"code": null,
"e": 27283,
"s": 27243,
"text": "Syntax:SELECT NULLIF(115, 115);\nOutput:"
},
{
"code": null,
"e": 27309,
"s": 27283,
"text": "SELECT NULLIF(115, 115);\n"
},
{
"code": null,
"e": 27317,
"s": 27309,
"text": "Output:"
},
{
"code": null,
"e": 27436,
"s": 27317,
"text": "SESSION_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SESSION_USER();Output:"
},
{
"code": null,
"e": 27459,
"s": 27436,
"text": "SELECT SESSION_USER();"
},
{
"code": null,
"e": 27467,
"s": 27459,
"text": "Output:"
},
{
"code": null,
"e": 27585,
"s": 27467,
"text": "SYSTEM_USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT SYSTEM_USER();\nOutput:"
},
{
"code": null,
"e": 27608,
"s": 27585,
"text": "SELECT SYSTEM_USER();\n"
},
{
"code": null,
"e": 27616,
"s": 27608,
"text": "Output:"
},
{
"code": null,
"e": 27720,
"s": 27616,
"text": "USER(): It returns the user name and host name for the current MySQL user.Syntax:SELECT USER();\nOutput:"
},
{
"code": null,
"e": 27736,
"s": 27720,
"text": "SELECT USER();\n"
},
{
"code": null,
"e": 27744,
"s": 27736,
"text": "Output:"
},
{
"code": null,
"e": 27833,
"s": 27744,
"text": "VERSION(): It returns the version of the MySQL database.Syntax:SELECT VERSION();\nOutput:"
},
{
"code": null,
"e": 27852,
"s": 27833,
"text": "SELECT VERSION();\n"
},
{
"code": null,
"e": 27860,
"s": 27852,
"text": "Output:"
},
{
"code": null,
"e": 27869,
"s": 27860,
"text": "mariodod"
},
{
"code": null,
"e": 27883,
"s": 27869,
"text": "SQL-Functions"
},
{
"code": null,
"e": 27887,
"s": 27883,
"text": "SQL"
},
{
"code": null,
"e": 27891,
"s": 27887,
"text": "SQL"
},
{
"code": null,
"e": 27989,
"s": 27891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27998,
"s": 27989,
"text": "Comments"
},
{
"code": null,
"e": 28011,
"s": 27998,
"text": "Old Comments"
},
{
"code": null,
"e": 28042,
"s": 28011,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 28054,
"s": 28042,
"text": "SQL | Views"
},
{
"code": null,
"e": 28065,
"s": 28054,
"text": "CTE in SQL"
},
{
"code": null,
"e": 28110,
"s": 28065,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 28176,
"s": 28110,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28209,
"s": 28176,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 28224,
"s": 28209,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 28263,
"s": 28224,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 28295,
"s": 28263,
"text": "What is Temporary Table in SQL?"
}
] |
Find Quotient and Remainder of two integer without using division operators - GeeksforGeeks | 07 Apr, 2021
Given two positive integers dividend and divisor, our task is to find quotient and remainder. The use of division or mod operator is not allowed.
Examples:
Input : dividend = 10, divisor = 3 Output : 3, 1 Explanation: The quotient when 10 is divided by 3 is 3 and the remainder is 1.
Input : dividend = 11, divisor = 5 Output : 2, 1 Explanation: The quotient when 11 is divided by 5 is 2 and the remainder is 1.
Approach: To solve the problem mentioned above we will use the Binary Search technique. We can implement the search method in range 1 to N where N is the dividend. Here we will use multiplication to decide the range. As soon as we break out of the while loop of binary search we get our quotient and the remainder can be found using the multiplication and subtraction operator. Handle the special case, when the dividend is less than or equal to the divisor, without the use of binary search.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search #include <bits/stdc++.h>using namespace std; // Function to the quotient and remainderpair<int, int> find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} pair<int, int> divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codeint main(int argc, char* argv[]){ int dividend = 10, divisor = 3; pair<int, int> ans; ans = divide(dividend, divisor); cout << ans.first << ", "; cout << ans.second << endl; return 0;}
// JAVA implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search class GFG{ // Function to the quotient and remainderstatic int[] find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return new int[] { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return new int[] { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} static int[] divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codepublic static void main(String[] args){ int dividend = 10, divisor = 3; int []ans = divide(dividend, divisor); System.out.print(ans[0]+ ", "); System.out.print(ans[1] +"\n"); }} // This code contributed by sapnasingh4991
# Python3 implementation to Find Quotient# and Remainder of two integer without# using / and % operator using Binary search # Function to the quotient and remainderdef find(dividend, divisor, start, end) : # Check if start is greater than the end if (start > end) : return ( 0, dividend ); # Calculate mid mid = start + (end - start) // 2; n = dividend - divisor * mid; # Check if n is greater than divisor # then increment the mid by 1 if (n > divisor) : start = mid + 1; # Check if n is less than 0 # then decrement the mid by 1 elif (n < 0) : end = mid - 1; else : # Check if n equals to divisor if (n == divisor) : mid += 1; n = 0; # Return the final answer return ( mid, n ); # Recursive calls return find(dividend, divisor, start, end); def divide(dividend, divisor) : return find(dividend, divisor, 1, dividend); # Driver codeif __name__ == "__main__" : dividend = 10; divisor = 3; ans = divide(dividend, divisor); print(ans[0],", ",ans[1]) # This code is contributed by Yash_R
// C# implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search using System; public class GFG{ // Function to the quotient and remainderstatic int[] find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return new int[] { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the readonly answer return new int[] { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} static int[] divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codepublic static void Main(String[] args){ int dividend = 10, divisor = 3; int []ans = divide(dividend, divisor); Console.Write(ans[0]+ ", "); Console.Write(ans[1] +"\n"); }}// This code contributed by Princi Singh
<script> // Javascript implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search // Function to the quotient and remainderfunction find(dividend, divisor, start, end){ // Check if start is greater than the end if (start > end) return [0, dividend]; // Calculate mid var mid = start + parseInt((end - start) / 2); var n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return [ mid, n]; } // Recursive calls return find(dividend, divisor, start, end);} function divide(dividend, divisor){ return find(dividend, divisor, 1, dividend);} // Driver codevar dividend = 10, divisor = 3;var ans = divide(dividend, divisor); document.write(ans[0] + ", ");document.write(ans[1] + "\n"); // This code is contributed by gauravrajput1 </script>
3, 1
Time Complexity: O(logN)Space Complexity: O(n)Similar article: Divide two integers without using multiplication, division and mod operator
Yash_R
sapnasingh4991
princi singh
GauravRajput1
Mathematical
Searching
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Program to find GCD or HCF of two numbers
Program for Decimal to Binary Conversion
Sieve of Eratosthenes
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times
K'th Smallest/Largest Element in Unsorted Array | Set 1 | [
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 24543,
"s": 24397,
"text": "Given two positive integers dividend and divisor, our task is to find quotient and remainder. The use of division or mod operator is not allowed."
},
{
"code": null,
"e": 24553,
"s": 24543,
"text": "Examples:"
},
{
"code": null,
"e": 24681,
"s": 24553,
"text": "Input : dividend = 10, divisor = 3 Output : 3, 1 Explanation: The quotient when 10 is divided by 3 is 3 and the remainder is 1."
},
{
"code": null,
"e": 24811,
"s": 24681,
"text": "Input : dividend = 11, divisor = 5 Output : 2, 1 Explanation: The quotient when 11 is divided by 5 is 2 and the remainder is 1. "
},
{
"code": null,
"e": 25304,
"s": 24811,
"text": "Approach: To solve the problem mentioned above we will use the Binary Search technique. We can implement the search method in range 1 to N where N is the dividend. Here we will use multiplication to decide the range. As soon as we break out of the while loop of binary search we get our quotient and the remainder can be found using the multiplication and subtraction operator. Handle the special case, when the dividend is less than or equal to the divisor, without the use of binary search."
},
{
"code": null,
"e": 25357,
"s": 25304,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25361,
"s": 25357,
"text": "C++"
},
{
"code": null,
"e": 25366,
"s": 25361,
"text": "Java"
},
{
"code": null,
"e": 25374,
"s": 25366,
"text": "Python3"
},
{
"code": null,
"e": 25377,
"s": 25374,
"text": "C#"
},
{
"code": null,
"e": 25388,
"s": 25377,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search #include <bits/stdc++.h>using namespace std; // Function to the quotient and remainderpair<int, int> find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} pair<int, int> divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codeint main(int argc, char* argv[]){ int dividend = 10, divisor = 3; pair<int, int> ans; ans = divide(dividend, divisor); cout << ans.first << \", \"; cout << ans.second << endl; return 0;}",
"e": 26687,
"s": 25388,
"text": null
},
{
"code": "// JAVA implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search class GFG{ // Function to the quotient and remainderstatic int[] find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return new int[] { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return new int[] { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} static int[] divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codepublic static void main(String[] args){ int dividend = 10, divisor = 3; int []ans = divide(dividend, divisor); System.out.print(ans[0]+ \", \"); System.out.print(ans[1] +\"\\n\"); }} // This code contributed by sapnasingh4991",
"e": 28013,
"s": 26687,
"text": null
},
{
"code": "# Python3 implementation to Find Quotient# and Remainder of two integer without# using / and % operator using Binary search # Function to the quotient and remainderdef find(dividend, divisor, start, end) : # Check if start is greater than the end if (start > end) : return ( 0, dividend ); # Calculate mid mid = start + (end - start) // 2; n = dividend - divisor * mid; # Check if n is greater than divisor # then increment the mid by 1 if (n > divisor) : start = mid + 1; # Check if n is less than 0 # then decrement the mid by 1 elif (n < 0) : end = mid - 1; else : # Check if n equals to divisor if (n == divisor) : mid += 1; n = 0; # Return the final answer return ( mid, n ); # Recursive calls return find(dividend, divisor, start, end); def divide(dividend, divisor) : return find(dividend, divisor, 1, dividend); # Driver codeif __name__ == \"__main__\" : dividend = 10; divisor = 3; ans = divide(dividend, divisor); print(ans[0],\", \",ans[1]) # This code is contributed by Yash_R",
"e": 29141,
"s": 28013,
"text": null
},
{
"code": "// C# implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search using System; public class GFG{ // Function to the quotient and remainderstatic int[] find(int dividend, int divisor, int start, int end){ // Check if start is greater than the end if (start > end) return new int[] { 0, dividend }; // Calculate mid int mid = start + (end - start) / 2; int n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the readonly answer return new int[] { mid, n }; } // Recursive calls return find(dividend, divisor, start, end);} static int[] divide(int dividend, int divisor){ return find(dividend, divisor, 1, dividend);} // Driver codepublic static void Main(String[] args){ int dividend = 10, divisor = 3; int []ans = divide(dividend, divisor); Console.Write(ans[0]+ \", \"); Console.Write(ans[1] +\"\\n\"); }}// This code contributed by Princi Singh",
"e": 30495,
"s": 29141,
"text": null
},
{
"code": "<script> // Javascript implementation to Find Quotient// and Remainder of two integer without// using / and % operator using Binary search // Function to the quotient and remainderfunction find(dividend, divisor, start, end){ // Check if start is greater than the end if (start > end) return [0, dividend]; // Calculate mid var mid = start + parseInt((end - start) / 2); var n = dividend - divisor * mid; // Check if n is greater than divisor // then increment the mid by 1 if (n > divisor) start = mid + 1; // Check if n is less than 0 // then decrement the mid by 1 else if (n < 0) end = mid - 1; else { // Check if n equals to divisor if (n == divisor) { ++mid; n = 0; } // Return the final answer return [ mid, n]; } // Recursive calls return find(dividend, divisor, start, end);} function divide(dividend, divisor){ return find(dividend, divisor, 1, dividend);} // Driver codevar dividend = 10, divisor = 3;var ans = divide(dividend, divisor); document.write(ans[0] + \", \");document.write(ans[1] + \"\\n\"); // This code is contributed by gauravrajput1 </script>",
"e": 31717,
"s": 30495,
"text": null
},
{
"code": null,
"e": 31722,
"s": 31717,
"text": "3, 1"
},
{
"code": null,
"e": 31864,
"s": 31724,
"text": "Time Complexity: O(logN)Space Complexity: O(n)Similar article: Divide two integers without using multiplication, division and mod operator "
},
{
"code": null,
"e": 31871,
"s": 31864,
"text": "Yash_R"
},
{
"code": null,
"e": 31886,
"s": 31871,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 31899,
"s": 31886,
"text": "princi singh"
},
{
"code": null,
"e": 31913,
"s": 31899,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31926,
"s": 31913,
"text": "Mathematical"
},
{
"code": null,
"e": 31936,
"s": 31926,
"text": "Searching"
},
{
"code": null,
"e": 31946,
"s": 31936,
"text": "Searching"
},
{
"code": null,
"e": 31959,
"s": 31946,
"text": "Mathematical"
},
{
"code": null,
"e": 32057,
"s": 31959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32066,
"s": 32057,
"text": "Comments"
},
{
"code": null,
"e": 32079,
"s": 32066,
"text": "Old Comments"
},
{
"code": null,
"e": 32103,
"s": 32079,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32117,
"s": 32103,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32159,
"s": 32117,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32200,
"s": 32159,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 32222,
"s": 32200,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 32236,
"s": 32222,
"text": "Binary Search"
},
{
"code": null,
"e": 32250,
"s": 32236,
"text": "Linear Search"
},
{
"code": null,
"e": 32318,
"s": 32250,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32409,
"s": 32318,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
}
] |
Check if any anagram of a string is palindrome or not in Python | Suppose we have a string s. We have to check whether an anagram of that string is forming a palindrome or not.
So, if the input is like s = "aarcrec", then the output will be True one anagram of this string is "racecar" which is palindrome.
To solve this, we will follow these steps −
freq := a map to store all characters and their frequencies
odd_count := 0
for each f in list of all values of freq, doif f is odd, thenodd_count := odd_count + 1
if f is odd, thenodd_count := odd_count + 1
odd_count := odd_count + 1
if odd_count > 1, thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
Live Demo
from collections import defaultdict
def solve(s):
freq = defaultdict(int)
for char in s:
freq[char] += 1
odd_count = 0
for f in freq.values():
if f % 2 == 1:
odd_count += 1
if odd_count > 1:
return False
return True
s = "aarcrec"
print(solve(s))
"aarcrec"
True | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "Suppose we have a string s. We have to check whether an anagram of that string is forming a palindrome or not."
},
{
"code": null,
"e": 1303,
"s": 1173,
"text": "So, if the input is like s = \"aarcrec\", then the output will be True one anagram of this string is \"racecar\" which is palindrome."
},
{
"code": null,
"e": 1347,
"s": 1303,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1407,
"s": 1347,
"text": "freq := a map to store all characters and their frequencies"
},
{
"code": null,
"e": 1422,
"s": 1407,
"text": "odd_count := 0"
},
{
"code": null,
"e": 1510,
"s": 1422,
"text": "for each f in list of all values of freq, doif f is odd, thenodd_count := odd_count + 1"
},
{
"code": null,
"e": 1554,
"s": 1510,
"text": "if f is odd, thenodd_count := odd_count + 1"
},
{
"code": null,
"e": 1581,
"s": 1554,
"text": "odd_count := odd_count + 1"
},
{
"code": null,
"e": 1616,
"s": 1581,
"text": "if odd_count > 1, thenreturn False"
},
{
"code": null,
"e": 1629,
"s": 1616,
"text": "return False"
},
{
"code": null,
"e": 1641,
"s": 1629,
"text": "return True"
},
{
"code": null,
"e": 1711,
"s": 1641,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1722,
"s": 1711,
"text": " Live Demo"
},
{
"code": null,
"e": 2013,
"s": 1722,
"text": "from collections import defaultdict\ndef solve(s):\n freq = defaultdict(int)\n for char in s:\n freq[char] += 1\n odd_count = 0\n for f in freq.values():\n if f % 2 == 1:\n odd_count += 1\n if odd_count > 1:\n return False\n return True\ns = \"aarcrec\"\nprint(solve(s))"
},
{
"code": null,
"e": 2023,
"s": 2013,
"text": "\"aarcrec\""
},
{
"code": null,
"e": 2028,
"s": 2023,
"text": "True"
}
] |
Connect to MySQL using PyMySQL in Python - GeeksforGeeks | 05 Sep, 2020
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database.
This package contains a pure-Python MySQL client library, based on PEP 249.
Requirements :
MySQL Server – one of the following :
MySQL >= 5.5
MariaDB >= 5.5
Installation :
This module does not come built-in with Python. You have to install it externally. To install this type the below command in the terminal.
pip install PyMySQL
The proper way to get an instance of this class is to call connect() method. This method establishes a connection to the MySQL database and accepts several arguments:
Parameters :
host – Host where the database server is located
user – Username to log in as
password – Password to use.
database – Database to use, None to not use a particular one.
port – MySQL port to use, default is usually OK. (default: 3306)
Example 1: Let’s connect to the MySQL server.
Python3
import pymysql def mysqlconnect(): # To connect MySQL database conn = pymysql.connect( host='localhost', user='root', password = "pass", db='College', ) cur = conn.cursor() cur.execute("select @@version") output = cur.fetchall() print(output) # To close the connection conn.close() # Driver Codeif __name__ == "__main__" : mysqlconnect()
Output :
(('5.7.30-0ubuntu0.18.04.1',),)
Example 2: Let’s try to access a table from the database
Table used:
Python3
import pymysql def mysqlconnect(): # To connect MySQL database conn = pymysql.connect( host='localhost', user='root', password = "pass", db='College', ) cur = conn.cursor() # Select query cur.execute("select * from STUDENT") output = cur.fetchall() for i in output: print(i) # To close the connection conn.close() # Driver Codeif __name__ == "__main__" : mysqlconnect()
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24476,
"s": 24292,
"text": "In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database."
},
{
"code": null,
"e": 24552,
"s": 24476,
"text": "This package contains a pure-Python MySQL client library, based on PEP 249."
},
{
"code": null,
"e": 24567,
"s": 24552,
"text": "Requirements :"
},
{
"code": null,
"e": 24605,
"s": 24567,
"text": "MySQL Server – one of the following :"
},
{
"code": null,
"e": 24618,
"s": 24605,
"text": "MySQL >= 5.5"
},
{
"code": null,
"e": 24633,
"s": 24618,
"text": "MariaDB >= 5.5"
},
{
"code": null,
"e": 24648,
"s": 24633,
"text": "Installation :"
},
{
"code": null,
"e": 24787,
"s": 24648,
"text": "This module does not come built-in with Python. You have to install it externally. To install this type the below command in the terminal."
},
{
"code": null,
"e": 24808,
"s": 24787,
"text": "pip install PyMySQL\n"
},
{
"code": null,
"e": 24975,
"s": 24808,
"text": "The proper way to get an instance of this class is to call connect() method. This method establishes a connection to the MySQL database and accepts several arguments:"
},
{
"code": null,
"e": 24988,
"s": 24975,
"text": "Parameters :"
},
{
"code": null,
"e": 25037,
"s": 24988,
"text": "host – Host where the database server is located"
},
{
"code": null,
"e": 25066,
"s": 25037,
"text": "user – Username to log in as"
},
{
"code": null,
"e": 25094,
"s": 25066,
"text": "password – Password to use."
},
{
"code": null,
"e": 25156,
"s": 25094,
"text": "database – Database to use, None to not use a particular one."
},
{
"code": null,
"e": 25221,
"s": 25156,
"text": "port – MySQL port to use, default is usually OK. (default: 3306)"
},
{
"code": null,
"e": 25268,
"s": 25221,
"text": "Example 1: Let’s connect to the MySQL server. "
},
{
"code": null,
"e": 25276,
"s": 25268,
"text": "Python3"
},
{
"code": "import pymysql def mysqlconnect(): # To connect MySQL database conn = pymysql.connect( host='localhost', user='root', password = \"pass\", db='College', ) cur = conn.cursor() cur.execute(\"select @@version\") output = cur.fetchall() print(output) # To close the connection conn.close() # Driver Codeif __name__ == \"__main__\" : mysqlconnect()",
"e": 25691,
"s": 25276,
"text": null
},
{
"code": null,
"e": 25700,
"s": 25691,
"text": "Output :"
},
{
"code": null,
"e": 25733,
"s": 25700,
"text": "(('5.7.30-0ubuntu0.18.04.1',),)\n"
},
{
"code": null,
"e": 25790,
"s": 25733,
"text": "Example 2: Let’s try to access a table from the database"
},
{
"code": null,
"e": 25802,
"s": 25790,
"text": "Table used:"
},
{
"code": null,
"e": 25810,
"s": 25802,
"text": "Python3"
},
{
"code": "import pymysql def mysqlconnect(): # To connect MySQL database conn = pymysql.connect( host='localhost', user='root', password = \"pass\", db='College', ) cur = conn.cursor() # Select query cur.execute(\"select * from STUDENT\") output = cur.fetchall() for i in output: print(i) # To close the connection conn.close() # Driver Codeif __name__ == \"__main__\" : mysqlconnect()",
"e": 26279,
"s": 25810,
"text": null
},
{
"code": null,
"e": 26287,
"s": 26279,
"text": "Output:"
},
{
"code": null,
"e": 26300,
"s": 26287,
"text": "Python-mySQL"
},
{
"code": null,
"e": 26307,
"s": 26300,
"text": "Python"
},
{
"code": null,
"e": 26405,
"s": 26307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26437,
"s": 26405,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26479,
"s": 26437,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26535,
"s": 26479,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26577,
"s": 26535,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26632,
"s": 26577,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26663,
"s": 26632,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26685,
"s": 26663,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26724,
"s": 26685,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26753,
"s": 26724,
"text": "Create a directory in Python"
}
] |
Machine Learning Kaggle Competition Part One: Getting Started | by Will Koehrsen | Towards Data Science | In the field of data science, there are almost too many resources available: from Datacamp to Udacity to KDnuggets, there are thousands of places online to learn about data science. However, if you are someone who likes to jump in and learn by doing, Kaggle might be the single best location for expanding your skills through hands-on data science projects.
While it originally was known as a place for machine learning competitions, Kaggle — which bills itself as “Your Home for Data Science” — now offers an array of data science resources. Although this series of articles will focus on a competition, it’s worth pointing out the main aspects of Kaggle:
Datasets: Tens of thousands of datasets of all different types and sizes that you can download and use for free. This is a great place to go if you are looking for interesting data to explore or to test your modeling skills.
Machine Learning Competitions: once the heart of Kaggle, these tests of modeling skill are a great way to learn cutting edge machine learning techniques and hone your abilities on interesting problems using real data.
Learn: A series of data science learning tracks covering SQL to Deep Learning taught in Jupyter Notebooks.
Discussion: A place to ask questions and get advice from the thousands of data scientists in the Kaggle community.
Kernels: Online programming environments running on Kaggle’s servers where you can write Python/R scripts, or Jupyter Notebooks. These kernels are entirely free to run (you can even add a GPU) and are a great resource because you don’t have to worry about setting up a data science environment on your own computer. The kernels can be used to analyze any dataset, compete in machine learning competitions, or complete the learning tracks. You can copy and build on existing kernels from other users and share your kernels with the community for feedback.
Overall, Kaggle is a great place to learn, whether that’s through the more traditional learning tracks or by competing in competitions. When I want to find out about the latest machine learning method, I could go read a book, or, I could go on Kaggle, find a competition, and see how people use it in practice. Personally, I find this much more enjoyable and a more effective teaching method. Moreover, the community is extremely supportive and always willing to answer questions or provide feedback on a project.
In this article, we’ll focus on getting started with a Kaggle machine learning competition: the Home Credit Default Risk problem. This is a fairly straightforward competition with a reasonable sized dataset (which can’t be said for all of the competitions) which means we can compete entirely using Kaggle’s kernels. This significantly lowers the barrier to entry because you don’t have to worry about any software on your computer and you don’t even have to download the data! As long as you have a Kaggle account and an Internet connection, you can connect to a kernel and run the code.
I plan to do the entire competition on Kaggle and the kernel (a Python Jupyter Notebook) for this post is available here. To get the most from this article, copy the kernel by creating a Kaggle account, then hitting the blue Fork Notebook button. This will open up the notebook for editing and running in the kernel environment.
The Home Credit Default Risk competition is a standard supervised machine learning task where the goal is to use historical loan application data to predict whether or not an applicant will repay a loan. During training, we provide our model with the features — the variables describing a loan application — and the label — a binary 0 if the loan was repaid and a 1 if the loan was not repaid — and the model learns a mapping from the features to the label. Then, during testing, we feed the model the features for a new batch of applications and ask it to predict the label.
All the data for this competition is structured meaning it exists in neat rows and columns — think a spreadsheet. This means we won’t need to use any convolutional neural networks (which excel at processing image data ) and it will give us great practice on a real-world dataset.
Home Credit, the host of the competition, is a finance provider that focuses on serving the unbanked population. Predicting whether or not an application will repay a loan is a vital business need, and Home Credit has developed this competition in the hopes that the Kaggle community can develop an effective algorithm for this task. This competition follows the general idea of most Kaggle competitions: a company has data and a problem to solve, and rather than (or in addition to) hiring internal data scientists to build a model, they put up a modest prize to entice the entire world to contribute solutions. A community of thousands of skilled data scientists (Kagglers) then work on the problem for basically no charge to come up with the best solution. As far as cost effective business plans go, this seems like a brilliant idea!
When you go to the competition homepage, you’ll see this:
Here’s a quick run through of the tabs
Overview: a brief description of the problem, the evaluation metric, the prizes, and the timeline
Data: all of the data needed for the competition as external data is not allowed. You can download all of the data, but we won’t need to do that because we will be using a Kaggle Kernel which can connect to the data.
Kernels: Previous work done by you and other competitors. This —in my opinion — is the most valuable resource for a competition. You can read through other scripts and notebooks and then copy the code (called “Forking”) to edit and run.
Discussion: another helpful resource where you can find conversations both from the competition hosts and from other competitors. A great place to ask questions and learn from the answers of others.
Leaderboard: who’s on top and where you stand
Rules: not very interesting, but good to understand
Team: manage the members of your team if you decide to form a team
My Submissions: view your previous submissions and select the final ones to be used for the competition
Although they are called competitions, Kaggle machine learning events should really be termed “collaborative projects” because the main goal is not necessarily to win but to practice and learn from fellow data scientists. Once you realize that it’s not so much about beating others but about expanding your own skills, you will get a lot more out of the competitions. When you sign up for Kaggle, you not only get all the resources , you also get to be part of a community of data scientists with thousands of years of collective experience.
Take advantage of all that experience by trying to be an active part of the community! That means anything from sharing a kernel to asking a question in a discussion forum. While it can be intimidating to make your work public, we learn best by making mistakes, receiving feedback, and improving so we don’t make the same mistake again. Everyone starts out a beginner, and the community is very supportive of data scientists of all skill levels.
In that mindset, I want to emphasize that discussion with others and building on others’ code is not only acceptable, but encouraged! In school, working with others is called cheating and gets you a zero, but in the real world, it’s called collaboration and an extremely important skill.
A great method for throwing yourself into a competition is to find a kernel someone has shared with a good leaderboard score, fork the kernel, edit it to try and improve the score, and then run it to see the results. Then, make the kernel public so others can use your work. Data scientists stand not on the shoulders of giants, but on the backs of thousands of individuals who have made their work public for the benefit of all. (Sorry for getting philosophical, but this is why I love data science!)
Once you have a basic understanding of how Kaggle works and the philosophy of how to get the most out of a competition, it’s time to get started. Here, I’ll briefly outline a Python Jupyter Notebook I put together in a kernel for the Home Credit Default Risk problem, but to get the full benefit, you’ll want to fork the notebook on Kaggle and run it yourself (you don’t have to download or set-up anything so I’d highly encourage checking it out).
When you open the notebook in a kernel, you’ll see this environment:
Think of this as a standard Jupyter Notebook with slightly different aesthetics. You can write Python code and text (using Markdown syntax) just like in Jupyter and run the code completely in the cloud on Kaggle’s servers. However, Kaggle kernels have some unique features not available in Jupyter Notebook. Hit the leftward facing arrow in the upper right to expand the kernel control panel which brings up three tabs (if the notebook is not in fullscreen, then these three tabs may already be visible next to the code).
In the data tab, we can view the datasets to which our Kernel is connected. In this case, we have the entire competition data, but we can also connect to any other dataset on Kaggle or upload our own data and access it in the kernel. Data files are available in the ../input/ directory from within the code:
import os# List data files that are connected to the kernelos.listdir('../input/')
The Settings tab lets us control different technical aspects of the kernel. Here we can add a GPU to our session, change the visibility, and install any Python package which is not already in the environment.
Finally, the Versions tab lets us see any previous committed runs of the code. We can view changes to the code, look at log files of a run, see the notebook generated by a run, and download the files that are output from a run.
To run the entire notebook and record a new Version, hit the blue Commit & Run button in the upper right of the kernel. This executes all the code, shows us the completed notebook (or any errors if there are mistakes), and saves any files that are created during the run. When we commit the notebook, we can then access any predictions our models made and submit them for scoring.
The first notebook is meant to get you familiar with the problem. We start off much the same way as any data science problem: understanding the data and the task. For this problem, there is 1 main training data file (with the labels included), 1 main testing data file, and 6 additional data files. In this first notebook, we use only the main data, which will get us a decent score, but later work will have to incorporate all the data in order to be competitive.
To understand the data, it’s best to take a couple minutes away from the keyboard and read through the problem documentation, such as the column descriptions of each data file. Because there are multiple files, we need to know how they are all linked together, although for this first notebook we only use the main file to keep things simple. Reading through other kernels can also help us get familiar with the data and which variables are important.
Once we understand the data and the problem, we can start structuring it for a machine learning task This means dealing with categorical variables (through one-hot encoding), filling in the missing values (imputation), and scaling the variables to a range. We can do exploratory data analysis, such as finding correlations with the label, and graphing these relationships.
We can use these relationships later on for modeling decisions, such as including which variables to use. (See the notebook for implementation).
Of course, no exploratory data analysis is complete without my favorite plot, the Pairs Plot.
After thoroughly exploring the data and making sure it’s acceptable for machine learning, we move on to creating baseline models. However, before we quite get to the modeling stage, it’s critical we understand the performance metric for the competition. In a Kaggle competition, it all comes down to a single number, the metric on the test data.
While it might make intuitive sense to use accuracy for a binary classification task, that is a poor choice because we are dealing with an imbalanced class problem. Instead of accuracy, submissions are judged in terms of ROC AUC or Receiver Operating Characteristic curve Area Under the Curve. I’ll let you do the research on this one, or read the explanation in the notebook. Just know that higher is better, with a random model scoring 0.5 and a perfect model scoring 1.0. To calculate a ROC AUC, we need to make predictions in terms of probabilities rather than a binary 0 or 1. The ROC then shows the True Positive Rate versus the False Positive Rate as a function of the threshold according to which we classify an instance as positive.
Usually we like to make a naive baseline prediction, but in this case, we already know that random guessing on the task would get an ROC AUC of 0.5. Therefore, for our baseline model, we will use a slightly more sophisticated method, Logistic Regression. This is a popular simple algorithm for binary classification problems and it will set a low bar for future models to surpass.
After implementing the logistic regression, we can save the results to a csv file for submission. When the notebook is committed, any results we write will show up in the Output sub-tab on the Versions tab:
From this tab, we can download the submissions to our computer and then upload them to the competition. In this notebook, we make four different models with scores as follows:
Logistic Regression: 0.671
Random Forest: 0.678
Random Forest with Constructed Features: 0.678
Light Gradient Boosting Machine: 0.729
These scores don’t get us anywhere close to the top of the leaderboard, but they leave room for plenty of future improvement! We also get an idea of the performance we can expect using only a single source of data.
(Not surprisingly, the extraordinary Gradient Boosting Machine (using the LightGBM library) performs the best. This model wins nearly every structured Kaggle competition (where the data is in table format) and we will likely need to use some form of this model if we want to seriously compete!)
This article and introductory kernel demonstrated a basic start to a Kaggle competition. It’s not meant to win, but rather to show you the basics of how to approach a machine learning competition and also a few models to get you off the ground (although the LightGBM model is like jumping off the deep end).
Furthermore, I laid out my philosophy for machine learning competitions, which is to learn as much as possible by taking part in discussions, building on other’s code, and sharing your own work. It’s enjoyable to best your past scores, but I view doing well not as the main focus but as a positive side effect of learning new data science techniques. While these are known as competitions, they are really collaborative projects where everyone is welcome to participate and hone their abilities.
There remains a ton of work to be done, but thankfully we don’t have to do it alone. In later articles and notebooks we’ll see how to build on the work of others to make even better models. I hope this article (and the notebook kernel) has given you the confidence to start competing on Kaggle or taking on any data science project.
As always, I welcome constructive criticism and discussion and can be reached on Twitter @koehrsen_will. | [
{
"code": null,
"e": 405,
"s": 47,
"text": "In the field of data science, there are almost too many resources available: from Datacamp to Udacity to KDnuggets, there are thousands of places online to learn about data science. However, if you are someone who likes to jump in and learn by doing, Kaggle might be the single best location for expanding your skills through hands-on data science projects."
},
{
"code": null,
"e": 704,
"s": 405,
"text": "While it originally was known as a place for machine learning competitions, Kaggle — which bills itself as “Your Home for Data Science” — now offers an array of data science resources. Although this series of articles will focus on a competition, it’s worth pointing out the main aspects of Kaggle:"
},
{
"code": null,
"e": 929,
"s": 704,
"text": "Datasets: Tens of thousands of datasets of all different types and sizes that you can download and use for free. This is a great place to go if you are looking for interesting data to explore or to test your modeling skills."
},
{
"code": null,
"e": 1147,
"s": 929,
"text": "Machine Learning Competitions: once the heart of Kaggle, these tests of modeling skill are a great way to learn cutting edge machine learning techniques and hone your abilities on interesting problems using real data."
},
{
"code": null,
"e": 1254,
"s": 1147,
"text": "Learn: A series of data science learning tracks covering SQL to Deep Learning taught in Jupyter Notebooks."
},
{
"code": null,
"e": 1369,
"s": 1254,
"text": "Discussion: A place to ask questions and get advice from the thousands of data scientists in the Kaggle community."
},
{
"code": null,
"e": 1924,
"s": 1369,
"text": "Kernels: Online programming environments running on Kaggle’s servers where you can write Python/R scripts, or Jupyter Notebooks. These kernels are entirely free to run (you can even add a GPU) and are a great resource because you don’t have to worry about setting up a data science environment on your own computer. The kernels can be used to analyze any dataset, compete in machine learning competitions, or complete the learning tracks. You can copy and build on existing kernels from other users and share your kernels with the community for feedback."
},
{
"code": null,
"e": 2438,
"s": 1924,
"text": "Overall, Kaggle is a great place to learn, whether that’s through the more traditional learning tracks or by competing in competitions. When I want to find out about the latest machine learning method, I could go read a book, or, I could go on Kaggle, find a competition, and see how people use it in practice. Personally, I find this much more enjoyable and a more effective teaching method. Moreover, the community is extremely supportive and always willing to answer questions or provide feedback on a project."
},
{
"code": null,
"e": 3027,
"s": 2438,
"text": "In this article, we’ll focus on getting started with a Kaggle machine learning competition: the Home Credit Default Risk problem. This is a fairly straightforward competition with a reasonable sized dataset (which can’t be said for all of the competitions) which means we can compete entirely using Kaggle’s kernels. This significantly lowers the barrier to entry because you don’t have to worry about any software on your computer and you don’t even have to download the data! As long as you have a Kaggle account and an Internet connection, you can connect to a kernel and run the code."
},
{
"code": null,
"e": 3356,
"s": 3027,
"text": "I plan to do the entire competition on Kaggle and the kernel (a Python Jupyter Notebook) for this post is available here. To get the most from this article, copy the kernel by creating a Kaggle account, then hitting the blue Fork Notebook button. This will open up the notebook for editing and running in the kernel environment."
},
{
"code": null,
"e": 3932,
"s": 3356,
"text": "The Home Credit Default Risk competition is a standard supervised machine learning task where the goal is to use historical loan application data to predict whether or not an applicant will repay a loan. During training, we provide our model with the features — the variables describing a loan application — and the label — a binary 0 if the loan was repaid and a 1 if the loan was not repaid — and the model learns a mapping from the features to the label. Then, during testing, we feed the model the features for a new batch of applications and ask it to predict the label."
},
{
"code": null,
"e": 4212,
"s": 3932,
"text": "All the data for this competition is structured meaning it exists in neat rows and columns — think a spreadsheet. This means we won’t need to use any convolutional neural networks (which excel at processing image data ) and it will give us great practice on a real-world dataset."
},
{
"code": null,
"e": 5050,
"s": 4212,
"text": "Home Credit, the host of the competition, is a finance provider that focuses on serving the unbanked population. Predicting whether or not an application will repay a loan is a vital business need, and Home Credit has developed this competition in the hopes that the Kaggle community can develop an effective algorithm for this task. This competition follows the general idea of most Kaggle competitions: a company has data and a problem to solve, and rather than (or in addition to) hiring internal data scientists to build a model, they put up a modest prize to entice the entire world to contribute solutions. A community of thousands of skilled data scientists (Kagglers) then work on the problem for basically no charge to come up with the best solution. As far as cost effective business plans go, this seems like a brilliant idea!"
},
{
"code": null,
"e": 5108,
"s": 5050,
"text": "When you go to the competition homepage, you’ll see this:"
},
{
"code": null,
"e": 5147,
"s": 5108,
"text": "Here’s a quick run through of the tabs"
},
{
"code": null,
"e": 5245,
"s": 5147,
"text": "Overview: a brief description of the problem, the evaluation metric, the prizes, and the timeline"
},
{
"code": null,
"e": 5462,
"s": 5245,
"text": "Data: all of the data needed for the competition as external data is not allowed. You can download all of the data, but we won’t need to do that because we will be using a Kaggle Kernel which can connect to the data."
},
{
"code": null,
"e": 5699,
"s": 5462,
"text": "Kernels: Previous work done by you and other competitors. This —in my opinion — is the most valuable resource for a competition. You can read through other scripts and notebooks and then copy the code (called “Forking”) to edit and run."
},
{
"code": null,
"e": 5898,
"s": 5699,
"text": "Discussion: another helpful resource where you can find conversations both from the competition hosts and from other competitors. A great place to ask questions and learn from the answers of others."
},
{
"code": null,
"e": 5944,
"s": 5898,
"text": "Leaderboard: who’s on top and where you stand"
},
{
"code": null,
"e": 5996,
"s": 5944,
"text": "Rules: not very interesting, but good to understand"
},
{
"code": null,
"e": 6063,
"s": 5996,
"text": "Team: manage the members of your team if you decide to form a team"
},
{
"code": null,
"e": 6167,
"s": 6063,
"text": "My Submissions: view your previous submissions and select the final ones to be used for the competition"
},
{
"code": null,
"e": 6709,
"s": 6167,
"text": "Although they are called competitions, Kaggle machine learning events should really be termed “collaborative projects” because the main goal is not necessarily to win but to practice and learn from fellow data scientists. Once you realize that it’s not so much about beating others but about expanding your own skills, you will get a lot more out of the competitions. When you sign up for Kaggle, you not only get all the resources , you also get to be part of a community of data scientists with thousands of years of collective experience."
},
{
"code": null,
"e": 7155,
"s": 6709,
"text": "Take advantage of all that experience by trying to be an active part of the community! That means anything from sharing a kernel to asking a question in a discussion forum. While it can be intimidating to make your work public, we learn best by making mistakes, receiving feedback, and improving so we don’t make the same mistake again. Everyone starts out a beginner, and the community is very supportive of data scientists of all skill levels."
},
{
"code": null,
"e": 7443,
"s": 7155,
"text": "In that mindset, I want to emphasize that discussion with others and building on others’ code is not only acceptable, but encouraged! In school, working with others is called cheating and gets you a zero, but in the real world, it’s called collaboration and an extremely important skill."
},
{
"code": null,
"e": 7945,
"s": 7443,
"text": "A great method for throwing yourself into a competition is to find a kernel someone has shared with a good leaderboard score, fork the kernel, edit it to try and improve the score, and then run it to see the results. Then, make the kernel public so others can use your work. Data scientists stand not on the shoulders of giants, but on the backs of thousands of individuals who have made their work public for the benefit of all. (Sorry for getting philosophical, but this is why I love data science!)"
},
{
"code": null,
"e": 8394,
"s": 7945,
"text": "Once you have a basic understanding of how Kaggle works and the philosophy of how to get the most out of a competition, it’s time to get started. Here, I’ll briefly outline a Python Jupyter Notebook I put together in a kernel for the Home Credit Default Risk problem, but to get the full benefit, you’ll want to fork the notebook on Kaggle and run it yourself (you don’t have to download or set-up anything so I’d highly encourage checking it out)."
},
{
"code": null,
"e": 8463,
"s": 8394,
"text": "When you open the notebook in a kernel, you’ll see this environment:"
},
{
"code": null,
"e": 8985,
"s": 8463,
"text": "Think of this as a standard Jupyter Notebook with slightly different aesthetics. You can write Python code and text (using Markdown syntax) just like in Jupyter and run the code completely in the cloud on Kaggle’s servers. However, Kaggle kernels have some unique features not available in Jupyter Notebook. Hit the leftward facing arrow in the upper right to expand the kernel control panel which brings up three tabs (if the notebook is not in fullscreen, then these three tabs may already be visible next to the code)."
},
{
"code": null,
"e": 9293,
"s": 8985,
"text": "In the data tab, we can view the datasets to which our Kernel is connected. In this case, we have the entire competition data, but we can also connect to any other dataset on Kaggle or upload our own data and access it in the kernel. Data files are available in the ../input/ directory from within the code:"
},
{
"code": null,
"e": 9376,
"s": 9293,
"text": "import os# List data files that are connected to the kernelos.listdir('../input/')"
},
{
"code": null,
"e": 9585,
"s": 9376,
"text": "The Settings tab lets us control different technical aspects of the kernel. Here we can add a GPU to our session, change the visibility, and install any Python package which is not already in the environment."
},
{
"code": null,
"e": 9813,
"s": 9585,
"text": "Finally, the Versions tab lets us see any previous committed runs of the code. We can view changes to the code, look at log files of a run, see the notebook generated by a run, and download the files that are output from a run."
},
{
"code": null,
"e": 10194,
"s": 9813,
"text": "To run the entire notebook and record a new Version, hit the blue Commit & Run button in the upper right of the kernel. This executes all the code, shows us the completed notebook (or any errors if there are mistakes), and saves any files that are created during the run. When we commit the notebook, we can then access any predictions our models made and submit them for scoring."
},
{
"code": null,
"e": 10659,
"s": 10194,
"text": "The first notebook is meant to get you familiar with the problem. We start off much the same way as any data science problem: understanding the data and the task. For this problem, there is 1 main training data file (with the labels included), 1 main testing data file, and 6 additional data files. In this first notebook, we use only the main data, which will get us a decent score, but later work will have to incorporate all the data in order to be competitive."
},
{
"code": null,
"e": 11111,
"s": 10659,
"text": "To understand the data, it’s best to take a couple minutes away from the keyboard and read through the problem documentation, such as the column descriptions of each data file. Because there are multiple files, we need to know how they are all linked together, although for this first notebook we only use the main file to keep things simple. Reading through other kernels can also help us get familiar with the data and which variables are important."
},
{
"code": null,
"e": 11484,
"s": 11111,
"text": "Once we understand the data and the problem, we can start structuring it for a machine learning task This means dealing with categorical variables (through one-hot encoding), filling in the missing values (imputation), and scaling the variables to a range. We can do exploratory data analysis, such as finding correlations with the label, and graphing these relationships."
},
{
"code": null,
"e": 11629,
"s": 11484,
"text": "We can use these relationships later on for modeling decisions, such as including which variables to use. (See the notebook for implementation)."
},
{
"code": null,
"e": 11723,
"s": 11629,
"text": "Of course, no exploratory data analysis is complete without my favorite plot, the Pairs Plot."
},
{
"code": null,
"e": 12069,
"s": 11723,
"text": "After thoroughly exploring the data and making sure it’s acceptable for machine learning, we move on to creating baseline models. However, before we quite get to the modeling stage, it’s critical we understand the performance metric for the competition. In a Kaggle competition, it all comes down to a single number, the metric on the test data."
},
{
"code": null,
"e": 12811,
"s": 12069,
"text": "While it might make intuitive sense to use accuracy for a binary classification task, that is a poor choice because we are dealing with an imbalanced class problem. Instead of accuracy, submissions are judged in terms of ROC AUC or Receiver Operating Characteristic curve Area Under the Curve. I’ll let you do the research on this one, or read the explanation in the notebook. Just know that higher is better, with a random model scoring 0.5 and a perfect model scoring 1.0. To calculate a ROC AUC, we need to make predictions in terms of probabilities rather than a binary 0 or 1. The ROC then shows the True Positive Rate versus the False Positive Rate as a function of the threshold according to which we classify an instance as positive."
},
{
"code": null,
"e": 13192,
"s": 12811,
"text": "Usually we like to make a naive baseline prediction, but in this case, we already know that random guessing on the task would get an ROC AUC of 0.5. Therefore, for our baseline model, we will use a slightly more sophisticated method, Logistic Regression. This is a popular simple algorithm for binary classification problems and it will set a low bar for future models to surpass."
},
{
"code": null,
"e": 13399,
"s": 13192,
"text": "After implementing the logistic regression, we can save the results to a csv file for submission. When the notebook is committed, any results we write will show up in the Output sub-tab on the Versions tab:"
},
{
"code": null,
"e": 13575,
"s": 13399,
"text": "From this tab, we can download the submissions to our computer and then upload them to the competition. In this notebook, we make four different models with scores as follows:"
},
{
"code": null,
"e": 13602,
"s": 13575,
"text": "Logistic Regression: 0.671"
},
{
"code": null,
"e": 13623,
"s": 13602,
"text": "Random Forest: 0.678"
},
{
"code": null,
"e": 13670,
"s": 13623,
"text": "Random Forest with Constructed Features: 0.678"
},
{
"code": null,
"e": 13709,
"s": 13670,
"text": "Light Gradient Boosting Machine: 0.729"
},
{
"code": null,
"e": 13924,
"s": 13709,
"text": "These scores don’t get us anywhere close to the top of the leaderboard, but they leave room for plenty of future improvement! We also get an idea of the performance we can expect using only a single source of data."
},
{
"code": null,
"e": 14219,
"s": 13924,
"text": "(Not surprisingly, the extraordinary Gradient Boosting Machine (using the LightGBM library) performs the best. This model wins nearly every structured Kaggle competition (where the data is in table format) and we will likely need to use some form of this model if we want to seriously compete!)"
},
{
"code": null,
"e": 14527,
"s": 14219,
"text": "This article and introductory kernel demonstrated a basic start to a Kaggle competition. It’s not meant to win, but rather to show you the basics of how to approach a machine learning competition and also a few models to get you off the ground (although the LightGBM model is like jumping off the deep end)."
},
{
"code": null,
"e": 15023,
"s": 14527,
"text": "Furthermore, I laid out my philosophy for machine learning competitions, which is to learn as much as possible by taking part in discussions, building on other’s code, and sharing your own work. It’s enjoyable to best your past scores, but I view doing well not as the main focus but as a positive side effect of learning new data science techniques. While these are known as competitions, they are really collaborative projects where everyone is welcome to participate and hone their abilities."
},
{
"code": null,
"e": 15356,
"s": 15023,
"text": "There remains a ton of work to be done, but thankfully we don’t have to do it alone. In later articles and notebooks we’ll see how to build on the work of others to make even better models. I hope this article (and the notebook kernel) has given you the confidence to start competing on Kaggle or taking on any data science project."
}
] |
Subsets and Splits