title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Django, Pandas, and Chart.js for a quick dashboard | by Shane Gary | Towards Data Science
Today we will talk about how to use Django, Pandas, and Chart.js together to throw up a quick dashboard. This will not be a Django tutorial, and I am taking some shortcuts here. The goal is to show you how to start using these tools together to quickly display some data. This is best applied when you need to get something up fast to visualize a single table with a few different charts. It could also be a starting point for a more robust django and chart.js site. Why Pandas? It is my experience that doing a bunch of pandas wrangling behind the scenes on a web server while someone is waiting on a website to respond is generally not an good strategy. There is certainly a way to do all of this from within Django directly from the database. The right database queries are almost always going to be faster and a better long-term answer for a dynamic production website. However, there are times when you have gotten to a good data exploration stage in a Jupyter notebook and you just want to throw something together to show what you have found so far. Why Django? Well, we are really talking about just two minutes of work to have Django up, running, authenticating, and talking to the database server of your choice. Django is a great choice for this project when you can get the data exported into a single table. Flask would probably be a better choice if you don’t need authentication and want to access the data from an existing database. Why Chart.js? I have found that if you want to deploy a bunch of different interactive charts by modifying a few variables Chart.js is amazing. After I hacked my way through the first chart, I found that the rest of them pretty much just worked with slight modification. The code is here. Let’s dig in. For the tutorial I grabbed this dataset. It is not the best dataset for dynamic charts, but it was easy. I am running this on a Debian server and my goal is just to document what was done. Again, this is not a Django or a python tutorial. I am going to speed through this section. Feel free to skip it but I thought it would be good to include for reference or so someone could reproduce this directly. pip install django pandasdjango-admin startproject django_chartscd django_chartspython manage.py migratepython manage.py createsuperuserpython manage.py startapp datacd data mkdir templatescd ..python manage.py runserver Optionally palettable is a fantastic for color palettes. However, the code will work without it. pip install palettable Based on the dataset I created the following model but this should be modified for your data. Make sure to update the database after you create this from the terminal: python manage.py makemigrationspython manage.py migrate I created a file with a method to load the csv file downloaded for Kaggle into the database using pandas and Django: The easiest way to run this is just to import it and run it in your view. We will delete this later but this is a good way to make sure the site is setup. So lets create the view but for now it just needs to run this function. Next, create a blank file named base/dashboard.html and create a data/urls.py file Edit django_charts/urls.py to add the data urls Update the django_charts/settings.py to include ‘data’ in INSTALLED_APPS: Let’s make sure we can see purchase in the admin site by adding this to data/admin.py Now you should be able to go to the dashboard page in a browser. Only do this once and then check on the admin site to see if you see the records. There should be 1000 records if you used the same dataset. OK. Sorry about the speed run but now we can start from the same place. I have a base file that will be extended. This might seem like a lot but this is a good basic template. I tend to put 4 code blocks in my base template. {% block title %}{% endblock %}{% block custom_css %}{% endblock %}{% block page_content %}{% endblock %}{% block js_scripts %}{% endblock %} The names are probably self-explanatory but the this gives me a way to add a title, css, body element, or javascript from any page. Admittedly, I mostly only use the page_content and js_scripts blocks. You will notice that I have included bootstrap CDN here. You really don’t need popper.js for this project. You could do the project without bootstrap actually but you would need to change some of dashboard.html. I have also included the chart.js cdn. This you will need for sure. I wrap any scripts I write into a $(document).ready in the base so that any manipulations won’t happen until the page is ready. Next here is dashboard.html which is the page for our charts: Basically, we are creating a bootstrap container, then a row, then a column. Inside the column I have a card-deck. The card-deck will create evenly sized cards. I then loop through each chart and place a card inside the card-deck. The card-deck will try and cram everything on the same row. The forloop.counters are used to detect the size of the screen and the wrap the card deck accordingly. This is my modification from this example. However, in practice you will find that somehow chart.js ignores your canvas size settings. This is one area that I wish chart.js would reconsider. HTML’s main function here is layout and I am not sure how to stop chart.js for ignoring the html layout. You will see my 2 main loops. I insert the html elements chart by chart in a card. Then later in the js code block I implement the js script chart by chart. This is a very simple way to get a responsive column (for mobile) or grid of charts. In my most recent case, I simply wanted a column of charts to show up on a mobile device. I think it might be easiest to look at views.py file first to get an idea of the flow of things. You will notice I deleted the one time method to load the data. We will be using a TemplateView. This is a very simple view to add things to. I tend to name my html files something I will be able to guess so I identify which template I am using with template_name. The only method we need to extend in this case is get_context_data. This is the method Django uses in class based views to get the data to be presented. We pull the objects we want and create a dataframe. Because chart.js generally does not play well with dates, I go ahead the convert the dates to strings after the dataframe is created. Then we just add each chart we want to the chart’s context. This allows us to loop through charts in the html code. For reference each chart is a dictionary that contains an html and a js entry. The html is just a simple canvas tag with the ID and the js does most of the work. I covered the loops in the last html section. The rest of this is in a file data/charts.py. I do this so it is easily portable to another project. You could just put this in views. I really should clean this up and package it, but the goal here is quick, temporary charts. I will include the entire file at the end but it is best to walk through some of the functions first and then get into the Chart class. All of the following functions are in the data/charts.py file. You can read through the comments to understand all the options. But this function takes in a Django model and returns all the records. You can include some filters after all of the name arguments. So for example: would limit the result to the city of Mandalay. Include and exclude fields work the same way Django typically uses these. If you do not include anything it will pull in all the fields from the model. It is important to note that excludes are processed after includes. So, if you include and exclude a column it will not show up. I use pandas apply to convert the dates based on the input. This does not actually do anything in this example. However, I used a dataclass for Chart and this is a way to set default options for all charts. I reuse the code and often modify the function when want to set a default option for all charts. If you wanted to not bother labeling each chart this function sets a random ID that is used by js to modify the associated html element. This ID is also used to name the JS function and variable to make debugging is easier. Because of that you need to avoid a chart ID with disallowed js characters (ex. -). get_colors is used to set the initial colors. If you pass in a palette it will use that instead. This is mainly written to take advantage of any palettable imports. However, if you do not pass anything in and don’t import something from palletable it will randomly generate colors. get_random_colors is used to generate colors in the case where no colors were passed in, imported or when you have more colors than values. It starts with the colors you pass in and them adds them at random until you reach the desired number. These are all the functions we needed before we get into the class. So, the following is the Chart class. I will start with just the class and then get into each function within the class. I used a dataclass here. These are relatively recent additions to Python and for quick and easy classes they often are a good choice. Setting the initial values can look a bit strange but it helps to ensure you do not use a mutable object for instances. It really is not difficult but does lead to writing some little functions to create initial values. from_lists is how I populate all the chart object with data, labels, and colors. After checking to make sure we have enough colors and adding some random colors, it builds what chart.js calls the datasets. Each stack needs its only little dictionary appended here. If there is only one value, we want to append the entire color palette so each bar is a different color. Labels are assigned directly. from_lists is how you could bypass pandas and create a chart from a database query. from_dataframe is what helps us use a few lines of code to manipulate just about any dataframe to be able to easily feed directly into from_lists for chart.js. We use the pandas pivot_table method to create a pivot table based on the input. That pivot table can the directly dump out the lists we need for the chart. If you are doing a ton of charts from a single dataframe this is very fast. OK.... I know. This is the one function that almost and maybe should have prevented me from publishing this article until I broke it up. However, it is easy to see what is going on here. We need to form our initial elements dictionary that contains our label, datasets, and options. These are the basic charts.js requirements. Once that happens the code uses the passed in type to set additional chart options. I think you will find that this might be the only function you need to add to for most if not all of the chart.js charts. This is where, for example, we need to tell chart.js to stack an axis for the stacked bar chart. You will see ‘begin at zero’ for a few of them because chart.js sometimes defaults to starting closer to the lowest value. Personally I think the default should be zero. Often it is as easy as the three at the end that really just need a chart type defined. I write functions here to handle the html and javascript code. Typically I would create actual html and js templates. It would be easy to do but this is more portable. It doesn’t get more simple than this. Just create the canvas for js to update. This is what the html loop places in the html template for each chart. get_js just generates the js code. You can see that most of the work is already done in the code above (get_elements). This grabs the chart element in the dom (the canvas) and adds the chart. Finally I just defined a function that returns both the html and js as a dictionary. You could basically just copy chart.py into your project and use it like I did in my views.py file. You need to make sure your base html file imports the chart.js cdn. Bootstrap is obviously optional but does make it easy. Happy dashboarding!!! Here is a complete class definition for reference:
[ { "code": null, "e": 638, "s": 171, "text": "Today we will talk about how to use Django, Pandas, and Chart.js together to throw up a quick dashboard. This will not be a Django tutorial, and I am taking some shortcuts here. The goal is to show you how to start using these tools together to quickly display some data. This is best applied when you need to get something up fast to visualize a single table with a few different charts. It could also be a starting point for a more robust django and chart.js site." }, { "code": null, "e": 1228, "s": 638, "text": "Why Pandas? It is my experience that doing a bunch of pandas wrangling behind the scenes on a web server while someone is waiting on a website to respond is generally not an good strategy. There is certainly a way to do all of this from within Django directly from the database. The right database queries are almost always going to be faster and a better long-term answer for a dynamic production website. However, there are times when you have gotten to a good data exploration stage in a Jupyter notebook and you just want to throw something together to show what you have found so far." }, { "code": null, "e": 1620, "s": 1228, "text": "Why Django? Well, we are really talking about just two minutes of work to have Django up, running, authenticating, and talking to the database server of your choice. Django is a great choice for this project when you can get the data exported into a single table. Flask would probably be a better choice if you don’t need authentication and want to access the data from an existing database." }, { "code": null, "e": 1891, "s": 1620, "text": "Why Chart.js? I have found that if you want to deploy a bunch of different interactive charts by modifying a few variables Chart.js is amazing. After I hacked my way through the first chart, I found that the rest of them pretty much just worked with slight modification." }, { "code": null, "e": 1923, "s": 1891, "text": "The code is here. Let’s dig in." }, { "code": null, "e": 2028, "s": 1923, "text": "For the tutorial I grabbed this dataset. It is not the best dataset for dynamic charts, but it was easy." }, { "code": null, "e": 2326, "s": 2028, "text": "I am running this on a Debian server and my goal is just to document what was done. Again, this is not a Django or a python tutorial. I am going to speed through this section. Feel free to skip it but I thought it would be good to include for reference or so someone could reproduce this directly." }, { "code": null, "e": 2547, "s": 2326, "text": "pip install django pandasdjango-admin startproject django_chartscd django_chartspython manage.py migratepython manage.py createsuperuserpython manage.py startapp datacd data mkdir templatescd ..python manage.py runserver" }, { "code": null, "e": 2644, "s": 2547, "text": "Optionally palettable is a fantastic for color palettes. However, the code will work without it." }, { "code": null, "e": 2667, "s": 2644, "text": "pip install palettable" }, { "code": null, "e": 2761, "s": 2667, "text": "Based on the dataset I created the following model but this should be modified for your data." }, { "code": null, "e": 2835, "s": 2761, "text": "Make sure to update the database after you create this from the terminal:" }, { "code": null, "e": 2891, "s": 2835, "text": "python manage.py makemigrationspython manage.py migrate" }, { "code": null, "e": 3008, "s": 2891, "text": "I created a file with a method to load the csv file downloaded for Kaggle into the database using pandas and Django:" }, { "code": null, "e": 3235, "s": 3008, "text": "The easiest way to run this is just to import it and run it in your view. We will delete this later but this is a good way to make sure the site is setup. So lets create the view but for now it just needs to run this function." }, { "code": null, "e": 3318, "s": 3235, "text": "Next, create a blank file named base/dashboard.html and create a data/urls.py file" }, { "code": null, "e": 3366, "s": 3318, "text": "Edit django_charts/urls.py to add the data urls" }, { "code": null, "e": 3440, "s": 3366, "text": "Update the django_charts/settings.py to include ‘data’ in INSTALLED_APPS:" }, { "code": null, "e": 3526, "s": 3440, "text": "Let’s make sure we can see purchase in the admin site by adding this to data/admin.py" }, { "code": null, "e": 3732, "s": 3526, "text": "Now you should be able to go to the dashboard page in a browser. Only do this once and then check on the admin site to see if you see the records. There should be 1000 records if you used the same dataset." }, { "code": null, "e": 3804, "s": 3732, "text": "OK. Sorry about the speed run but now we can start from the same place." }, { "code": null, "e": 3846, "s": 3804, "text": "I have a base file that will be extended." }, { "code": null, "e": 3957, "s": 3846, "text": "This might seem like a lot but this is a good basic template. I tend to put 4 code blocks in my base template." }, { "code": null, "e": 4099, "s": 3957, "text": "{% block title %}{% endblock %}{% block custom_css %}{% endblock %}{% block page_content %}{% endblock %}{% block js_scripts %}{% endblock %}" }, { "code": null, "e": 4301, "s": 4099, "text": "The names are probably self-explanatory but the this gives me a way to add a title, css, body element, or javascript from any page. Admittedly, I mostly only use the page_content and js_scripts blocks." }, { "code": null, "e": 4513, "s": 4301, "text": "You will notice that I have included bootstrap CDN here. You really don’t need popper.js for this project. You could do the project without bootstrap actually but you would need to change some of dashboard.html." }, { "code": null, "e": 4581, "s": 4513, "text": "I have also included the chart.js cdn. This you will need for sure." }, { "code": null, "e": 4709, "s": 4581, "text": "I wrap any scripts I write into a $(document).ready in the base so that any manipulations won’t happen until the page is ready." }, { "code": null, "e": 4771, "s": 4709, "text": "Next here is dashboard.html which is the page for our charts:" }, { "code": null, "e": 5002, "s": 4771, "text": "Basically, we are creating a bootstrap container, then a row, then a column. Inside the column I have a card-deck. The card-deck will create evenly sized cards. I then loop through each chart and place a card inside the card-deck." }, { "code": null, "e": 5461, "s": 5002, "text": "The card-deck will try and cram everything on the same row. The forloop.counters are used to detect the size of the screen and the wrap the card deck accordingly. This is my modification from this example. However, in practice you will find that somehow chart.js ignores your canvas size settings. This is one area that I wish chart.js would reconsider. HTML’s main function here is layout and I am not sure how to stop chart.js for ignoring the html layout." }, { "code": null, "e": 5793, "s": 5461, "text": "You will see my 2 main loops. I insert the html elements chart by chart in a card. Then later in the js code block I implement the js script chart by chart. This is a very simple way to get a responsive column (for mobile) or grid of charts. In my most recent case, I simply wanted a column of charts to show up on a mobile device." }, { "code": null, "e": 5954, "s": 5793, "text": "I think it might be easiest to look at views.py file first to get an idea of the flow of things. You will notice I deleted the one time method to load the data." }, { "code": null, "e": 6308, "s": 5954, "text": "We will be using a TemplateView. This is a very simple view to add things to. I tend to name my html files something I will be able to guess so I identify which template I am using with template_name. The only method we need to extend in this case is get_context_data. This is the method Django uses in class based views to get the data to be presented." }, { "code": null, "e": 6818, "s": 6308, "text": "We pull the objects we want and create a dataframe. Because chart.js generally does not play well with dates, I go ahead the convert the dates to strings after the dataframe is created. Then we just add each chart we want to the chart’s context. This allows us to loop through charts in the html code. For reference each chart is a dictionary that contains an html and a js entry. The html is just a simple canvas tag with the ID and the js does most of the work. I covered the loops in the last html section." }, { "code": null, "e": 7244, "s": 6818, "text": "The rest of this is in a file data/charts.py. I do this so it is easily portable to another project. You could just put this in views. I really should clean this up and package it, but the goal here is quick, temporary charts. I will include the entire file at the end but it is best to walk through some of the functions first and then get into the Chart class. All of the following functions are in the data/charts.py file." }, { "code": null, "e": 7458, "s": 7244, "text": "You can read through the comments to understand all the options. But this function takes in a Django model and returns all the records. You can include some filters after all of the name arguments. So for example:" }, { "code": null, "e": 7847, "s": 7458, "text": "would limit the result to the city of Mandalay. Include and exclude fields work the same way Django typically uses these. If you do not include anything it will pull in all the fields from the model. It is important to note that excludes are processed after includes. So, if you include and exclude a column it will not show up. I use pandas apply to convert the dates based on the input." }, { "code": null, "e": 8091, "s": 7847, "text": "This does not actually do anything in this example. However, I used a dataclass for Chart and this is a way to set default options for all charts. I reuse the code and often modify the function when want to set a default option for all charts." }, { "code": null, "e": 8399, "s": 8091, "text": "If you wanted to not bother labeling each chart this function sets a random ID that is used by js to modify the associated html element. This ID is also used to name the JS function and variable to make debugging is easier. Because of that you need to avoid a chart ID with disallowed js characters (ex. -)." }, { "code": null, "e": 8681, "s": 8399, "text": "get_colors is used to set the initial colors. If you pass in a palette it will use that instead. This is mainly written to take advantage of any palettable imports. However, if you do not pass anything in and don’t import something from palletable it will randomly generate colors." }, { "code": null, "e": 8924, "s": 8681, "text": "get_random_colors is used to generate colors in the case where no colors were passed in, imported or when you have more colors than values. It starts with the colors you pass in and them adds them at random until you reach the desired number." }, { "code": null, "e": 8992, "s": 8924, "text": "These are all the functions we needed before we get into the class." }, { "code": null, "e": 9113, "s": 8992, "text": "So, the following is the Chart class. I will start with just the class and then get into each function within the class." }, { "code": null, "e": 9467, "s": 9113, "text": "I used a dataclass here. These are relatively recent additions to Python and for quick and easy classes they often are a good choice. Setting the initial values can look a bit strange but it helps to ensure you do not use a mutable object for instances. It really is not difficult but does lead to writing some little functions to create initial values." }, { "code": null, "e": 9951, "s": 9467, "text": "from_lists is how I populate all the chart object with data, labels, and colors. After checking to make sure we have enough colors and adding some random colors, it builds what chart.js calls the datasets. Each stack needs its only little dictionary appended here. If there is only one value, we want to append the entire color palette so each bar is a different color. Labels are assigned directly. from_lists is how you could bypass pandas and create a chart from a database query." }, { "code": null, "e": 10344, "s": 9951, "text": "from_dataframe is what helps us use a few lines of code to manipulate just about any dataframe to be able to easily feed directly into from_lists for chart.js. We use the pandas pivot_table method to create a pivot table based on the input. That pivot table can the directly dump out the lists we need for the chart. If you are doing a ton of charts from a single dataframe this is very fast." }, { "code": null, "e": 11232, "s": 10344, "text": "OK.... I know. This is the one function that almost and maybe should have prevented me from publishing this article until I broke it up. However, it is easy to see what is going on here. We need to form our initial elements dictionary that contains our label, datasets, and options. These are the basic charts.js requirements. Once that happens the code uses the passed in type to set additional chart options. I think you will find that this might be the only function you need to add to for most if not all of the chart.js charts. This is where, for example, we need to tell chart.js to stack an axis for the stacked bar chart. You will see ‘begin at zero’ for a few of them because chart.js sometimes defaults to starting closer to the lowest value. Personally I think the default should be zero. Often it is as easy as the three at the end that really just need a chart type defined." }, { "code": null, "e": 11400, "s": 11232, "text": "I write functions here to handle the html and javascript code. Typically I would create actual html and js templates. It would be easy to do but this is more portable." }, { "code": null, "e": 11550, "s": 11400, "text": "It doesn’t get more simple than this. Just create the canvas for js to update. This is what the html loop places in the html template for each chart." }, { "code": null, "e": 11742, "s": 11550, "text": "get_js just generates the js code. You can see that most of the work is already done in the code above (get_elements). This grabs the chart element in the dom (the canvas) and adds the chart." }, { "code": null, "e": 11827, "s": 11742, "text": "Finally I just defined a function that returns both the html and js as a dictionary." }, { "code": null, "e": 12072, "s": 11827, "text": "You could basically just copy chart.py into your project and use it like I did in my views.py file. You need to make sure your base html file imports the chart.js cdn. Bootstrap is obviously optional but does make it easy. Happy dashboarding!!!" } ]
Batch Script - Variables
There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command. Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen. @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. 1 2 3 If we were to run the batch as Example 1 2 3 4 The output would still remain the same as above. However, the fourth parameter would be ignored. The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command. set /A variable-name=value where, variable-name is the name of the variable you want to set. variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. value is the value which needs to be set against the variable. /A – This switch is used if the value needs to be numeric in nature. /A – This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used. @echo off set message=Hello World echo %message% In the above code snippet, a variable called message is defined and set with the value of "Hello World". In the above code snippet, a variable called message is defined and set with the value of "Hello World". To display the value of the variable, note that the variable needs to be enclosed in the % sign. To display the value of the variable, note that the variable needs to be enclosed in the % sign. The above command produces the following output. Hello World In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50 In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script. @echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program. The ‘globalvar’ is defined with a global scope and is available throughout the entire script. The ‘globalvar’ is defined with a global scope and is available throughout the entire script. The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed. The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed. The above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist. If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. @echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2169, "text": "There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command." }, { "code": null, "e": 2551, "s": 2333, "text": "Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on." }, { "code": null, "e": 2675, "s": 2551, "text": "The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen." }, { "code": null, "e": 2712, "s": 2675, "text": "@echo off \necho %1 \necho %2 \necho %3" }, { "code": null, "e": 2806, "s": 2712, "text": "If the above batch script is stored in a file called test.bat and we were to run the batch as" }, { "code": null, "e": 2822, "s": 2806, "text": "Test.bat 1 2 3\n" }, { "code": null, "e": 2926, "s": 2822, "text": "Following is a screenshot of how this would look in the command prompt when the batch file is executed." }, { "code": null, "e": 2975, "s": 2926, "text": "The above command produces the following output." }, { "code": null, "e": 2984, "s": 2975, "text": "1 \n2 \n3\n" }, { "code": null, "e": 3015, "s": 2984, "text": "If we were to run the batch as" }, { "code": null, "e": 3032, "s": 3015, "text": "Example 1 2 3 4\n" }, { "code": null, "e": 3129, "s": 3032, "text": "The output would still remain the same as above. However, the fourth parameter would be ignored." }, { "code": null, "e": 3251, "s": 3129, "text": "The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command." }, { "code": null, "e": 3279, "s": 3251, "text": "set /A variable-name=value\n" }, { "code": null, "e": 3286, "s": 3279, "text": "where," }, { "code": null, "e": 3345, "s": 3286, "text": "variable-name is the name of the variable you want to set." }, { "code": null, "e": 3404, "s": 3345, "text": "variable-name is the name of the variable you want to set." }, { "code": null, "e": 3467, "s": 3404, "text": "value is the value which needs to be set against the variable." }, { "code": null, "e": 3530, "s": 3467, "text": "value is the value which needs to be set against the variable." }, { "code": null, "e": 3599, "s": 3530, "text": "/A – This switch is used if the value needs to be numeric in nature." }, { "code": null, "e": 3668, "s": 3599, "text": "/A – This switch is used if the value needs to be numeric in nature." }, { "code": null, "e": 3738, "s": 3668, "text": "The following example shows a simple way the set command can be used." }, { "code": null, "e": 3789, "s": 3738, "text": "@echo off \nset message=Hello World \necho %message%" }, { "code": null, "e": 3894, "s": 3789, "text": "In the above code snippet, a variable called message is defined and set with the value of \"Hello World\"." }, { "code": null, "e": 3999, "s": 3894, "text": "In the above code snippet, a variable called message is defined and set with the value of \"Hello World\"." }, { "code": null, "e": 4096, "s": 3999, "text": "To display the value of the variable, note that the variable needs to be enclosed in the % sign." }, { "code": null, "e": 4193, "s": 4096, "text": "To display the value of the variable, note that the variable needs to be enclosed in the % sign." }, { "code": null, "e": 4242, "s": 4193, "text": "The above command produces the following output." }, { "code": null, "e": 4255, "s": 4242, "text": "Hello World\n" }, { "code": null, "e": 4379, "s": 4255, "text": "In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch." }, { "code": null, "e": 4472, "s": 4379, "text": "The following code shows a simple way in which numeric values can be set with the /A switch." }, { "code": null, "e": 4543, "s": 4472, "text": "@echo off \nSET /A a = 5 \nSET /A b = 10 \nSET /A c = %a% + %b% \necho %c%" }, { "code": null, "e": 4624, "s": 4543, "text": "We are first setting the value of 2 variables, a and b to 5 and 10 respectively." }, { "code": null, "e": 4705, "s": 4624, "text": "We are first setting the value of 2 variables, a and b to 5 and 10 respectively." }, { "code": null, "e": 4763, "s": 4705, "text": "We are adding those values and storing in the variable c." }, { "code": null, "e": 4821, "s": 4763, "text": "We are adding those values and storing in the variable c." }, { "code": null, "e": 4877, "s": 4821, "text": "Finally, we are displaying the value of the variable c." }, { "code": null, "e": 4933, "s": 4877, "text": "Finally, we are displaying the value of the variable c." }, { "code": null, "e": 4978, "s": 4933, "text": "The output of the above program would be 15." }, { "code": null, "e": 5108, "s": 4978, "text": "All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files." }, { "code": null, "e": 5275, "s": 5108, "text": "@echo off \nSET /A a = 5 \nSET /A b = 10 \nSET /A c = %a% + %b% \necho %c% \nSET /A c = %a% - %b% \necho %c% \nSET /A c = %b% / %a% \necho %c% \nSET /A c = %b% * %a% \necho %c%" }, { "code": null, "e": 5324, "s": 5275, "text": "The above command produces the following output." }, { "code": null, "e": 5339, "s": 5324, "text": "15 \n-5 \n2 \n50\n" }, { "code": null, "e": 5658, "s": 5339, "text": "In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed." }, { "code": null, "e": 6143, "s": 5658, "text": "DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script." }, { "code": null, "e": 6257, "s": 6143, "text": "@echo off \nset globalvar = 5\nSETLOCAL\nset var = 13145\nset /A var = %var% + 5\necho %var%\necho %globalvar%\nENDLOCAL" }, { "code": null, "e": 6305, "s": 6257, "text": "Few key things to note about the above program." }, { "code": null, "e": 6399, "s": 6305, "text": "The ‘globalvar’ is defined with a global scope and is available throughout the entire script." }, { "code": null, "e": 6493, "s": 6399, "text": "The ‘globalvar’ is defined with a global scope and is available throughout the entire script." }, { "code": null, "e": 6691, "s": 6493, "text": "The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed." }, { "code": null, "e": 6889, "s": 6691, "text": "The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed." }, { "code": null, "e": 6938, "s": 6889, "text": "The above command produces the following output." }, { "code": null, "e": 6947, "s": 6938, "text": "13150\n5\n" }, { "code": null, "e": 7094, "s": 6947, "text": "You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist." }, { "code": null, "e": 7464, "s": 7094, "text": "If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications." }, { "code": null, "e": 7492, "s": 7464, "text": "@echo off \necho %JAVA_HOME%" }, { "code": null, "e": 7618, "s": 7492, "text": "The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output." }, { "code": null, "e": 7652, "s": 7618, "text": "C:\\Atlassian\\Bitbucket\\4.0.1\\jre\n" }, { "code": null, "e": 7659, "s": 7652, "text": " Print" }, { "code": null, "e": 7670, "s": 7659, "text": " Add Notes" } ]
The handling missing values exclusive pythonic guide | by Philippe Bouaziz,Data Scientist at Africa4Data,PhD | Towards Data Science
Handling missing values is a key step in exploratory data analysis (EDA) for most data science projects whether your developing machine learning models or business analytics. Most libraries including scikit-learn don’t build a model using data with missing values. Due to the high quantity of data, finding tricks for getting the best imputing values results is a massive advantage for becoming a unicorn data scientist. In this article, we will review the 3 most successful open source short python code lines which can be combined for handling missing values. For this article, we will be analyzing the samples flowers, titanic, and house prices Kaggle datasets you can find here. There are many scenarios dealing with missing values, missing numbers are commonly represented in python as nan which is short for “not a number”. The classical method consists in detecting cells with missing values, and count their numbers in each column with this command: missing_val_count_by_column = (data.isnull().sum())print(missing_val_count_by_column[missing_val_count_by_column > 0 3 mains methods can be found in most Kaggle competitions, let us review them: One way to drop columns with missing values is to drop the same columns in both train/test dataframe , as show below : From original data-frame: data_without_missing_values = original_data.dropna(axis=1) With train, test data-frame: cols_with_missing = [col for col in original_data.columnsif original_data[col].isnull().any()]reduced_original_data = original_data.drop(cols_with_missing, axis=1)reduced_test_data = test_data.drop(cols_with_missing, axis=1) After deleting your missing values your model loses access to this column which results in losing essential data. However, this strategy can be appropriate when most values in a column are missing. A better option than dropping your datasets columns is filling the missing values with the data distribution mean, as show below: from sklearn.impute import SimpleImputermy_imputer = SimpleImputer()data_with_imputed_values = my_imputer.fit_transform(original_data) This option is integrated commonly in the scikit-learn pipelines using more complex statistical metrics than the mean. A pipelines is a key strategy to simplify model validation and deployment. The last strategy systematically filling missing values randomly. If you need to get the best results, you need to consider your column statistical metrics. Here’s how it might look: # make a copy to avoid changing original data (when Imputing) new_data = original_data.copy() # make new columns indicating what will be imputed cols_with_missing = (col for col in new_data.columnsif new_data[col].isnull().any())for col in cols_with_missing:new_data[col + ‘_was_missing’] = new_data[col].isnull() # Imputation my_imputer = SimpleImputer()new_data = pd.DataFrame(my_imputer.fit_transform(new_data))new_data.columns = original_data.columns In most cases this approach will improve your results significantly. Now let us practice with the most known Kaggle datasets. We will review examples from titanic, flower, price housing Kaggle competitions datasets. To master missing value handling, I advise you to follow each step using this notebook and repeat the same steps with your datasets. data = pd.read_csv(‘../input/titanicdataset-traincsv/train.csv’) from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splittitanic_target = data.Survivedtitanic_predictors = data.drop(‘Survived’, axis=1) # For the sake of keeping the example simple, we’ll use only numeric predictors. titanic_numeric_predictors = titanic_predictors.select_dtypes(exclude=[‘object’])X = titanic_numeric_predictors.select_dtypes(exclude=[‘object’])y = titanic_target # Divide the data in train and test datasets. X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) Method 1 cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test)) Mean Absolute Error from dropping columns with Missing Values: 0.391340782122905 Method 2 my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test)) Mean Absolute Error from Imputation : 0.3914525139664804 Method 3 imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull() # Imputation my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test)) Mean Absolute Error from Imputation while Track What Was Imputed: 0.38586592178770945 => The best method is: Method 1 data = pd.read_csv(‘../input/flower-type-prediction-machine-hack/Train.csv’) from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splitflower_target = data.Classflower_predictors = data.drop(‘Class’, axis=1) # For the sake of keeping the example simple, we’ll use only numeric predictors. flower_numeric_predictors = flower_predictors.select_dtypes(exclude=[‘object’])X = flower_numeric_predictors.select_dtypes(exclude=[‘object’])y = flower_target # Divide the data in train and test datasets. X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) Method 1 cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test)) Mean Absolute Error from dropping columns with Missing Values: 1.316111627552926 Method 2 my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test)) Mean Absolute Error from Imputation: 1.3137274481525667 Method 3 imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull() # Imputation my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test)) Mean Absolute Error from Imputation while Track What Was Imputed: 1.3199202727466344 => The best method is: Method 1 data = pd.read_csv(‘../input/house-prices-advanced-regression-techniques/train.csv’) from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splithouse_target = data.SalePricehouse_predictors = data.drop(‘SalePrice’, axis=1) # For the sake of keeping the example simple, we’ll use only numeric predictors. house_numeric_predictors = house_predictors.select_dtypes(exclude=[‘object’])X = house_numeric_predictors.select_dtypes(exclude=[‘object’])y = house_target # Divide the data in train and test datasets. X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) Method 1 cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test)) Mean Absolute Error from dropping columns with Missing Values: 16907.894178082195 Method 2 my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test)) Mean Absolute Error from Imputation: 17433.810719178084 Method 3 imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull() # Imputation my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test)) Mean Absolute Error from Imputation while Track What Was Imputed: 17404.84109589041 => The best method is: Method 1 If you have some spare time I’d recommend, you’ll read this article : medium.com Refer to this link for the complete missing data analysis of these datasets using these methods. This brief overview is a reminder of the importance of using more than one method for handling missing values using python in data science. This post has for the scope to covered 3 essential Python handling missing values for making a complete exploration workflow, as well as useful documentation.
[ { "code": null, "e": 734, "s": 172, "text": "Handling missing values is a key step in exploratory data analysis (EDA) for most data science projects whether your developing machine learning models or business analytics. Most libraries including scikit-learn don’t build a model using data with missing values. Due to the high quantity of data, finding tricks for getting the best imputing values results is a massive advantage for becoming a unicorn data scientist. In this article, we will review the 3 most successful open source short python code lines which can be combined for handling missing values." }, { "code": null, "e": 855, "s": 734, "text": "For this article, we will be analyzing the samples flowers, titanic, and house prices Kaggle datasets you can find here." }, { "code": null, "e": 1130, "s": 855, "text": "There are many scenarios dealing with missing values, missing numbers are commonly represented in python as nan which is short for “not a number”. The classical method consists in detecting cells with missing values, and count their numbers in each column with this command:" }, { "code": null, "e": 1247, "s": 1130, "text": "missing_val_count_by_column = (data.isnull().sum())print(missing_val_count_by_column[missing_val_count_by_column > 0" }, { "code": null, "e": 1325, "s": 1247, "text": "3 mains methods can be found in most Kaggle competitions, let us review them:" }, { "code": null, "e": 1444, "s": 1325, "text": "One way to drop columns with missing values is to drop the same columns in both train/test dataframe , as show below :" }, { "code": null, "e": 1470, "s": 1444, "text": "From original data-frame:" }, { "code": null, "e": 1529, "s": 1470, "text": "data_without_missing_values = original_data.dropna(axis=1)" }, { "code": null, "e": 1558, "s": 1529, "text": "With train, test data-frame:" }, { "code": null, "e": 1783, "s": 1558, "text": "cols_with_missing = [col for col in original_data.columnsif original_data[col].isnull().any()]reduced_original_data = original_data.drop(cols_with_missing, axis=1)reduced_test_data = test_data.drop(cols_with_missing, axis=1)" }, { "code": null, "e": 1981, "s": 1783, "text": "After deleting your missing values your model loses access to this column which results in losing essential data. However, this strategy can be appropriate when most values in a column are missing." }, { "code": null, "e": 2111, "s": 1981, "text": "A better option than dropping your datasets columns is filling the missing values with the data distribution mean, as show below:" }, { "code": null, "e": 2246, "s": 2111, "text": "from sklearn.impute import SimpleImputermy_imputer = SimpleImputer()data_with_imputed_values = my_imputer.fit_transform(original_data)" }, { "code": null, "e": 2440, "s": 2246, "text": "This option is integrated commonly in the scikit-learn pipelines using more complex statistical metrics than the mean. A pipelines is a key strategy to simplify model validation and deployment." }, { "code": null, "e": 2623, "s": 2440, "text": "The last strategy systematically filling missing values randomly. If you need to get the best results, you need to consider your column statistical metrics. Here’s how it might look:" }, { "code": null, "e": 2685, "s": 2623, "text": "# make a copy to avoid changing original data (when Imputing)" }, { "code": null, "e": 2717, "s": 2685, "text": "new_data = original_data.copy()" }, { "code": null, "e": 2768, "s": 2717, "text": "# make new columns indicating what will be imputed" }, { "code": null, "e": 2937, "s": 2768, "text": "cols_with_missing = (col for col in new_data.columnsif new_data[col].isnull().any())for col in cols_with_missing:new_data[col + ‘_was_missing’] = new_data[col].isnull()" }, { "code": null, "e": 2950, "s": 2937, "text": "# Imputation" }, { "code": null, "e": 3078, "s": 2950, "text": "my_imputer = SimpleImputer()new_data = pd.DataFrame(my_imputer.fit_transform(new_data))new_data.columns = original_data.columns" }, { "code": null, "e": 3147, "s": 3078, "text": "In most cases this approach will improve your results significantly." }, { "code": null, "e": 3294, "s": 3147, "text": "Now let us practice with the most known Kaggle datasets. We will review examples from titanic, flower, price housing Kaggle competitions datasets." }, { "code": null, "e": 3427, "s": 3294, "text": "To master missing value handling, I advise you to follow each step using this notebook and repeat the same steps with your datasets." }, { "code": null, "e": 3492, "s": 3427, "text": "data = pd.read_csv(‘../input/titanicdataset-traincsv/train.csv’)" }, { "code": null, "e": 3722, "s": 3492, "text": "from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splittitanic_target = data.Survivedtitanic_predictors = data.drop(‘Survived’, axis=1)" }, { "code": null, "e": 3803, "s": 3722, "text": "# For the sake of keeping the example simple, we’ll use only numeric predictors." }, { "code": null, "e": 3967, "s": 3803, "text": "titanic_numeric_predictors = titanic_predictors.select_dtypes(exclude=[‘object’])X = titanic_numeric_predictors.select_dtypes(exclude=[‘object’])y = titanic_target" }, { "code": null, "e": 4013, "s": 3967, "text": "# Divide the data in train and test datasets." }, { "code": null, "e": 4084, "s": 4013, "text": "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" }, { "code": null, "e": 4093, "s": 4084, "text": "Method 1" }, { "code": null, "e": 4429, "s": 4093, "text": "cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test))" }, { "code": null, "e": 4510, "s": 4429, "text": "Mean Absolute Error from dropping columns with Missing Values: 0.391340782122905" }, { "code": null, "e": 4519, "s": 4510, "text": "Method 2" }, { "code": null, "e": 4759, "s": 4519, "text": "my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test))" }, { "code": null, "e": 4816, "s": 4759, "text": "Mean Absolute Error from Imputation : 0.3914525139664804" }, { "code": null, "e": 4825, "s": 4816, "text": "Method 3" }, { "code": null, "e": 5165, "s": 4825, "text": "imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull()" }, { "code": null, "e": 5178, "s": 5165, "text": "# Imputation" }, { "code": null, "e": 5493, "s": 5178, "text": "my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test))" }, { "code": null, "e": 5579, "s": 5493, "text": "Mean Absolute Error from Imputation while Track What Was Imputed: 0.38586592178770945" }, { "code": null, "e": 5611, "s": 5579, "text": "=> The best method is: Method 1" }, { "code": null, "e": 5688, "s": 5611, "text": "data = pd.read_csv(‘../input/flower-type-prediction-machine-hack/Train.csv’)" }, { "code": null, "e": 5910, "s": 5688, "text": "from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splitflower_target = data.Classflower_predictors = data.drop(‘Class’, axis=1)" }, { "code": null, "e": 5991, "s": 5910, "text": "# For the sake of keeping the example simple, we’ll use only numeric predictors." }, { "code": null, "e": 6151, "s": 5991, "text": "flower_numeric_predictors = flower_predictors.select_dtypes(exclude=[‘object’])X = flower_numeric_predictors.select_dtypes(exclude=[‘object’])y = flower_target" }, { "code": null, "e": 6197, "s": 6151, "text": "# Divide the data in train and test datasets." }, { "code": null, "e": 6268, "s": 6197, "text": "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" }, { "code": null, "e": 6277, "s": 6268, "text": "Method 1" }, { "code": null, "e": 6613, "s": 6277, "text": "cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test))" }, { "code": null, "e": 6694, "s": 6613, "text": "Mean Absolute Error from dropping columns with Missing Values: 1.316111627552926" }, { "code": null, "e": 6703, "s": 6694, "text": "Method 2" }, { "code": null, "e": 6943, "s": 6703, "text": "my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test))" }, { "code": null, "e": 6999, "s": 6943, "text": "Mean Absolute Error from Imputation: 1.3137274481525667" }, { "code": null, "e": 7008, "s": 6999, "text": "Method 3" }, { "code": null, "e": 7348, "s": 7008, "text": "imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull()" }, { "code": null, "e": 7361, "s": 7348, "text": "# Imputation" }, { "code": null, "e": 7676, "s": 7361, "text": "my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test))" }, { "code": null, "e": 7761, "s": 7676, "text": "Mean Absolute Error from Imputation while Track What Was Imputed: 1.3199202727466344" }, { "code": null, "e": 7793, "s": 7761, "text": "=> The best method is: Method 1" }, { "code": null, "e": 7878, "s": 7793, "text": "data = pd.read_csv(‘../input/house-prices-advanced-regression-techniques/train.csv’)" }, { "code": null, "e": 8106, "s": 7878, "text": "from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import train_test_splithouse_target = data.SalePricehouse_predictors = data.drop(‘SalePrice’, axis=1)" }, { "code": null, "e": 8187, "s": 8106, "text": "# For the sake of keeping the example simple, we’ll use only numeric predictors." }, { "code": null, "e": 8343, "s": 8187, "text": "house_numeric_predictors = house_predictors.select_dtypes(exclude=[‘object’])X = house_numeric_predictors.select_dtypes(exclude=[‘object’])y = house_target" }, { "code": null, "e": 8389, "s": 8343, "text": "# Divide the data in train and test datasets." }, { "code": null, "e": 8460, "s": 8389, "text": "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" }, { "code": null, "e": 8469, "s": 8460, "text": "Method 1" }, { "code": null, "e": 8805, "s": 8469, "text": "cols_with_missing = [col for col in X_train.columnsif X_train[col].isnull().any()]reduced_X_train = X_train.drop(cols_with_missing, axis=1)reduced_X_test = X_test.drop(cols_with_missing, axis=1)print(“Mean Absolute Error from dropping columns with Missing Values:”)print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test))" }, { "code": null, "e": 8887, "s": 8805, "text": "Mean Absolute Error from dropping columns with Missing Values: 16907.894178082195" }, { "code": null, "e": 8896, "s": 8887, "text": "Method 2" }, { "code": null, "e": 9136, "s": 8896, "text": "my_imputer = SimpleImputer()imputed_X_train = my_imputer.fit_transform(X_train)imputed_X_test = my_imputer.transform(X_test)print(“Mean Absolute Error from Imputation:”)print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test))" }, { "code": null, "e": 9192, "s": 9136, "text": "Mean Absolute Error from Imputation: 17433.810719178084" }, { "code": null, "e": 9201, "s": 9192, "text": "Method 3" }, { "code": null, "e": 9541, "s": 9201, "text": "imputed_X_train_plus = X_train.copy()imputed_X_test_plus = X_test.copy()cols_with_missing = (col for col in X_train.columnsif X_train[col].isnull().any())for col in cols_with_missing:imputed_X_train_plus[col + ‘_was_missing’] = imputed_X_train_plus[col].isnull()imputed_X_test_plus[col + ‘_was_missing’] = imputed_X_test_plus[col].isnull()" }, { "code": null, "e": 9554, "s": 9541, "text": "# Imputation" }, { "code": null, "e": 9869, "s": 9554, "text": "my_imputer = SimpleImputer()imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)print(“Mean Absolute Error from Imputation while Track What Was Imputed:”)print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test))" }, { "code": null, "e": 9953, "s": 9869, "text": "Mean Absolute Error from Imputation while Track What Was Imputed: 17404.84109589041" }, { "code": null, "e": 9985, "s": 9953, "text": "=> The best method is: Method 1" }, { "code": null, "e": 10055, "s": 9985, "text": "If you have some spare time I’d recommend, you’ll read this article :" }, { "code": null, "e": 10066, "s": 10055, "text": "medium.com" }, { "code": null, "e": 10163, "s": 10066, "text": "Refer to this link for the complete missing data analysis of these datasets using these methods." } ]
Find all occurrences of a given word in a matrix - GeeksforGeeks
31 Mar, 2022 Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word can be matched in all 8 directions at any point. Word is said be found in a direction if all characters match in this direction (not in zig-zag form). The solution should print all coordinates if a cycle is found. i.e. The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonals. Input: mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'} }; Word = “DES” Output: D(1, 2) E(1, 1) S(2, 0) D(1, 2) E(1, 3) S(0, 4) D(1, 2) E(1, 3) S(1, 4) D(2, 3) E(1, 3) S(0, 4) D(2, 3) E(1, 3) S(1, 4) D(2, 3) E(2, 4) S(1, 4) Input: char mat[ROW][COL] = { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'}}; char word[] ="BNEGSHBN"; Output: B(0, 0) N(0, 1) E(1, 1) G(2, 1) S(2, 0) H(1, 0) B(0, 0) N(0, 1) We strongly recommend you to minimize your browser and try this yourself first. This is mainly an extension of this post. Here with locations path is also printed.The problem can be easily solved by applying DFS() on each occurrence of first character of the word in the matrix. A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we recursively call for all adjacent vertices, here we can recursive call for 8 neighbours only. CPP Java Python3 C# Javascript // Program to find all occurrences of the word in// a matrix#include <bits/stdc++.h>using namespace std; #define ROW 3#define COL 5 // check whether given cell (row, col) is a valid// cell or not.bool isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row== prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellint rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesvoid DFS(char mat[][COL], int row, int col, int prevRow, int prevCol, char* word, string path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; //append current character position to path path += string(1, word[index]) + "(" + to_string(row) + ", " + to_string(col) + ") "; // current character matches with the last character // in the word if (index == n) { cout << path << endl; return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index+1, n);} // The main function to find all occurrences of the// word in a matrixvoid findWords(char mat[][COL], char* word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, "", 0, n);} // Driver program to test above functionint main(){ char mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'} }; char word[] ="DES"; findWords(mat, word, strlen(word) - 1); return 0;} // Java Program to find all occurrences of the word in// a matriximport java.util.*; class GFG{ static final int ROW = 3;static final int COL = 5; // check whether given cell (row, col) is a valid// cell or not.static boolean isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellstatic int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};static int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesstatic void DFS(char mat[][], int row, int col, int prevRow, int prevCol, char[] word, String path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; // append current character position to path path += (word[index]) + "(" + String.valueOf(row) + ", " + String.valueOf(col) + ") "; // current character matches with the last character // in the word if (index == n) { System.out.print(path +"\n"); return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixstatic void findWords(char mat[][], char []word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, "", 0, n);} // Driver codepublic static void main(String[] args){ char mat[][]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'}}; char []word ="DES".toCharArray(); findWords(mat, word, word.length - 1);}} // This code is contributed by PrinciRaj1992 # Python3 Program to find all occurrences of the word in# a matrixROW = 3COL = 5 # check whether given cell (row, col) is a valid# cell or not.def isvalid(row, col, prevRow, prevCol): # return true if row number and column number # is in range return (row >= 0) and (row < ROW) and (col >= 0) and \ (col < COL) and not (row== prevRow and col == prevCol) # These arrays are used to get row and column# numbers of 8 neighboursof a given cellrowNum = [-1, -1, -1, 0, 0, 1, 1, 1]colNum = [-1, 0, 1, -1, 1, -1, 0, 1] # A utility function to do DFS for a 2D boolean# matrix. It only considers the 8 neighbours as# adjacent verticesdef DFS(mat, row, col,prevRow, prevCol, word,path, index, n): # return if current character doesn't match with # the next character in the word if (index > n or mat[row][col] != word[index]): return # append current character position to path path += word[index] + "(" + str(row)+ ", " + str(col) + ") " # current character matches with the last character\ # in the word if (index == n): print(path) return # Recur for all connected neighbours for k in range(8): if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)): DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n) # The main function to find all occurrences of the# word in a matrixdef findWords(mat,word, n): # traverse through the all cells of given matrix for i in range(ROW): for j in range(COL): # occurrence of first character in matrix if (mat[i][j] == word[0]): # check and print if path exists DFS(mat, i, j, -1, -1, word, "", 0, n) # Driver codemat = [['B', 'N', 'E', 'Y', 'S'], ['H', 'E', 'D', 'E', 'S'], ['S', 'G', 'N', 'D', 'E']]word = list("DES")findWords(mat, word, len(word) - 1) # This code is contributed by SHUBHAMSINGH10 // C# Program to find all occurrences of the word in// a matrixusing System; class GFG{ static readonly int ROW = 3;static readonly int COL = 5; // check whether given cell (row, col) is a valid// cell or not.static bool isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellstatic int []rowNum = {-1, -1, -1, 0, 0, 1, 1, 1};static int []colNum = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D bool// matrix. It only considers the 8 neighbours as// adjacent verticesstatic void DFS(char [,]mat, int row, int col, int prevRow, int prevCol, char[] word, String path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row,col] != word[index]) return; // append current character position to path path += (word[index]) + "(" + String.Join("",row) + ", " + String.Join("",col) + ") "; // current character matches with the last character // in the word if (index == n) { Console.Write(path +"\n"); return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixstatic void findWords(char [,]mat, char []word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i,j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, "", 0, n);} // Driver codepublic static void Main(String[] args){ char [,]mat= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'}}; char []word ="DES".ToCharArray(); findWords(mat, word, word.Length - 1);}} // This code is contributed by 29AjayKumar <script>// Javascript Program to find all occurrences of the word in// a matrixlet ROW = 3;let COL = 5; // check whether given cell (row, col) is a valid// cell or not.function isvalid(row, col, prevRow, prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given celllet rowNum=[-1, -1, -1, 0, 0, 1, 1, 1];let colNum=[-1, 0, 1, -1, 1, -1, 0, 1]; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesfunction DFS(mat, row, col, prevRow, prevCol, word, path, index, n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; // append current character position to path path += (word[index]) + "(" + (row).toString() + ", " + (col).toString() + ") "; // current character matches with the last character // in the word if (index == n) { document.write(path +"<br>"); return; } // Recur for all connected neighbours for (let k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixfunction findWords(mat, word, n){ // traverse through the all cells of given matrix for (let i = 0; i < ROW; ++i) for (let j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, "", 0, n);} // Driver codelet mat = [['B', 'N', 'E', 'Y', 'S'], ['H', 'E', 'D', 'E', 'S'], ['S', 'G', 'N', 'D', 'E']];let word = "DES".split("");findWords(mat, word, word.length - 1); // This code is contributed by rag2127</script> Output : D(1, 2) E(1, 1) S(2, 0) D(1, 2) E(1, 3) S(0, 4) D(1, 2) E(1, 3) S(1, 4) D(2, 3) E(1, 3) S(0, 4) D(2, 3) E(1, 3) S(1, 4) D(2, 3) E(2, 4) S(1, 4) This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 princiraj1992 SHUBHAMSINGH10 29AjayKumar rag2127 simmytarika5 Pattern Searching Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Boyer Moore Algorithm for Pattern Searching Check if an URL is valid or not using Regular Expression Check if a string contains uppercase, lowercase, special characters and numeric values How to check if string contains only digits in Java Frequency of a substring in a string String matching where one string contains wildcard characters Remove leading zeros from a Number given as a string Pattern Searching using Suffix Tree Applications of String Matching Algorithms How to validate a domain name using Regular Expression
[ { "code": null, "e": 24337, "s": 24309, "text": "\n31 Mar, 2022" }, { "code": null, "e": 24759, "s": 24337, "text": "Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word can be matched in all 8 directions at any point. Word is said be found in a direction if all characters match in this direction (not in zig-zag form). The solution should print all coordinates if a cycle is found. i.e. The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonals. " }, { "code": null, "e": 25367, "s": 24759, "text": "Input:\nmat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'},\n {'H', 'E', 'D', 'E', 'S'},\n {'S', 'G', 'N', 'D', 'E'}\n };\nWord = “DES”\nOutput:\nD(1, 2) E(1, 1) S(2, 0) \nD(1, 2) E(1, 3) S(0, 4) \nD(1, 2) E(1, 3) S(1, 4)\nD(2, 3) E(1, 3) S(0, 4)\nD(2, 3) E(1, 3) S(1, 4)\nD(2, 3) E(2, 4) S(1, 4)\n\nInput:\nchar mat[ROW][COL] = { {'B', 'N', 'E', 'Y', 'S'},\n {'H', 'E', 'D', 'E', 'S'},\n {'S', 'G', 'N', 'D', 'E'}};\nchar word[] =\"BNEGSHBN\";\nOutput:\nB(0, 0) N(0, 1) E(1, 1) G(2, 1) S(2, 0) H(1, 0)\n B(0, 0) N(0, 1) " }, { "code": null, "e": 25833, "s": 25369, "text": "We strongly recommend you to minimize your browser and try this yourself first. This is mainly an extension of this post. Here with locations path is also printed.The problem can be easily solved by applying DFS() on each occurrence of first character of the word in the matrix. A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we recursively call for all adjacent vertices, here we can recursive call for 8 neighbours only. " }, { "code": null, "e": 25837, "s": 25833, "text": "CPP" }, { "code": null, "e": 25842, "s": 25837, "text": "Java" }, { "code": null, "e": 25850, "s": 25842, "text": "Python3" }, { "code": null, "e": 25853, "s": 25850, "text": "C#" }, { "code": null, "e": 25864, "s": 25853, "text": "Javascript" }, { "code": "// Program to find all occurrences of the word in// a matrix#include <bits/stdc++.h>using namespace std; #define ROW 3#define COL 5 // check whether given cell (row, col) is a valid// cell or not.bool isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row== prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellint rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesvoid DFS(char mat[][COL], int row, int col, int prevRow, int prevCol, char* word, string path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; //append current character position to path path += string(1, word[index]) + \"(\" + to_string(row) + \", \" + to_string(col) + \") \"; // current character matches with the last character // in the word if (index == n) { cout << path << endl; return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index+1, n);} // The main function to find all occurrences of the// word in a matrixvoid findWords(char mat[][COL], char* word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, \"\", 0, n);} // Driver program to test above functionint main(){ char mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'} }; char word[] =\"DES\"; findWords(mat, word, strlen(word) - 1); return 0;}", "e": 28211, "s": 25864, "text": null }, { "code": "// Java Program to find all occurrences of the word in// a matriximport java.util.*; class GFG{ static final int ROW = 3;static final int COL = 5; // check whether given cell (row, col) is a valid// cell or not.static boolean isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellstatic int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};static int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesstatic void DFS(char mat[][], int row, int col, int prevRow, int prevCol, char[] word, String path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; // append current character position to path path += (word[index]) + \"(\" + String.valueOf(row) + \", \" + String.valueOf(col) + \") \"; // current character matches with the last character // in the word if (index == n) { System.out.print(path +\"\\n\"); return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixstatic void findWords(char mat[][], char []word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, \"\", 0, n);} // Driver codepublic static void main(String[] args){ char mat[][]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'}}; char []word =\"DES\".toCharArray(); findWords(mat, word, word.length - 1);}} // This code is contributed by PrinciRaj1992", "e": 30617, "s": 28211, "text": null }, { "code": "# Python3 Program to find all occurrences of the word in# a matrixROW = 3COL = 5 # check whether given cell (row, col) is a valid# cell or not.def isvalid(row, col, prevRow, prevCol): # return true if row number and column number # is in range return (row >= 0) and (row < ROW) and (col >= 0) and \\ (col < COL) and not (row== prevRow and col == prevCol) # These arrays are used to get row and column# numbers of 8 neighboursof a given cellrowNum = [-1, -1, -1, 0, 0, 1, 1, 1]colNum = [-1, 0, 1, -1, 1, -1, 0, 1] # A utility function to do DFS for a 2D boolean# matrix. It only considers the 8 neighbours as# adjacent verticesdef DFS(mat, row, col,prevRow, prevCol, word,path, index, n): # return if current character doesn't match with # the next character in the word if (index > n or mat[row][col] != word[index]): return # append current character position to path path += word[index] + \"(\" + str(row)+ \", \" + str(col) + \") \" # current character matches with the last character\\ # in the word if (index == n): print(path) return # Recur for all connected neighbours for k in range(8): if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)): DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n) # The main function to find all occurrences of the# word in a matrixdef findWords(mat,word, n): # traverse through the all cells of given matrix for i in range(ROW): for j in range(COL): # occurrence of first character in matrix if (mat[i][j] == word[0]): # check and print if path exists DFS(mat, i, j, -1, -1, word, \"\", 0, n) # Driver codemat = [['B', 'N', 'E', 'Y', 'S'], ['H', 'E', 'D', 'E', 'S'], ['S', 'G', 'N', 'D', 'E']]word = list(\"DES\")findWords(mat, word, len(word) - 1) # This code is contributed by SHUBHAMSINGH10", "e": 32589, "s": 30617, "text": null }, { "code": "// C# Program to find all occurrences of the word in// a matrixusing System; class GFG{ static readonly int ROW = 3;static readonly int COL = 5; // check whether given cell (row, col) is a valid// cell or not.static bool isvalid(int row, int col, int prevRow, int prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given cellstatic int []rowNum = {-1, -1, -1, 0, 0, 1, 1, 1};static int []colNum = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D bool// matrix. It only considers the 8 neighbours as// adjacent verticesstatic void DFS(char [,]mat, int row, int col, int prevRow, int prevCol, char[] word, String path, int index, int n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row,col] != word[index]) return; // append current character position to path path += (word[index]) + \"(\" + String.Join(\"\",row) + \", \" + String.Join(\"\",col) + \") \"; // current character matches with the last character // in the word if (index == n) { Console.Write(path +\"\\n\"); return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixstatic void findWords(char [,]mat, char []word, int n){ // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i,j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, \"\", 0, n);} // Driver codepublic static void Main(String[] args){ char [,]mat= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'}}; char []word =\"DES\".ToCharArray(); findWords(mat, word, word.Length - 1);}} // This code is contributed by 29AjayKumar", "e": 34977, "s": 32589, "text": null }, { "code": "<script>// Javascript Program to find all occurrences of the word in// a matrixlet ROW = 3;let COL = 5; // check whether given cell (row, col) is a valid// cell or not.function isvalid(row, col, prevRow, prevCol){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);} // These arrays are used to get row and column// numbers of 8 neighboursof a given celllet rowNum=[-1, -1, -1, 0, 0, 1, 1, 1];let colNum=[-1, 0, 1, -1, 1, -1, 0, 1]; // A utility function to do DFS for a 2D boolean// matrix. It only considers the 8 neighbours as// adjacent verticesfunction DFS(mat, row, col, prevRow, prevCol, word, path, index, n){ // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; // append current character position to path path += (word[index]) + \"(\" + (row).toString() + \", \" + (col).toString() + \") \"; // current character matches with the last character // in the word if (index == n) { document.write(path +\"<br>\"); return; } // Recur for all connected neighbours for (let k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index + 1, n);} // The main function to find all occurrences of the// word in a matrixfunction findWords(mat, word, n){ // traverse through the all cells of given matrix for (let i = 0; i < ROW; ++i) for (let j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, \"\", 0, n);} // Driver codelet mat = [['B', 'N', 'E', 'Y', 'S'], ['H', 'E', 'D', 'E', 'S'], ['S', 'G', 'N', 'D', 'E']];let word = \"DES\".split(\"\");findWords(mat, word, word.length - 1); // This code is contributed by rag2127</script>", "e": 37167, "s": 34977, "text": null }, { "code": null, "e": 37177, "s": 37167, "text": "Output : " }, { "code": null, "e": 37327, "s": 37177, "text": "D(1, 2) E(1, 1) S(2, 0) \nD(1, 2) E(1, 3) S(0, 4) \nD(1, 2) E(1, 3) S(1, 4) \nD(2, 3) E(1, 3) S(0, 4) \nD(2, 3) E(1, 3) S(1, 4) \nD(2, 3) E(2, 4) S(1, 4) " }, { "code": null, "e": 37717, "s": 37327, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 37731, "s": 37717, "text": "princiraj1992" }, { "code": null, "e": 37746, "s": 37731, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 37758, "s": 37746, "text": "29AjayKumar" }, { "code": null, "e": 37766, "s": 37758, "text": "rag2127" }, { "code": null, "e": 37779, "s": 37766, "text": "simmytarika5" }, { "code": null, "e": 37797, "s": 37779, "text": "Pattern Searching" }, { "code": null, "e": 37815, "s": 37797, "text": "Pattern Searching" }, { "code": null, "e": 37913, "s": 37815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37922, "s": 37913, "text": "Comments" }, { "code": null, "e": 37935, "s": 37922, "text": "Old Comments" }, { "code": null, "e": 37979, "s": 37935, "text": "Boyer Moore Algorithm for Pattern Searching" }, { "code": null, "e": 38036, "s": 37979, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 38123, "s": 38036, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 38175, "s": 38123, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 38212, "s": 38175, "text": "Frequency of a substring in a string" }, { "code": null, "e": 38274, "s": 38212, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 38327, "s": 38274, "text": "Remove leading zeros from a Number given as a string" }, { "code": null, "e": 38363, "s": 38327, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 38406, "s": 38363, "text": "Applications of String Matching Algorithms" } ]
jQuery | parent() & parents() with Examples
03 Aug, 2021 The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element.Syntax: $(selector).parent() Here selector is the selected elements whose parent need to find.Parameter: It does not accept any parameter.Return value: It returns the parent of the selected elements.jQuery code to show the working of this function: <html> <head> <style> .main_div * { display: block; border: 1px solid green; color: green; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("span").parent().css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body> <div class="main_div"> <div style="width:500px;">div (Great-Grandparent) <ul>This is the grand-parent of the selected span element.! <li>This is the parent of the selected span element.! <span>This is the span element !!!</span> </li> </ul> </div> </div></body> </html> In the above code only the parent element of the selected element is get deep green colour.Output: The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.Syntax: $(selector).parents() Here selector is the selected element whose all parent need to find.Parameters: It does not accept any parameter.Return value: It returns all the parents of the selected element.jQuery code to show the working of this function: <html> <head> <style> .main_body* { display: block; border: 2px solid green; color: green; padding: 5px; margin: 15px; } </style><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script> $(document).ready(function() { $("span").parents().css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body class="main_body"> <div style="width:500px;">This is the great grand parent of the selected span element.! <ul>This is the grand parent of the selected span element.! <li>This is the parent of the selected element.! <span>This is the selected span element.!</span> </li> </ul> </div></body> </html> In the above code all the parent element of the selected is shown by the deep green color.Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Traversing JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 257, "s": 28, "text": "The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element.Syntax:" }, { "code": null, "e": 279, "s": 257, "text": "$(selector).parent()\n" }, { "code": null, "e": 499, "s": 279, "text": "Here selector is the selected elements whose parent need to find.Parameter: It does not accept any parameter.Return value: It returns the parent of the selected elements.jQuery code to show the working of this function:" }, { "code": "<html> <head> <style> .main_div * { display: block; border: 1px solid green; color: green; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"span\").parent().css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body> <div class=\"main_div\"> <div style=\"width:500px;\">div (Great-Grandparent) <ul>This is the grand-parent of the selected span element.! <li>This is the parent of the selected span element.! <span>This is the span element !!!</span> </li> </ul> </div> </div></body> </html>", "e": 1338, "s": 499, "text": null }, { "code": null, "e": 1437, "s": 1338, "text": "In the above code only the parent element of the selected element is get deep green colour.Output:" }, { "code": null, "e": 1678, "s": 1437, "text": "The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.Syntax:" }, { "code": null, "e": 1701, "s": 1678, "text": "$(selector).parents()\n" }, { "code": null, "e": 1929, "s": 1701, "text": "Here selector is the selected element whose all parent need to find.Parameters: It does not accept any parameter.Return value: It returns all the parents of the selected element.jQuery code to show the working of this function:" }, { "code": "<html> <head> <style> .main_body* { display: block; border: 2px solid green; color: green; padding: 5px; margin: 15px; } </style><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script><script> $(document).ready(function() { $(\"span\").parents().css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body class=\"main_body\"> <div style=\"width:500px;\">This is the great grand parent of the selected span element.! <ul>This is the grand parent of the selected span element.! <li>This is the parent of the selected element.! <span>This is the selected span element.!</span> </li> </ul> </div></body> </html>", "e": 2752, "s": 1929, "text": null }, { "code": null, "e": 2850, "s": 2752, "text": "In the above code all the parent element of the selected is shown by the deep green color.Output:" }, { "code": null, "e": 3118, "s": 2850, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 3136, "s": 3118, "text": "jQuery-Traversing" }, { "code": null, "e": 3147, "s": 3136, "text": "JavaScript" }, { "code": null, "e": 3154, "s": 3147, "text": "JQuery" } ]
Quantitative Aptitude - GeeksforGeeks
28 Nov, 2021 Woman Child Earns 6 + 4 = 10 | | |60% __ max 6 = 16 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n28 Nov, 2021" }, { "code": null, "e": 29603, "s": 29498, "text": "Woman Child Earns\n 6 + 4 = 10\n | | |60%\n __ max 6 = 16\n" } ]
Maintain the aspect ratio of a div with CSS
09 Jul, 2021 In order to maintain the aspect ratio of a div with CSS create flexible elements that keep their aspect ratio (4:3, 16:9, etc.) when resize the browser window.What is aspect ratio? The aspect ratio of an element describes the proportional relationship between its width and height. Two common video aspect ratios are 4:3 and 16:9.To maintain the aspect ratio of the div add a percentage value for padding-top. Different aspect ratio have different percentage values. Some of them are shown below: aspect ratio | padding-top value --------------|---------------------- 1:1 | 100% 16:9 | 56.25% 4:3 | 75% 3:2 | 66.66% 8:5 | 62.5% Syntax: element { padding-top: %value; } Example: html <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .container { background-color: green; position: relative; width: 100%; padding-top: 56.25%; /* 16:9 Aspect Ratio */ } .text { position: absolute; top: 0; left: 0; bottom: 0; right: 0; text-align: center; font-size: 25px; color: white; } .example { background: white; color: green; font-weight:bold; font-size: 40px; padding-bottom: 20px; } </style> </head> <body> <div class="container"> <div class="text"> <div class = "example">GeeksforGeeks</div> <p>A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. Also it contains several coding questions to practice and develop your skills in programming.</p> </div> </div> </body></html> Output: The output of above example is set to Aspect Ratio of 16:9. Resize the window to see the effect. Also change the corresponding values of the aspect ratio to see the desired changes in the browser window. sweetyty Web-Programs CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2021" }, { "code": null, "e": 527, "s": 28, "text": "In order to maintain the aspect ratio of a div with CSS create flexible elements that keep their aspect ratio (4:3, 16:9, etc.) when resize the browser window.What is aspect ratio? The aspect ratio of an element describes the proportional relationship between its width and height. Two common video aspect ratios are 4:3 and 16:9.To maintain the aspect ratio of the div add a percentage value for padding-top. Different aspect ratio have different percentage values. Some of them are shown below: " }, { "code": null, "e": 738, "s": 527, "text": "aspect ratio | padding-top value\n--------------|----------------------\n 1:1 | 100%\n 16:9 | 56.25%\n 4:3 | 75%\n 3:2 | 66.66%\n 8:5 | 62.5%" }, { "code": null, "e": 748, "s": 738, "text": "Syntax: " }, { "code": null, "e": 785, "s": 748, "text": "element {\n padding-top: %value;\n}" }, { "code": null, "e": 796, "s": 785, "text": "Example: " }, { "code": null, "e": 801, "s": 796, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> .container { background-color: green; position: relative; width: 100%; padding-top: 56.25%; /* 16:9 Aspect Ratio */ } .text { position: absolute; top: 0; left: 0; bottom: 0; right: 0; text-align: center; font-size: 25px; color: white; } .example { background: white; color: green; font-weight:bold; font-size: 40px; padding-bottom: 20px; } </style> </head> <body> <div class=\"container\"> <div class=\"text\"> <div class = \"example\">GeeksforGeeks</div> <p>A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc. Also it contains several coding questions to practice and develop your skills in programming.</p> </div> </div> </body></html> ", "e": 2178, "s": 801, "text": null }, { "code": null, "e": 2188, "s": 2178, "text": "Output: " }, { "code": null, "e": 2393, "s": 2188, "text": "The output of above example is set to Aspect Ratio of 16:9. Resize the window to see the effect. Also change the corresponding values of the aspect ratio to see the desired changes in the browser window. " }, { "code": null, "e": 2402, "s": 2393, "text": "sweetyty" }, { "code": null, "e": 2415, "s": 2402, "text": "Web-Programs" }, { "code": null, "e": 2419, "s": 2415, "text": "CSS" }, { "code": null, "e": 2424, "s": 2419, "text": "HTML" }, { "code": null, "e": 2441, "s": 2424, "text": "Web Technologies" }, { "code": null, "e": 2446, "s": 2441, "text": "HTML" }, { "code": null, "e": 2544, "s": 2446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2592, "s": 2544, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2654, "s": 2592, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2704, "s": 2654, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2762, "s": 2704, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2812, "s": 2762, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2860, "s": 2812, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2922, "s": 2860, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2972, "s": 2922, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2996, "s": 2972, "text": "REST API (Introduction)" } ]
Burst Balloon to maximize coins
09 Aug, 2021 We have been given N balloons, each with a number of coins associated with it. On bursting a balloon i, the number of coins gained is equal to A[i-1]*A[i]*A[i+1]. Also, balloons i-1 and i+1 now become adjacent. Find the maximum possible profit earned after bursting all the balloons. Assume an extra 1 at each boundary.Examples: Input : 5, 10 Output : 60 Explanation - First Burst 5, Coins = 1*5*10 Then burst 10, Coins+= 1*10*1 Total = 60 Input : 1, 2, 3, 4, 5 Output : 110 A recursive solution is discussed here. We can solve this problem using dynamic programming. First, consider a sub-array from indices Left to Right(inclusive). If we assume the balloon at index Last to be the last balloon to be burst in this sub-array, we would say the coined gained to be-A[left-1]*A[last]*A[right+1]. Also, the total Coin Gained would be this value, plus dp[left][last – 1] + dp[last + 1][right], where dp[i][j] means maximum coin gained for sub-array with indices i, j. Therefore, for each value of Left and Right, we need find and choose a value of Last with maximum coin gained, and update the dp array. Our Answer is the value at dp[1][N]. C++ Java Python3 C# Javascript // C++ program burst balloon problem#include <bits/stdc++.h>#include <iostream>using namespace std; int getMax(int A[], int N){ // Add Bordering Balloons int B[N + 2]; B[0] = 1; B[N + 1] = 1; for (int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declare DP Array int dp[N + 2][N + 2]; memset(dp, 0, sizeof(dp)); for (int length = 1; length < N + 1; length++) { for (int left = 1; left < N - length + 2; left++) { int right = left + length - 1; // For a sub-array from indices left, right // This innermost loop finds the last balloon burst for (int last = left; last < right + 1; last++) { dp[left][right] = max(dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; // Size of the array int N = sizeof(A) / sizeof(A[0]); // Calling function cout << getMax(A, N) << endl;} // This code is contributed by ashutosh450 // Java program to illustrate// Burst balloon problemimport java.util.Arrays; class GFG{ public static int getMax(int[] A, int N){ // Add Bordering Balloons int[] B = new int[N + 2]; B[0] = B[N + 1] = 1; for(int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declaring DP array int[][] dp = new int[N + 2][N + 2]; for(int length = 1; length < N + 1; length++) { for(int left = 1; left < N - length + 2; left++) { int right = left + length -1; // For a sub-array from indices // left, right. This innermost // loop finds the last balloon burst for(int last = left; last < right + 1; last++) { dp[left][right] = Math.max( dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codepublic static void main(String args[]){ int[] A = { 1, 2, 3, 4, 5 }; // Size of the array int N = A.length; // Calling function System.out.println(getMax(A, N));}} // This code is contributed by dadi madhav # Python3 program burst balloon problem. def getMax(A): N = len(A) A = [1] + A + [1]# Add Bordering Balloons dp = [[0 for x in range(N + 2)] for y in range(N + 2)]# Declare DP Array for length in range(1, N + 1): for left in range(1, N-length + 2): right = left + length -1 # For a sub-array from indices left, right # This innermost loop finds the last balloon burst for last in range(left, right + 1): dp[left][right] = max(dp[left][right], \ dp[left][last-1] + \ A[left-1]*A[last]*A[right + 1] + \ dp[last + 1][right]) return(dp[1][N]) # Driver codeA = [1, 2, 3, 4, 5]print(getMax(A)) // C# program to illustrate// Burst balloon problemusing System; class GFG{ public static int getMax(int[] A, int N){ // Add Bordering Balloons int[] B = new int[N + 2]; B[0] = B[N + 1] = 1; for(int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declaring DP array int[,] dp = new int[(N + 2), (N + 2)]; for(int length = 1; length < N + 1; length++) { for(int left = 1; left < N - length + 2; left++) { int right = left + length -1; // For a sub-array from indices // left, right. This innermost // loop finds the last balloon burst for(int last = left; last < right + 1; last++) { dp[left, right] = Math.Max( dp[left, right], dp[left, last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1, right]); } } } return dp[1, N];} // Driver codepublic static void Main(){ int[] A = new int[] { 1, 2, 3, 4, 5 }; // Size of the array int N = A.Length; // Calling function Console.WriteLine(getMax(A, N));}} // This code is contributed by sanjoy_62 <script>// Javascript program burst balloon problem function getMax(A, N){ // Add Bordering Balloons var B = new Array(N+2); B[0] = 1; B[N + 1] = 1; for (var i = 1; i <= N; i++) B[i] = A[i - 1]; // Declare DP Array var dp = new Array(N + 2); for (var i = 0; i < dp.length; i++) { dp[i] = new Array(N + 2).fill(0); } for (var length = 1; length < N + 1; length++) { for (var left = 1; left < N - length + 2; left++) { var right = left + length - 1; // For a sub-array from indices left, right // This innermost loop finds the last balloon burst for (var last = left; last < right + 1; last++) { dp[left][right] = Math.max(dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codevar A = [ 1, 2, 3, 4, 5 ]; // Size of the arrayvar N = A.length; // Calling functiondocument.write(getMax(A, N)); // This code is contributed by shubhamsingh10</script> 110 ashutosh450 dadimadhav sanjoy_62 ruhelaa48 SHUBHAMSINGH10 surindertarika1234 Picked Samsung Competitive Programming Dynamic Programming Samsung Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Algorithm Library | C++ Magicians STL Algorithm Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Aug, 2021" }, { "code": null, "e": 382, "s": 52, "text": "We have been given N balloons, each with a number of coins associated with it. On bursting a balloon i, the number of coins gained is equal to A[i-1]*A[i]*A[i+1]. Also, balloons i-1 and i+1 now become adjacent. Find the maximum possible profit earned after bursting all the balloons. Assume an extra 1 at each boundary.Examples: " }, { "code": null, "e": 557, "s": 382, "text": "Input : 5, 10\nOutput : 60\nExplanation - First Burst 5, Coins = 1*5*10\n Then burst 10, Coins+= 1*10*1\n Total = 60\n\nInput : 1, 2, 3, 4, 5\nOutput : 110" }, { "code": null, "e": 1221, "s": 557, "text": "A recursive solution is discussed here. We can solve this problem using dynamic programming. First, consider a sub-array from indices Left to Right(inclusive). If we assume the balloon at index Last to be the last balloon to be burst in this sub-array, we would say the coined gained to be-A[left-1]*A[last]*A[right+1]. Also, the total Coin Gained would be this value, plus dp[left][last – 1] + dp[last + 1][right], where dp[i][j] means maximum coin gained for sub-array with indices i, j. Therefore, for each value of Left and Right, we need find and choose a value of Last with maximum coin gained, and update the dp array. Our Answer is the value at dp[1][N]. " }, { "code": null, "e": 1225, "s": 1221, "text": "C++" }, { "code": null, "e": 1230, "s": 1225, "text": "Java" }, { "code": null, "e": 1238, "s": 1230, "text": "Python3" }, { "code": null, "e": 1241, "s": 1238, "text": "C#" }, { "code": null, "e": 1252, "s": 1241, "text": "Javascript" }, { "code": "// C++ program burst balloon problem#include <bits/stdc++.h>#include <iostream>using namespace std; int getMax(int A[], int N){ // Add Bordering Balloons int B[N + 2]; B[0] = 1; B[N + 1] = 1; for (int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declare DP Array int dp[N + 2][N + 2]; memset(dp, 0, sizeof(dp)); for (int length = 1; length < N + 1; length++) { for (int left = 1; left < N - length + 2; left++) { int right = left + length - 1; // For a sub-array from indices left, right // This innermost loop finds the last balloon burst for (int last = left; last < right + 1; last++) { dp[left][right] = max(dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; // Size of the array int N = sizeof(A) / sizeof(A[0]); // Calling function cout << getMax(A, N) << endl;} // This code is contributed by ashutosh450", "e": 2468, "s": 1252, "text": null }, { "code": "// Java program to illustrate// Burst balloon problemimport java.util.Arrays; class GFG{ public static int getMax(int[] A, int N){ // Add Bordering Balloons int[] B = new int[N + 2]; B[0] = B[N + 1] = 1; for(int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declaring DP array int[][] dp = new int[N + 2][N + 2]; for(int length = 1; length < N + 1; length++) { for(int left = 1; left < N - length + 2; left++) { int right = left + length -1; // For a sub-array from indices // left, right. This innermost // loop finds the last balloon burst for(int last = left; last < right + 1; last++) { dp[left][right] = Math.max( dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codepublic static void main(String args[]){ int[] A = { 1, 2, 3, 4, 5 }; // Size of the array int N = A.length; // Calling function System.out.println(getMax(A, N));}} // This code is contributed by dadi madhav", "e": 3849, "s": 2468, "text": null }, { "code": "# Python3 program burst balloon problem. def getMax(A): N = len(A) A = [1] + A + [1]# Add Bordering Balloons dp = [[0 for x in range(N + 2)] for y in range(N + 2)]# Declare DP Array for length in range(1, N + 1): for left in range(1, N-length + 2): right = left + length -1 # For a sub-array from indices left, right # This innermost loop finds the last balloon burst for last in range(left, right + 1): dp[left][right] = max(dp[left][right], \\ dp[left][last-1] + \\ A[left-1]*A[last]*A[right + 1] + \\ dp[last + 1][right]) return(dp[1][N]) # Driver codeA = [1, 2, 3, 4, 5]print(getMax(A))", "e": 4635, "s": 3849, "text": null }, { "code": "// C# program to illustrate// Burst balloon problemusing System; class GFG{ public static int getMax(int[] A, int N){ // Add Bordering Balloons int[] B = new int[N + 2]; B[0] = B[N + 1] = 1; for(int i = 1; i <= N; i++) B[i] = A[i - 1]; // Declaring DP array int[,] dp = new int[(N + 2), (N + 2)]; for(int length = 1; length < N + 1; length++) { for(int left = 1; left < N - length + 2; left++) { int right = left + length -1; // For a sub-array from indices // left, right. This innermost // loop finds the last balloon burst for(int last = left; last < right + 1; last++) { dp[left, right] = Math.Max( dp[left, right], dp[left, last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1, right]); } } } return dp[1, N];} // Driver codepublic static void Main(){ int[] A = new int[] { 1, 2, 3, 4, 5 }; // Size of the array int N = A.Length; // Calling function Console.WriteLine(getMax(A, N));}} // This code is contributed by sanjoy_62", "e": 6000, "s": 4635, "text": null }, { "code": "<script>// Javascript program burst balloon problem function getMax(A, N){ // Add Bordering Balloons var B = new Array(N+2); B[0] = 1; B[N + 1] = 1; for (var i = 1; i <= N; i++) B[i] = A[i - 1]; // Declare DP Array var dp = new Array(N + 2); for (var i = 0; i < dp.length; i++) { dp[i] = new Array(N + 2).fill(0); } for (var length = 1; length < N + 1; length++) { for (var left = 1; left < N - length + 2; left++) { var right = left + length - 1; // For a sub-array from indices left, right // This innermost loop finds the last balloon burst for (var last = left; last < right + 1; last++) { dp[left][right] = Math.max(dp[left][right], dp[left][last - 1] + B[left - 1] * B[last] * B[right + 1] + dp[last + 1][right]); } } } return dp[1][N];} // Driver codevar A = [ 1, 2, 3, 4, 5 ]; // Size of the arrayvar N = A.length; // Calling functiondocument.write(getMax(A, N)); // This code is contributed by shubhamsingh10</script>", "e": 7202, "s": 6000, "text": null }, { "code": null, "e": 7206, "s": 7202, "text": "110" }, { "code": null, "e": 7220, "s": 7208, "text": "ashutosh450" }, { "code": null, "e": 7231, "s": 7220, "text": "dadimadhav" }, { "code": null, "e": 7241, "s": 7231, "text": "sanjoy_62" }, { "code": null, "e": 7251, "s": 7241, "text": "ruhelaa48" }, { "code": null, "e": 7266, "s": 7251, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7285, "s": 7266, "text": "surindertarika1234" }, { "code": null, "e": 7292, "s": 7285, "text": "Picked" }, { "code": null, "e": 7300, "s": 7292, "text": "Samsung" }, { "code": null, "e": 7324, "s": 7300, "text": "Competitive Programming" }, { "code": null, "e": 7344, "s": 7324, "text": "Dynamic Programming" }, { "code": null, "e": 7352, "s": 7344, "text": "Samsung" }, { "code": null, "e": 7372, "s": 7352, "text": "Dynamic Programming" }, { "code": null, "e": 7470, "s": 7372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7497, "s": 7470, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7575, "s": 7497, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 7613, "s": 7575, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 7672, "s": 7613, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 7720, "s": 7672, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 7752, "s": 7720, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 7782, "s": 7752, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7811, "s": 7782, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 7845, "s": 7811, "text": "Longest Common Subsequence | DP-4" } ]
vector rbegin() and rend() function in C++ STL
09 Jun, 2022 vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: vector_name.rbegin() Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::rbegin() method: Program 1: Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::rbegin() method: Program 1: CPP // CPP program to illustrate// the vector::rbegin() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); // prints all the elements cout << "The vector elements in reverse order are:\n"; for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it << " "; return 0;} The vector elements in reverse order are: 15 14 13 12 11 Time Complexity – constant O(1) vector::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Syntax: vector::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Syntax: vector_name.rend() Parameters: The function does not take any parameter.Return value: The function returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Program to demonstrate the vector::rend() method: Program 1: Parameters: The function does not take any parameter.Return value: The function returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Program to demonstrate the vector::rend() method: Program 1: CPP // CPP program to illustrate// the vector::rend() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); cout << "The last element is: " << *v.rbegin(); // prints all the elements cout << "\nThe vector elements in reverse order are:\n"; for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it << " "; return 0;} The last element is: 15 The vector elements in reverse order are: 15 14 13 12 11 Time Complexity – constant O(1) abhijeetmurmu1997 utkarshgupta110092 CPP-Functions cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ std::find in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) Power Function in C/C++
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 194, "s": 53, "text": "vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: " }, { "code": null, "e": 335, "s": 194, "text": "vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: " }, { "code": null, "e": 356, "s": 335, "text": "vector_name.rbegin()" }, { "code": null, "e": 576, "s": 356, "text": "Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::rbegin() method: Program 1: " }, { "code": null, "e": 796, "s": 576, "text": "Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::rbegin() method: Program 1: " }, { "code": null, "e": 800, "s": 796, "text": "CPP" }, { "code": "// CPP program to illustrate// the vector::rbegin() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); // prints all the elements cout << \"The vector elements in reverse order are:\\n\"; for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it << \" \"; return 0;}", "e": 1217, "s": 800, "text": null }, { "code": null, "e": 1278, "s": 1221, "text": "The vector elements in reverse order are:\n15 14 13 12 11" }, { "code": null, "e": 1313, "s": 1280, "text": " Time Complexity – constant O(1)" }, { "code": null, "e": 1496, "s": 1313, "text": "vector::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Syntax: " }, { "code": null, "e": 1679, "s": 1496, "text": "vector::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Syntax: " }, { "code": null, "e": 1698, "s": 1679, "text": "vector_name.rend()" }, { "code": null, "e": 1959, "s": 1698, "text": "Parameters: The function does not take any parameter.Return value: The function returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Program to demonstrate the vector::rend() method: Program 1: " }, { "code": null, "e": 2220, "s": 1959, "text": "Parameters: The function does not take any parameter.Return value: The function returns a reverse iterator pointing to the theoretical element right before the first element in the vector container.Program to demonstrate the vector::rend() method: Program 1: " }, { "code": null, "e": 2224, "s": 2220, "text": "CPP" }, { "code": "// CPP program to illustrate// the vector::rend() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; v.push_back(11); v.push_back(12); v.push_back(13); v.push_back(14); v.push_back(15); cout << \"The last element is: \" << *v.rbegin(); // prints all the elements cout << \"\\nThe vector elements in reverse order are:\\n\"; for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it << \" \"; return 0;}", "e": 2693, "s": 2224, "text": null }, { "code": null, "e": 2778, "s": 2697, "text": "The last element is: 15\nThe vector elements in reverse order are:\n15 14 13 12 11" }, { "code": null, "e": 2813, "s": 2780, "text": " Time Complexity – constant O(1)" }, { "code": null, "e": 2831, "s": 2813, "text": "abhijeetmurmu1997" }, { "code": null, "e": 2850, "s": 2831, "text": "utkarshgupta110092" }, { "code": null, "e": 2864, "s": 2850, "text": "CPP-Functions" }, { "code": null, "e": 2875, "s": 2864, "text": "cpp-vector" }, { "code": null, "e": 2879, "s": 2875, "text": "STL" }, { "code": null, "e": 2883, "s": 2879, "text": "C++" }, { "code": null, "e": 2887, "s": 2883, "text": "STL" }, { "code": null, "e": 2891, "s": 2887, "text": "CPP" }, { "code": null, "e": 2989, "s": 2891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3013, "s": 2989, "text": "Sorting a vector in C++" }, { "code": null, "e": 3033, "s": 3013, "text": "Polymorphism in C++" }, { "code": null, "e": 3077, "s": 3033, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3110, "s": 3077, "text": "Friend class and function in C++" }, { "code": null, "e": 3135, "s": 3110, "text": "std::string class in C++" }, { "code": null, "e": 3152, "s": 3135, "text": "std::find in C++" }, { "code": null, "e": 3197, "s": 3152, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3245, "s": 3197, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3289, "s": 3245, "text": "List in C++ Standard Template Library (STL)" } ]
Java Examples - Find common elements from arrays
How to find common elements from arrays ? Following example shows how to find common elements from two arrays and store them in an array. import java.util.ArrayList; public class NewClass { public static void main(String[] args) { ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList(); objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon"); objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); objArray.add(2,"notcommon2"); System.out.println("Array elements of array1"+objArray); System.out.println("Array elements of array2"+objArray2); objArray.retainAll(objArray2); System.out.println("Array1 after retaining common elements of array2 & array1"+objArray); } } The above code sample will produce the following result. Array elements of array1[common1, common2, notcommon2] Array elements of array2[common1, common2, notcommon, notcommon1] Array1 after retaining common elements of array2 & array1 [common1, common2] Another sample example of Find common elements from arrays public class HelloWorld { public static void main(String a[]) { int[] arr1 = {4,7,3,9,2}; int[] arr2 = {3,2,12,9,40,32,4}; for(int i = 0;i < arr1.length; i++) { for(int j = 0; j < arr2.length; j++) { if(arr1[i] == arr2[j]) { System.out.println(arr1[i]); } } } } } The above code sample will produce the following result.
[ { "code": null, "e": 2244, "s": 2202, "text": "How to find common elements from arrays ?" }, { "code": null, "e": 2340, "s": 2244, "text": "Following example shows how to find common elements from two arrays and store them in an array." }, { "code": null, "e": 3036, "s": 2340, "text": "import java.util.ArrayList;\n\npublic class NewClass {\n public static void main(String[] args) {\n ArrayList objArray = new ArrayList();\n ArrayList objArray2 = new ArrayList();\n objArray2.add(0,\"common1\");\n objArray2.add(1,\"common2\");\n objArray2.add(2,\"notcommon\");\n objArray2.add(3,\"notcommon1\");\n objArray.add(0,\"common1\");\n objArray.add(1,\"common2\");\n objArray.add(2,\"notcommon2\");\n System.out.println(\"Array elements of array1\"+objArray);\n System.out.println(\"Array elements of array2\"+objArray2);\n objArray.retainAll(objArray2);\n System.out.println(\"Array1 after retaining common elements of array2 & array1\"+objArray);\n }\n}" }, { "code": null, "e": 3093, "s": 3036, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3292, "s": 3093, "text": "Array elements of array1[common1, common2, notcommon2]\nArray elements of array2[common1, common2, notcommon,\nnotcommon1]\nArray1 after retaining common elements of array2 & array1\n[common1, common2]\n" }, { "code": null, "e": 3351, "s": 3292, "text": "Another sample example of Find common elements from arrays" }, { "code": null, "e": 3712, "s": 3351, "text": "public class HelloWorld {\n public static void main(String a[]) {\n int[] arr1 = {4,7,3,9,2};\n int[] arr2 = {3,2,12,9,40,32,4};\n \n for(int i = 0;i < arr1.length; i++) {\n for(int j = 0; j < arr2.length; j++) {\n if(arr1[i] == arr2[j]) { \n System.out.println(arr1[i]);\n } \n } \n }\n }\n}" } ]
SQL – SELECT FIRST
14 May, 2021 In this article we are going to study the SELECT FIRST commands in SQL, as we all know that there is already a command for selecting all the rows from a table by “SELECT * FROM Table” but if we want to select only the top row, here SELECT FIRST comes into play. This FIRST query can be used for login related purpose in any website, or if we want to make a billing system we can implement this that increment the Bill number from the top row number. The first () function is used to return the first row of any table. Syntax : SELECT FIRST(columnName) FROM tableName So we will start by creating a database to perform the operations. Step 1: Create a database. CREATE DATABASE GFG Step 2: Use this database USE GFG Step 3: Create a table /****** (1,1) indicates that increment 1 every time insert is performed ******/ CREATE TABLE first (ID INT PRIMARY KEY IDENTITY (1,1), Name VARCHAR (20) NOT NULL, Age INT NOT NULL, Dept VARCHAR (20) NOT NULL) Step 4: Check the created table schema Schema of table Step 4: Insert the values in Table /****** Insertion queries ******/ INSERT INTO [dbo].[first] ([Name] ,[Age] ,[Dept]) VALUES ('Devesh', 20, 'CSE') GO INSERT INTO [dbo].[first] ([Name] ,[Age] ,[Dept]) VALUES ('Aditya', 19, 'BT') GO INSERT INTO [dbo].[first] ([Name] ,[Age] ,[Dept]) VALUES ('Megha', 20, 'CSE') GO Step 5: Use first() function in table( first() is used in MS ACCESS ). SELECT TOP 1 Name FROM first Picked SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL SQL | Sub queries in From Clause What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2021" }, { "code": null, "e": 504, "s": 54, "text": "In this article we are going to study the SELECT FIRST commands in SQL, as we all know that there is already a command for selecting all the rows from a table by “SELECT * FROM Table” but if we want to select only the top row, here SELECT FIRST comes into play. This FIRST query can be used for login related purpose in any website, or if we want to make a billing system we can implement this that increment the Bill number from the top row number." }, { "code": null, "e": 572, "s": 504, "text": "The first () function is used to return the first row of any table." }, { "code": null, "e": 621, "s": 572, "text": "Syntax : SELECT FIRST(columnName) FROM tableName" }, { "code": null, "e": 688, "s": 621, "text": "So we will start by creating a database to perform the operations." }, { "code": null, "e": 715, "s": 688, "text": "Step 1: Create a database." }, { "code": null, "e": 735, "s": 715, "text": "CREATE DATABASE GFG" }, { "code": null, "e": 761, "s": 735, "text": "Step 2: Use this database" }, { "code": null, "e": 769, "s": 761, "text": "USE GFG" }, { "code": null, "e": 792, "s": 769, "text": "Step 3: Create a table" }, { "code": null, "e": 1075, "s": 792, "text": "/****** (1,1) indicates that increment 1 every time insert is performed ******/\n\nCREATE TABLE first \n (ID INT PRIMARY KEY IDENTITY (1,1),\n Name VARCHAR (20) NOT NULL,\n Age INT NOT NULL,\n Dept VARCHAR (20) NOT NULL)" }, { "code": null, "e": 1116, "s": 1075, "text": "Step 4: Check the created table schema " }, { "code": null, "e": 1132, "s": 1116, "text": "Schema of table" }, { "code": null, "e": 1167, "s": 1132, "text": "Step 4: Insert the values in Table" }, { "code": null, "e": 1595, "s": 1167, "text": "/****** Insertion queries ******/\n\nINSERT INTO [dbo].[first]\n ([Name]\n ,[Age]\n ,[Dept])\n VALUES\n ('Devesh', 20, 'CSE')\nGO\n\nINSERT INTO [dbo].[first]\n ([Name]\n ,[Age]\n ,[Dept])\n VALUES\n ('Aditya', 19, 'BT')\nGO\n\nINSERT INTO [dbo].[first]\n ([Name]\n ,[Age]\n ,[Dept])\n VALUES\n ('Megha', 20, 'CSE')\nGO" }, { "code": null, "e": 1666, "s": 1595, "text": "Step 5: Use first() function in table( first() is used in MS ACCESS )." }, { "code": null, "e": 1695, "s": 1666, "text": "SELECT TOP 1 Name FROM first" }, { "code": null, "e": 1702, "s": 1695, "text": "Picked" }, { "code": null, "e": 1716, "s": 1702, "text": "SQL-Functions" }, { "code": null, "e": 1720, "s": 1716, "text": "SQL" }, { "code": null, "e": 1724, "s": 1720, "text": "SQL" }, { "code": null, "e": 1822, "s": 1724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1888, "s": 1822, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1912, "s": 1888, "text": "Window functions in SQL" }, { "code": null, "e": 1945, "s": 1912, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1977, "s": 1945, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1994, "s": 1977, "text": "SQL using Python" }, { "code": null, "e": 2072, "s": 1994, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2102, "s": 2072, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2138, "s": 2102, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2169, "s": 2138, "text": "SQL Query to Compare Two Dates" } ]
How to determine the content of HTML elements overflow or not ?
18 Jun, 2019 Given an HTML element and the task is to determine whether its content is overflow or not using JavaScript. Approach: Select the element to check form overflow. Check its style.overflow property, if it is ‘visible’ then the element is hidden. Also, check if its clientWidth is less then scrollWidth or clientHeight is less then scrollHeight then the element is overflowed. Example 1: In this example, check the content of paragraph (<p> element) is overflowed or not. <!DOCTYPE HTML> <html> <head> <title> How to determine the content of HTML elements overflow or not </title> <style> #GFG_UP { font-size: 16px; font-weight: bold; border: 1px solid black; height: 20px; width: 200px; margin: 0 auto; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <br><br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "Click on button to check OverFlow"; el_up.innerHTML = str; function check(el) { var curOverf = el.style.overflow; if ( !curOverf || curOverf === "visible" ) el.style.overflow = "hidden"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverf; return isOverflowing; } function gfg_Run() { ans = "No Overflow"; if (check(el_up)) { ans = "Content Overflowed"; } el_down.innerHTML = ans; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This is same as previous example, but here the content of paragraph (<p> element) is not overflowed, so the example checks and display the desired output No Overflow. <!DOCTYPE HTML> <html> <head> <title> How to determine the content of HTML elements overflow or not </title> <style> #GFG_UP { font-size: 16px; font-weight: bold; border: 1px solid black; height: 20px; width: 200px; margin: 0 auto; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <br><br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "Click on button to check"; el_up.innerHTML = str; function check(el) { var curOverf = el.style.overflow; if ( !curOverf || curOverf === "visible" ) el.style.overflow = "hidden"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverf; return isOverflowing; } function gfg_Run() { ans = "No Overflow"; if (check(el_up)) { ans = "Content Overflowed"; } el_down.innerHTML = ans; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2019" }, { "code": null, "e": 136, "s": 28, "text": "Given an HTML element and the task is to determine whether its content is overflow or not using JavaScript." }, { "code": null, "e": 146, "s": 136, "text": "Approach:" }, { "code": null, "e": 189, "s": 146, "text": "Select the element to check form overflow." }, { "code": null, "e": 271, "s": 189, "text": "Check its style.overflow property, if it is ‘visible’ then the element is hidden." }, { "code": null, "e": 401, "s": 271, "text": "Also, check if its clientWidth is less then scrollWidth or clientHeight is less then scrollHeight then the element is overflowed." }, { "code": null, "e": 496, "s": 401, "text": "Example 1: In this example, check the content of paragraph (<p> element) is overflowed or not." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to determine the content of HTML elements overflow or not </title> <style> #GFG_UP { font-size: 16px; font-weight: bold; border: 1px solid black; height: 20px; width: 200px; margin: 0 auto; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <br><br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"Click on button to check OverFlow\"; el_up.innerHTML = str; function check(el) { var curOverf = el.style.overflow; if ( !curOverf || curOverf === \"visible\" ) el.style.overflow = \"hidden\"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverf; return isOverflowing; } function gfg_Run() { ans = \"No Overflow\"; if (check(el_up)) { ans = \"Content Overflowed\"; } el_down.innerHTML = ans; } </script> </body> </html> ", "e": 2417, "s": 496, "text": null }, { "code": null, "e": 2425, "s": 2417, "text": "Output:" }, { "code": null, "e": 2456, "s": 2425, "text": "Before clicking on the button:" }, { "code": null, "e": 2486, "s": 2456, "text": "After clicking on the button:" }, { "code": null, "e": 2664, "s": 2486, "text": "Example 2: This is same as previous example, but here the content of paragraph (<p> element) is not overflowed, so the example checks and display the desired output No Overflow." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to determine the content of HTML elements overflow or not </title> <style> #GFG_UP { font-size: 16px; font-weight: bold; border: 1px solid black; height: 20px; width: 200px; margin: 0 auto; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <br><br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = \"Click on button to check\"; el_up.innerHTML = str; function check(el) { var curOverf = el.style.overflow; if ( !curOverf || curOverf === \"visible\" ) el.style.overflow = \"hidden\"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverf; return isOverflowing; } function gfg_Run() { ans = \"No Overflow\"; if (check(el_up)) { ans = \"Content Overflowed\"; } el_down.innerHTML = ans; } </script> </body> </html> ", "e": 4576, "s": 2664, "text": null }, { "code": null, "e": 4584, "s": 4576, "text": "Output:" }, { "code": null, "e": 4615, "s": 4584, "text": "Before clicking on the button:" }, { "code": null, "e": 4645, "s": 4615, "text": "After clicking on the button:" }, { "code": null, "e": 4661, "s": 4645, "text": "JavaScript-Misc" }, { "code": null, "e": 4672, "s": 4661, "text": "JavaScript" }, { "code": null, "e": 4689, "s": 4672, "text": "Web Technologies" }, { "code": null, "e": 4716, "s": 4689, "text": "Web technologies Questions" } ]
How to find the unique values in a column of R dataframe? - GeeksforGeeks
21 Apr, 2021 In this article, we will discuss how to find out the unique value in a column of dataframe in R Programming language. For this task, unique() function is used where the column name is passed for which unique values are to be printed. Syntax: unique(x) parameters: x: data frame For a column name select the column using $ dataframe$column_name Example 1: R id<- c(1,2,3,4,5,6,7,8,9) country <- c("INDIA","AMERICA","JAPAN","CHINA","BANGLADESH", "SRILANKA","NEPAL","AMERICA","CHINA") data<-data.frame(id,country) unique(data$country) Output: [1] INDIA AMERICA JAPAN CHINA BANGLADESH SRILANKA NEPAL Levels: AMERICA BANGLADESH CHINA INDIA JAPAN NEPAL SRILANKA Example 2: R data <- data.frame(x1 = c(9, 5, 6, 8, 9), x2 = c(2, 4, 2, 7, 1), x3 = c(3,6,7,0,3), x4 = c("Hello", "value", "value", "geeksforgeeks", NA) ) unique(data[c("x2")]) unique(data[c("x1")]) Output: Unique data in column x2 x2 1 2 2 4 4 7 5 1 Unique data in column x1 x1 1 9 2 5 3 6 4 8 Example 3: R data<- data.frame(Student=c('John','Lee','Guy', 'John','Lee','Guy'), Age=c(18,19,20,18,19,20), Gender=c('Male','Female','Male', 'Male','Female','Male')) unique(data) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n21 Apr, 2021" }, { "code": null, "e": 26721, "s": 26487, "text": "In this article, we will discuss how to find out the unique value in a column of dataframe in R Programming language. For this task, unique() function is used where the column name is passed for which unique values are to be printed." }, { "code": null, "e": 26739, "s": 26721, "text": "Syntax: unique(x)" }, { "code": null, "e": 26751, "s": 26739, "text": "parameters:" }, { "code": null, "e": 26765, "s": 26751, "text": "x: data frame" }, { "code": null, "e": 26809, "s": 26765, "text": "For a column name select the column using $" }, { "code": null, "e": 26831, "s": 26809, "text": "dataframe$column_name" }, { "code": null, "e": 26842, "s": 26831, "text": "Example 1:" }, { "code": null, "e": 26844, "s": 26842, "text": "R" }, { "code": "id<- c(1,2,3,4,5,6,7,8,9) country <- c(\"INDIA\",\"AMERICA\",\"JAPAN\",\"CHINA\",\"BANGLADESH\", \"SRILANKA\",\"NEPAL\",\"AMERICA\",\"CHINA\") data<-data.frame(id,country) unique(data$country)", "e": 27034, "s": 26844, "text": null }, { "code": null, "e": 27042, "s": 27034, "text": "Output:" }, { "code": null, "e": 27124, "s": 27042, "text": "[1] INDIA AMERICA JAPAN CHINA BANGLADESH SRILANKA NEPAL " }, { "code": null, "e": 27184, "s": 27124, "text": "Levels: AMERICA BANGLADESH CHINA INDIA JAPAN NEPAL SRILANKA" }, { "code": null, "e": 27196, "s": 27184, "text": "Example 2: " }, { "code": null, "e": 27198, "s": 27196, "text": "R" }, { "code": "data <- data.frame(x1 = c(9, 5, 6, 8, 9), x2 = c(2, 4, 2, 7, 1), x3 = c(3,6,7,0,3), x4 = c(\"Hello\", \"value\", \"value\", \"geeksforgeeks\", NA) ) unique(data[c(\"x2\")]) unique(data[c(\"x1\")])", "e": 27558, "s": 27198, "text": null }, { "code": null, "e": 27566, "s": 27558, "text": "Output:" }, { "code": null, "e": 27591, "s": 27566, "text": "Unique data in column x2" }, { "code": null, "e": 27596, "s": 27591, "text": " x2" }, { "code": null, "e": 27601, "s": 27596, "text": "1 2" }, { "code": null, "e": 27606, "s": 27601, "text": "2 4" }, { "code": null, "e": 27611, "s": 27606, "text": "4 7" }, { "code": null, "e": 27616, "s": 27611, "text": "5 1" }, { "code": null, "e": 27641, "s": 27616, "text": "Unique data in column x1" }, { "code": null, "e": 27646, "s": 27641, "text": " x1" }, { "code": null, "e": 27651, "s": 27646, "text": "1 9" }, { "code": null, "e": 27656, "s": 27651, "text": "2 5" }, { "code": null, "e": 27661, "s": 27656, "text": "3 6" }, { "code": null, "e": 27666, "s": 27661, "text": "4 8" }, { "code": null, "e": 27678, "s": 27666, "text": "Example 3: " }, { "code": null, "e": 27680, "s": 27678, "text": "R" }, { "code": "data<- data.frame(Student=c('John','Lee','Guy', 'John','Lee','Guy'), Age=c(18,19,20,18,19,20), Gender=c('Male','Female','Male', 'Male','Female','Male')) unique(data)", "e": 27975, "s": 27680, "text": null }, { "code": null, "e": 27983, "s": 27975, "text": "Output:" }, { "code": null, "e": 27990, "s": 27983, "text": "Picked" }, { "code": null, "e": 28011, "s": 27990, "text": "R DataFrame-Programs" }, { "code": null, "e": 28023, "s": 28011, "text": "R-DataFrame" }, { "code": null, "e": 28034, "s": 28023, "text": "R Language" }, { "code": null, "e": 28045, "s": 28034, "text": "R Programs" }, { "code": null, "e": 28143, "s": 28045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28195, "s": 28143, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28230, "s": 28195, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28268, "s": 28230, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28326, "s": 28268, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28369, "s": 28326, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28427, "s": 28369, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28470, "s": 28427, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28519, "s": 28470, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28569, "s": 28519, "text": "How to filter R dataframe by multiple conditions?" } ]
Count set bits in an integer - GeeksforGeeks
01 Mar, 2022 Write an efficient program to count the number of 1s in the binary representation of an integer. Examples : Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 13 is 1101 and has 3 set bits 1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is, then increment the set bit count. See the program below. C++ C Java Python3 C# PHP Javascript // C++ program to Count set// bits in an integer#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binaryrepresentation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; cout << countSetBits(i); return 0;} // This code is contributed// by Akanksha Rai // C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary representation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf("%d", countSetBits(i)); return 0;} // Java program to Count set// bits in an integerimport java.io.*; class countSetBits { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // driver program public static void main(String args[]) { int i = 9; System.out.println(countSetBits(i)); }} // This code is contributed by Anshika Goyal. # Python3 program to Count set# bits in an integer # Function to get no of set bits in binary# representation of positive integer n */def countSetBits(n): count = 0 while (n): count += n & 1 n >>= 1 return count # Program to test function countSetBits */i = 9print(countSetBits(i)) # This code is contributed by# Smitha Dinesh Semwal // C# program to Count set// bits in an integerusing System; class GFG { // Function to get no of set // bits in binary representation // of positive integer n static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Driver Code public static void Main() { int i = 9; Console.Write(countSetBits(i)); }} // This code is contributed by Sam007 <?php// PHP program to Count set// bits in an integer // Function to get no of set // bits in binary representation// of positive integer nfunction countSetBits($n){ $count = 0; while ($n) { $count += $n & 1; $n >>= 1; } return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed by ajit?> <script> // Javascript program to Count set // bits in an integer /* Function to get no of set bits in binary representation of positive integer n */ function countSetBits(n) { var count = 0; while (n) { count += n & 1; n >>= 1; } return count; } /* Program to test function countSetBits */ var i = 9; document.write(countSetBits(i)); // This code is contributed by noob2000. </script> Output : 2 Time Complexity: Θ(logn) (Theta of logn) Auxiliary Space: O(1) Recursive Approach: C++ Java Python3 C# PHP Javascript // cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj. // Java implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer nimport java.io.*; class GFG { // recursive function to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code public static void main(String[] args) { // get value from user int n = 9; // function calling System.out.println(countSetBits(n)); }} // This code is contributes by sunnysingh # Python3 implementation of recursive# approach to find the number of set# bits in binary representation of# positive integer n def countSetBits( n): # base case if (n == 0): return 0 else: # if last bit set add 1 else # add 0 return (n & 1) + countSetBits(n >> 1) # Get value from usern = 9 # Function callingprint( countSetBits(n)) # This code is contributed by sunnysingh // C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set // add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code static public void Main() { // get value // from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36 <?php// PHP implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer n // recursive function// to count set bitsfunction countSetBits($n){ // base case if ($n == 0) return 0; else // if last bit set // add 1 else add 0 return ($n & 1) + countSetBits($n >> 1);} // Driver code // get value from user$n = 9; // function callingecho countSetBits($n); // This code is contributed by m_kit.?> <script> // Javascript implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n // recursive function to count set bitsfunction countSetBits(n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver code // get value from user let n = 9; // function calling document.write(countSetBits(n)); // This code is contributed by Mayank Tyagi</script> Output : 2 Time Complexity: O(log n) Auxiliary Space: O(1) 2. Brian Kernighan’s Algorithm: Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit. for example : 10 in binary is 00001010 9 in binary is 00001001 8 in binary is 00001000 7 in binary is 00000111 So if we subtract a number by 1 and do it bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count. The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer. 1 Initialize count: = 0 2 If integer n is not zero (a) Do bitwise & with (n-1) and assign the value back to n n: = n&(n-1) (b) Increment count by 1 (c) go to step 2 3 Else return count Implementation of Brian Kernighan’s Algorithm: C++ C Java Python3 C# PHP Javascript // C++ program to Count set// bits in an integer#include <iostream>using namespace std;class gfg { /* Function to get no of set bits in binaryrepresentation of passed binary no. */public: unsigned int countSetBits(int n) { unsigned int count = 0; while (n) { n &= (n - 1); count++; } return count; }};/* Program to test function countSetBits */int main(){ gfg g; int i = 9; cout << g.countSetBits(i); return 0;} // C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary representation of passed binary no. */unsigned int countSetBits(int n){ unsigned int count = 0; while (n) { n &= (n - 1); count++; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf("%d", countSetBits(i)); getchar(); return 0;} // Java program to Count set// bits in an integerimport java.io.*; class countSetBits { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1); count++; } return count; } // driver program public static void main(String args[]) { int i = 9; System.out.println(countSetBits(i)); }} // This code is contributed by Anshika Goyal. # Function to get no of set bits in binary# representation of passed binary no. */def countSetBits(n): count = 0 while (n): n &= (n-1) count+= 1 return count # Program to test function countSetBitsi = 9print(countSetBits(i)) # This code is contributed by# Smitha Dinesh Semwal // C# program to Count set// bits in an integerusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1); count++; } return count; } // Driver Code static public void Main() { int i = 9; Console.WriteLine(countSetBits(i)); }} // This code is contributed by ajit <?php /* Function to get no ofset bits in binaryrepresentation of passedbinary no. */function countSetBits($n){ $count = 0; while ($n) { $n &= ($n - 1) ; $count++; } return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed// by akt_mit?> <script> // JavaScript program to Count set// bits in an integerclass /* Function to get no of setbits in binary representationof passed binary no. */ function countSetBits(n){ var count = 0; while (n > 0) { n &= (n - 1); count++; } return count;} // driver programvar i = 9;document.write(countSetBits(i)); // This code is contributed by 29AjayKumar </script> Output : 2 Example for Brian Kernighan’s Algorithm: n = 9 (1001) count = 0 Since 9 > 0, subtract by 1 and do bitwise & with (9-1) n = 9&8 (1001 & 1000) n = 8 count = 1 Since 8 > 0, subtract by 1 and do bitwise & with (8-1) n = 8&7 (1000 & 0111) n = 0 count = 2 Since n = 0, return count which is 2 now. Time Complexity: O(logn) Recursive Approach: C++ Java Python3 C# PHP Javascript // CPP implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1));} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj. // Java implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmimport java.io.*; class GFG { // recursive function to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1)); } // Driver function public static void main(String[] args) { // get value from user int n = 9; // function calling System.out.println(countSetBits(n)); }} // This code is contributed by sunnysingh # Python3 implementation for# recursive approach to find# the number of set bits using# Brian Kernighan’s Algorithm # recursive function to count# set bitsdef countSetBits(n): # base case if (n == 0): return 0 else: return 1 + countSetBits(n & (n - 1)) # Get value from usern = 9 # function callingprint(countSetBits(n)) # This code is contributed by sunnysingh // C# implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1)); } // Driver Code static public void Main() { // get value from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36 <?php// PHP implementation for// recursive approach to// find the number of set// bits using Brian// Kernighan’s Algorithm // recursive function to// count set bitsfunction countSetBits($n){ // base case if ($n == 0) return 0; else return 1 + countSetBits($n & ($n - 1));} // Driver Code // get value from user$n = 9; // function callingecho countSetBits($n); // This code is contributed by ajit.?> <script> // Javascript implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm // recursive function to count set bitsfunction countSetBits(n){ // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1));} // driver code// get value from user var n = 9;// function calling document.write(countSetBits(n)); </script> Output : 2 3. Using Lookup table: We can count bits in O(1) time using the lookup table.Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int BitsSetTable256[256]; // Function to initialise the lookup tablevoid initialize(){ // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; }} // Function to return the count// of set bits in nint countSetBits(int n){ return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]);} // Driver codeint main(){ // Initialise the lookup table initialize(); int n = 9; cout << countSetBits(n);} // This code is contributed by Sanjit_Kumar // Java implementation of the approachclass GFG { // Lookup table static int[] BitsSetTable256 = new int[256]; // Function to initialise the lookup table public static void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } // Driver code public static void main(String[] args) { // Initialise the lookup table initialize(); int n = 9; System.out.print(countSetBits(n)); }} # Python implementation of the approachBitsSetTable256 = [0] * 256 # Function to initialise the lookup tabledef initialize(): # To initially generate the # table algorithmically BitsSetTable256[0] = 0 for i in range(256): BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2] # Function to return the count# of set bits in ndef countSetBits(n): return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]) # Driver code # Initialise the lookup tableinitialize()n = 9print(countSetBits(n)) # This code is contributed by SHUBHAMSINGH10 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Lookup table static int[] BitsSetTable256 = new int[256]; // Function to initialise the lookup table public static void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } // Driver code public static void Main(String[] args) { // Initialise the lookup table initialize(); int n = 9; Console.Write(countSetBits(n)); }} // This code is contributed by 29AjayKumar <script> // javascript implementation of the approach var BitsSetTable256 = Array.from({length: 256}, (_, i) => 0); // Function to initialise the lookup tablefunction initialize(){ // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (var i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[parseInt(i / 2)]; }} // Function to return the count// of set bits in nfunction countSetBits(n){ return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]);} // Driver code // Initialise the lookup tableinitialize();var n = 9;document.write(countSetBits(n)); // This code is contributed by 29AjayKumar </script> 2 We can find one use of counting set bits at Count number of bits to be flipped to convert A to BNote: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. C++ Java Python3 C# PHP Javascript // C++ program to demonstrate __builtin_popcount()#include <iostream>using namespace std; int main(){ cout << __builtin_popcount(4) << endl; cout << __builtin_popcount(15); return 0;} // java program to demonstrate// __builtin_popcount() import java.io.*; class GFG { // Driver code public static void main(String[] args) { System.out.println(Integer.bitCount(4)); System.out.println(Integer.bitCount(15)); }} // This code is contributed by Raj # Python3 program to demonstrate __builtin_popcount() print(bin(4).count('1'));print(bin(15).count('1')); # This code is Contributed by mits // C# program to demonstrate// __builtin_popcount()using System;using System.Linq; class GFG { // Driver code public static void Main() { Console.WriteLine(Convert.ToString(4, 2).Count(c = > c == '1')); Console.WriteLine(Convert.ToString(15, 2).Count(c = > c == '1')); }} // This code is contributed by mits <?php// PHP program to demonstrate// __builtin_popcount() // Driver code$t = log10(4);$x = log(15, 2);$tt = ceil($t);$xx = ceil($x); echo ($tt), "\n";echo ($xx), "\n"; // This code is contributed// by jit_t?> <script> // Javascript program to demonstrate// __builtin_popcount() document.write((4).toString(2).split(''). filter(x => x == '1').length + "<br>");document.write((15).toString(2).split(''). filter(x => x == '1').length); </script> Output : 1 4 4. Mapping numbers with the bit. It simply maintains a map(or array) of numbers to bits for a nibble. A Nibble contains 4 bits. So we need an array of up to 15. int num_to_bits[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; Now we just need to get nibbles of a given long/int/word etc recursively. C++ C Java Python3 C# PHP Javascript // C++ program to count set bits by pre-storing// count set bits in nibbles.#include <bits/stdc++.h>using namespace std; int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */unsigned int countSetBitsRec(unsigned int num){ int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){ int num = 31; cout << countSetBitsRec(num); return 0;} // This code is contributed by rathbhupendra // C program to count set bits by pre-storing// count set bits in nibbles.#include <stdio.h> int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given number and map them in the array */unsigned int countSetBitsRec(unsigned int num){ int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){ int num = 31; printf("%d\n", countSetBitsRec(num));} // Java program to count set bits by pre-storing// count set bits in nibbles. class GFG { static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */ static int countSetBitsRec(int num) { int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); } // Driver code public static void main(String[] args) { int num = 31; System.out.println(countSetBitsRec(num)); }}// this code is contributed by mits # Python3 program to count set bits by pre-storing# count set bits in nibbles. num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; # Recursively get nibble of a given number# and map them in the arraydef countSetBitsRec(num): nibble = 0; if(0 == num): return num_to_bits[0]; # Find last nibble nibble = num & 0xf; # Use pre-stored values to find count # in last nibble plus recursively add # remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); # Driver code num = 31;print(countSetBitsRec(num)); # this code is contributed by mits // C# program to count set bits by pre-storing// count set bits in nibbles. class GFG { static int[] num_to_bits = new int[16] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */ static int countSetBitsRec(int num) { int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); } // Driver code static void Main() { int num = 31; System.Console.WriteLine(countSetBitsRec(num)); }}// this code is contributed by mits <?php// PHP program to count set bits by// pre-storing count set bits in nibbles. $num_to_bits = array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); /* Recursively get nibble of a givennumber and map them in the array */function countSetBitsRec( $num){ global $num_to_bits; $nibble = 0; if (0 == $num) return $num_to_bits[0]; // Find last nibble $nibble = $num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return $num_to_bits[$nibble] + countSetBitsRec($num >> 4);} // Driver code$num = 31;echo (countSetBitsRec($num)); // This code is contributed by mits?> <script> // Javascript program to count set bits by pre-storing// count set bits in nibbles. var num_to_bits =[ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ]; /* Recursively get nibble of a given numberand map them in the array */function countSetBitsRec(num){ var nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codevar num = 31;document.write(countSetBitsRec(num)); // This code is contributed by 29AjayKumar </script> Output : 5 Time Complexity: O(log n), because we have log(16, n) levels of recursion.Storage Complexity: O(1) Whether the given number is short, int, long, or long long we require an array of 16 sizes only, which is constant. 5. Checking each bit in a number: Each bit in the number is checked for whether it is set or not. The number is bitwise AND with powers of 2, so if the result is not equal to zero, we come to know that the particular bit in the position is set. C C++ Java Python3 C# Javascript #include <stdio.h> // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){ int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < sizeof(int) * 8; i++) { if (N & (1 << i)) count++; } return count;} // Driver Codeint main(){ int N = 15; printf("%d", countSetBits(N)); return 0;} #include <iostream>using namespace std; // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){ int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < sizeof(int) * 8; i++) { if (N & (1 << i)) count++; } return count;} int main(){ int N = 15; cout << countSetBits(N) << endl; return 0;} public class GFG{ // Check each bit in a number is set or not // and return the total count of the set bits. static int countSetBits(int N) { int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code public static void main(String[] args) { int N = 15; System.out.println(countSetBits(N)); }} // This code is contributed by divyeshrabadiya07. # Check each bit in a number is set or not# and return the total count of the set bitsdef countSetBits(N): count = 0 # (1 << i) = pow(2, i) for i in range(4*8): if(N & (1 << i)): count += 1 return count # Driver code N = 15 print(countSetBits(N)) # This code is contributed by avanitrachhadiya2155 using System;class GFG{ // Check each bit in a number is set or not // and return the total count of the set bits. static int countSetBits(int N) { int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code static void Main() { int N = 15; Console.WriteLine(countSetBits(N)); }} // This code is contributed by divyesh072019. <script> // Check each bit in a number is set or not // and return the total count of the set bits. function countSetBits(N) { var count = 0; // (1 << i) = pow(2, i) for (i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code var N = 15; document.write(countSetBits(N)); // This code is contributed by Amit Katiyar</script> 4 Count set bits in an integer Using Lookup Table Sam007 jit_t R_Raj NileshAwate BabisSarantoglou Mithun Kumar Akanksha_Rai SoumikMondal rathbhupendra likeicare Ankitkashyap Sanjit_Prasad SHUBHAMSINGH10 29AjayKumar paulsonraja divyeshrabadiya07 divyesh072019 avanitrachhadiya2155 rutvik_56 noob2000 mayanktyagi1709 amit143katiyar ytxmobile rishavmahato348 subham348 Adobe Brocade Cisco Juniper Networks Qualcomm Samsung setBitCount Wipro Bit Magic Samsung Adobe Wipro Brocade Juniper Networks Cisco Qualcomm Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Bit Fields in C Bits manipulation (Important tactics) Find the element that appears once Divide two integers without using multiplication, division and mod operator C++ bitset and its application 1's and 2's complement of a Binary Number Check whether K-th bit is set or not
[ { "code": null, "e": 26547, "s": 26519, "text": "\n01 Mar, 2022" }, { "code": null, "e": 26644, "s": 26547, "text": "Write an efficient program to count the number of 1s in the binary representation of an integer." }, { "code": null, "e": 26656, "s": 26644, "text": "Examples : " }, { "code": null, "e": 26816, "s": 26656, "text": "Input : n = 6\nOutput : 2\nBinary representation of 6 is 110 and has 2 set bits\n\nInput : n = 13\nOutput : 3\nBinary representation of 13 is 1101 and has 3 set bits" }, { "code": null, "e": 26968, "s": 26820, "text": "1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is, then increment the set bit count. See the program below. " }, { "code": null, "e": 26972, "s": 26968, "text": "C++" }, { "code": null, "e": 26974, "s": 26972, "text": "C" }, { "code": null, "e": 26979, "s": 26974, "text": "Java" }, { "code": null, "e": 26987, "s": 26979, "text": "Python3" }, { "code": null, "e": 26990, "s": 26987, "text": "C#" }, { "code": null, "e": 26994, "s": 26990, "text": "PHP" }, { "code": null, "e": 27005, "s": 26994, "text": "Javascript" }, { "code": "// C++ program to Count set// bits in an integer#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binaryrepresentation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; cout << countSetBits(i); return 0;} // This code is contributed// by Akanksha Rai", "e": 27484, "s": 27005, "text": null }, { "code": "// C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary representation of positive integer n */unsigned int countSetBits(unsigned int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf(\"%d\", countSetBits(i)); return 0;}", "e": 27898, "s": 27484, "text": null }, { "code": "// Java program to Count set// bits in an integerimport java.io.*; class countSetBits { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // driver program public static void main(String args[]) { int i = 9; System.out.println(countSetBits(i)); }} // This code is contributed by Anshika Goyal.", "e": 28428, "s": 27898, "text": null }, { "code": "# Python3 program to Count set# bits in an integer # Function to get no of set bits in binary# representation of positive integer n */def countSetBits(n): count = 0 while (n): count += n & 1 n >>= 1 return count # Program to test function countSetBits */i = 9print(countSetBits(i)) # This code is contributed by# Smitha Dinesh Semwal", "e": 28787, "s": 28428, "text": null }, { "code": "// C# program to Count set// bits in an integerusing System; class GFG { // Function to get no of set // bits in binary representation // of positive integer n static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Driver Code public static void Main() { int i = 9; Console.Write(countSetBits(i)); }} // This code is contributed by Sam007", "e": 29276, "s": 28787, "text": null }, { "code": "<?php// PHP program to Count set// bits in an integer // Function to get no of set // bits in binary representation// of positive integer nfunction countSetBits($n){ $count = 0; while ($n) { $count += $n & 1; $n >>= 1; } return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed by ajit?>", "e": 29624, "s": 29276, "text": null }, { "code": "<script> // Javascript program to Count set // bits in an integer /* Function to get no of set bits in binary representation of positive integer n */ function countSetBits(n) { var count = 0; while (n) { count += n & 1; n >>= 1; } return count; } /* Program to test function countSetBits */ var i = 9; document.write(countSetBits(i)); // This code is contributed by noob2000. </script>", "e": 30069, "s": 29624, "text": null }, { "code": null, "e": 30079, "s": 30069, "text": "Output : " }, { "code": null, "e": 30081, "s": 30079, "text": "2" }, { "code": null, "e": 30122, "s": 30081, "text": "Time Complexity: Θ(logn) (Theta of logn)" }, { "code": null, "e": 30144, "s": 30122, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30166, "s": 30144, "text": "Recursive Approach: " }, { "code": null, "e": 30170, "s": 30166, "text": "C++" }, { "code": null, "e": 30175, "s": 30170, "text": "Java" }, { "code": null, "e": 30183, "s": 30175, "text": "Python3" }, { "code": null, "e": 30186, "s": 30183, "text": "C#" }, { "code": null, "e": 30190, "s": 30186, "text": "PHP" }, { "code": null, "e": 30201, "s": 30190, "text": "Javascript" }, { "code": "// cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj.", "e": 30754, "s": 30201, "text": null }, { "code": "// Java implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer nimport java.io.*; class GFG { // recursive function to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code public static void main(String[] args) { // get value from user int n = 9; // function calling System.out.println(countSetBits(n)); }} // This code is contributes by sunnysingh", "e": 31414, "s": 30754, "text": null }, { "code": "# Python3 implementation of recursive# approach to find the number of set# bits in binary representation of# positive integer n def countSetBits( n): # base case if (n == 0): return 0 else: # if last bit set add 1 else # add 0 return (n & 1) + countSetBits(n >> 1) # Get value from usern = 9 # Function callingprint( countSetBits(n)) # This code is contributed by sunnysingh", "e": 31853, "s": 31414, "text": null }, { "code": "// C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set // add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code static public void Main() { // get value // from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36", "e": 32518, "s": 31853, "text": null }, { "code": "<?php// PHP implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer n // recursive function// to count set bitsfunction countSetBits($n){ // base case if ($n == 0) return 0; else // if last bit set // add 1 else add 0 return ($n & 1) + countSetBits($n >> 1);} // Driver code // get value from user$n = 9; // function callingecho countSetBits($n); // This code is contributed by m_kit.?>", "e": 33022, "s": 32518, "text": null }, { "code": "<script> // Javascript implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n // recursive function to count set bitsfunction countSetBits(n){ // base case if (n == 0) return 0; else // if last bit set add 1 else add 0 return (n & 1) + countSetBits(n >> 1);} // driver code // get value from user let n = 9; // function calling document.write(countSetBits(n)); // This code is contributed by Mayank Tyagi</script>", "e": 33550, "s": 33022, "text": null }, { "code": null, "e": 33560, "s": 33550, "text": "Output : " }, { "code": null, "e": 33562, "s": 33560, "text": "2" }, { "code": null, "e": 33588, "s": 33562, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 33610, "s": 33588, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 34210, "s": 33610, "text": "2. Brian Kernighan’s Algorithm: Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit. for example : 10 in binary is 00001010 9 in binary is 00001001 8 in binary is 00001000 7 in binary is 00000111 So if we subtract a number by 1 and do it bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count. The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer. " }, { "code": null, "e": 34435, "s": 34210, "text": " 1 Initialize count: = 0\n 2 If integer n is not zero\n (a) Do bitwise & with (n-1) and assign the value back to n\n n: = n&(n-1)\n (b) Increment count by 1\n (c) go to step 2\n 3 Else return count" }, { "code": null, "e": 34484, "s": 34435, "text": "Implementation of Brian Kernighan’s Algorithm: " }, { "code": null, "e": 34488, "s": 34484, "text": "C++" }, { "code": null, "e": 34490, "s": 34488, "text": "C" }, { "code": null, "e": 34495, "s": 34490, "text": "Java" }, { "code": null, "e": 34503, "s": 34495, "text": "Python3" }, { "code": null, "e": 34506, "s": 34503, "text": "C#" }, { "code": null, "e": 34510, "s": 34506, "text": "PHP" }, { "code": null, "e": 34521, "s": 34510, "text": "Javascript" }, { "code": "// C++ program to Count set// bits in an integer#include <iostream>using namespace std;class gfg { /* Function to get no of set bits in binaryrepresentation of passed binary no. */public: unsigned int countSetBits(int n) { unsigned int count = 0; while (n) { n &= (n - 1); count++; } return count; }};/* Program to test function countSetBits */int main(){ gfg g; int i = 9; cout << g.countSetBits(i); return 0;}", "e": 35007, "s": 34521, "text": null }, { "code": "// C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary representation of passed binary no. */unsigned int countSetBits(int n){ unsigned int count = 0; while (n) { n &= (n - 1); count++; } return count;} /* Program to test function countSetBits */int main(){ int i = 9; printf(\"%d\", countSetBits(i)); getchar(); return 0;}", "e": 35423, "s": 35007, "text": null }, { "code": "// Java program to Count set// bits in an integerimport java.io.*; class countSetBits { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1); count++; } return count; } // driver program public static void main(String args[]) { int i = 9; System.out.println(countSetBits(i)); }} // This code is contributed by Anshika Goyal.", "e": 35950, "s": 35423, "text": null }, { "code": "# Function to get no of set bits in binary# representation of passed binary no. */def countSetBits(n): count = 0 while (n): n &= (n-1) count+= 1 return count # Program to test function countSetBitsi = 9print(countSetBits(i)) # This code is contributed by# Smitha Dinesh Semwal", "e": 36258, "s": 35950, "text": null }, { "code": "// C# program to Count set// bits in an integerusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int n) { int count = 0; while (n > 0) { n &= (n - 1); count++; } return count; } // Driver Code static public void Main() { int i = 9; Console.WriteLine(countSetBits(i)); }} // This code is contributed by ajit", "e": 36744, "s": 36258, "text": null }, { "code": "<?php /* Function to get no ofset bits in binaryrepresentation of passedbinary no. */function countSetBits($n){ $count = 0; while ($n) { $n &= ($n - 1) ; $count++; } return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed// by akt_mit?>", "e": 37034, "s": 36744, "text": null }, { "code": "<script> // JavaScript program to Count set// bits in an integerclass /* Function to get no of setbits in binary representationof passed binary no. */ function countSetBits(n){ var count = 0; while (n > 0) { n &= (n - 1); count++; } return count;} // driver programvar i = 9;document.write(countSetBits(i)); // This code is contributed by 29AjayKumar </script>", "e": 37424, "s": 37034, "text": null }, { "code": null, "e": 37434, "s": 37424, "text": "Output : " }, { "code": null, "e": 37436, "s": 37434, "text": "2" }, { "code": null, "e": 37479, "s": 37436, "text": "Example for Brian Kernighan’s Algorithm: " }, { "code": null, "e": 37770, "s": 37479, "text": " n = 9 (1001)\n count = 0\n\n Since 9 > 0, subtract by 1 and do bitwise & with (9-1)\n n = 9&8 (1001 & 1000)\n n = 8\n count = 1\n\n Since 8 > 0, subtract by 1 and do bitwise & with (8-1)\n n = 8&7 (1000 & 0111)\n n = 0\n count = 2\n\n Since n = 0, return count which is 2 now." }, { "code": null, "e": 37795, "s": 37770, "text": "Time Complexity: O(logn)" }, { "code": null, "e": 37817, "s": 37795, "text": "Recursive Approach: " }, { "code": null, "e": 37821, "s": 37817, "text": "C++" }, { "code": null, "e": 37826, "s": 37821, "text": "Java" }, { "code": null, "e": 37834, "s": 37826, "text": "Python3" }, { "code": null, "e": 37837, "s": 37834, "text": "C#" }, { "code": null, "e": 37841, "s": 37837, "text": "PHP" }, { "code": null, "e": 37852, "s": 37841, "text": "Javascript" }, { "code": "// CPP implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){ // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1));} // driver codeint main(){ // get value from user int n = 9; // function calling cout << countSetBits(n); return 0;} // This code is contributed by Raj.", "e": 38345, "s": 37852, "text": null }, { "code": "// Java implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmimport java.io.*; class GFG { // recursive function to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1)); } // Driver function public static void main(String[] args) { // get value from user int n = 9; // function calling System.out.println(countSetBits(n)); }} // This code is contributed by sunnysingh", "e": 38943, "s": 38345, "text": null }, { "code": "# Python3 implementation for# recursive approach to find# the number of set bits using# Brian Kernighan’s Algorithm # recursive function to count# set bitsdef countSetBits(n): # base case if (n == 0): return 0 else: return 1 + countSetBits(n & (n - 1)) # Get value from usern = 9 # function callingprint(countSetBits(n)) # This code is contributed by sunnysingh", "e": 39358, "s": 38943, "text": null }, { "code": "// C# implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1)); } // Driver Code static public void Main() { // get value from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36", "e": 39933, "s": 39358, "text": null }, { "code": "<?php// PHP implementation for// recursive approach to// find the number of set// bits using Brian// Kernighan’s Algorithm // recursive function to// count set bitsfunction countSetBits($n){ // base case if ($n == 0) return 0; else return 1 + countSetBits($n & ($n - 1));} // Driver Code // get value from user$n = 9; // function callingecho countSetBits($n); // This code is contributed by ajit.?>", "e": 40389, "s": 39933, "text": null }, { "code": "<script> // Javascript implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm // recursive function to count set bitsfunction countSetBits(n){ // base case if (n == 0) return 0; else return 1 + countSetBits(n & (n - 1));} // driver code// get value from user var n = 9;// function calling document.write(countSetBits(n)); </script>", "e": 40796, "s": 40389, "text": null }, { "code": null, "e": 40806, "s": 40796, "text": "Output : " }, { "code": null, "e": 40808, "s": 40806, "text": "2" }, { "code": null, "e": 40936, "s": 40808, "text": "3. Using Lookup table: We can count bits in O(1) time using the lookup table.Below is the implementation of the above approach:" }, { "code": null, "e": 40940, "s": 40936, "text": "C++" }, { "code": null, "e": 40945, "s": 40940, "text": "Java" }, { "code": null, "e": 40952, "s": 40945, "text": "Python" }, { "code": null, "e": 40955, "s": 40952, "text": "C#" }, { "code": null, "e": 40966, "s": 40955, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int BitsSetTable256[256]; // Function to initialise the lookup tablevoid initialize(){ // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; }} // Function to return the count// of set bits in nint countSetBits(int n){ return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]);} // Driver codeint main(){ // Initialise the lookup table initialize(); int n = 9; cout << countSetBits(n);} // This code is contributed by Sanjit_Kumar", "e": 41746, "s": 40966, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Lookup table static int[] BitsSetTable256 = new int[256]; // Function to initialise the lookup table public static void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } // Driver code public static void main(String[] args) { // Initialise the lookup table initialize(); int n = 9; System.out.print(countSetBits(n)); }}", "e": 42658, "s": 41746, "text": null }, { "code": "# Python implementation of the approachBitsSetTable256 = [0] * 256 # Function to initialise the lookup tabledef initialize(): # To initially generate the # table algorithmically BitsSetTable256[0] = 0 for i in range(256): BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2] # Function to return the count# of set bits in ndef countSetBits(n): return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]) # Driver code # Initialise the lookup tableinitialize()n = 9print(countSetBits(n)) # This code is contributed by SHUBHAMSINGH10", "e": 43325, "s": 42658, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Lookup table static int[] BitsSetTable256 = new int[256]; // Function to initialise the lookup table public static void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n public static int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } // Driver code public static void Main(String[] args) { // Initialise the lookup table initialize(); int n = 9; Console.Write(countSetBits(n)); }} // This code is contributed by 29AjayKumar", "e": 44328, "s": 43325, "text": null }, { "code": "<script> // javascript implementation of the approach var BitsSetTable256 = Array.from({length: 256}, (_, i) => 0); // Function to initialise the lookup tablefunction initialize(){ // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (var i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[parseInt(i / 2)]; }} // Function to return the count// of set bits in nfunction countSetBits(n){ return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]);} // Driver code // Initialise the lookup tableinitialize();var n = 9;document.write(countSetBits(n)); // This code is contributed by 29AjayKumar </script>", "e": 45120, "s": 44328, "text": null }, { "code": null, "e": 45122, "s": 45120, "text": "2" }, { "code": null, "e": 45353, "s": 45124, "text": "We can find one use of counting set bits at Count number of bits to be flipped to convert A to BNote: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. " }, { "code": null, "e": 45357, "s": 45353, "text": "C++" }, { "code": null, "e": 45362, "s": 45357, "text": "Java" }, { "code": null, "e": 45370, "s": 45362, "text": "Python3" }, { "code": null, "e": 45373, "s": 45370, "text": "C#" }, { "code": null, "e": 45377, "s": 45373, "text": "PHP" }, { "code": null, "e": 45388, "s": 45377, "text": "Javascript" }, { "code": "// C++ program to demonstrate __builtin_popcount()#include <iostream>using namespace std; int main(){ cout << __builtin_popcount(4) << endl; cout << __builtin_popcount(15); return 0;}", "e": 45582, "s": 45388, "text": null }, { "code": "// java program to demonstrate// __builtin_popcount() import java.io.*; class GFG { // Driver code public static void main(String[] args) { System.out.println(Integer.bitCount(4)); System.out.println(Integer.bitCount(15)); }} // This code is contributed by Raj", "e": 45871, "s": 45582, "text": null }, { "code": "# Python3 program to demonstrate __builtin_popcount() print(bin(4).count('1'));print(bin(15).count('1')); # This code is Contributed by mits", "e": 46012, "s": 45871, "text": null }, { "code": "// C# program to demonstrate// __builtin_popcount()using System;using System.Linq; class GFG { // Driver code public static void Main() { Console.WriteLine(Convert.ToString(4, 2).Count(c = > c == '1')); Console.WriteLine(Convert.ToString(15, 2).Count(c = > c == '1')); }} // This code is contributed by mits", "e": 46348, "s": 46012, "text": null }, { "code": "<?php// PHP program to demonstrate// __builtin_popcount() // Driver code$t = log10(4);$x = log(15, 2);$tt = ceil($t);$xx = ceil($x); echo ($tt), \"\\n\";echo ($xx), \"\\n\"; // This code is contributed// by jit_t?>", "e": 46557, "s": 46348, "text": null }, { "code": "<script> // Javascript program to demonstrate// __builtin_popcount() document.write((4).toString(2).split(''). filter(x => x == '1').length + \"<br>\");document.write((15).toString(2).split(''). filter(x => x == '1').length); </script>", "e": 46793, "s": 46557, "text": null }, { "code": null, "e": 46803, "s": 46793, "text": "Output : " }, { "code": null, "e": 46807, "s": 46803, "text": "1\n4" }, { "code": null, "e": 47114, "s": 46807, "text": "4. Mapping numbers with the bit. It simply maintains a map(or array) of numbers to bits for a nibble. A Nibble contains 4 bits. So we need an array of up to 15. int num_to_bits[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; Now we just need to get nibbles of a given long/int/word etc recursively." }, { "code": null, "e": 47118, "s": 47114, "text": "C++" }, { "code": null, "e": 47120, "s": 47118, "text": "C" }, { "code": null, "e": 47125, "s": 47120, "text": "Java" }, { "code": null, "e": 47133, "s": 47125, "text": "Python3" }, { "code": null, "e": 47136, "s": 47133, "text": "C#" }, { "code": null, "e": 47140, "s": 47136, "text": "PHP" }, { "code": null, "e": 47151, "s": 47140, "text": "Javascript" }, { "code": "// C++ program to count set bits by pre-storing// count set bits in nibbles.#include <bits/stdc++.h>using namespace std; int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */unsigned int countSetBitsRec(unsigned int num){ int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){ int num = 31; cout << countSetBitsRec(num); return 0;} // This code is contributed by rathbhupendra", "e": 47906, "s": 47151, "text": null }, { "code": "// C program to count set bits by pre-storing// count set bits in nibbles.#include <stdio.h> int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given number and map them in the array */unsigned int countSetBitsRec(unsigned int num){ int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){ int num = 31; printf(\"%d\\n\", countSetBitsRec(num));}", "e": 48586, "s": 47906, "text": null }, { "code": "// Java program to count set bits by pre-storing// count set bits in nibbles. class GFG { static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */ static int countSetBitsRec(int num) { int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); } // Driver code public static void main(String[] args) { int num = 31; System.out.println(countSetBitsRec(num)); }}// this code is contributed by mits", "e": 49430, "s": 48586, "text": null }, { "code": "# Python3 program to count set bits by pre-storing# count set bits in nibbles. num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; # Recursively get nibble of a given number# and map them in the arraydef countSetBitsRec(num): nibble = 0; if(0 == num): return num_to_bits[0]; # Find last nibble nibble = num & 0xf; # Use pre-stored values to find count # in last nibble plus recursively add # remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); # Driver code num = 31;print(countSetBitsRec(num)); # this code is contributed by mits", "e": 50045, "s": 49430, "text": null }, { "code": "// C# program to count set bits by pre-storing// count set bits in nibbles. class GFG { static int[] num_to_bits = new int[16] { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */ static int countSetBitsRec(int num) { int nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4); } // Driver code static void Main() { int num = 31; System.Console.WriteLine(countSetBitsRec(num)); }}// this code is contributed by mits", "e": 50877, "s": 50045, "text": null }, { "code": "<?php// PHP program to count set bits by// pre-storing count set bits in nibbles. $num_to_bits = array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); /* Recursively get nibble of a givennumber and map them in the array */function countSetBitsRec( $num){ global $num_to_bits; $nibble = 0; if (0 == $num) return $num_to_bits[0]; // Find last nibble $nibble = $num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return $num_to_bits[$nibble] + countSetBitsRec($num >> 4);} // Driver code$num = 31;echo (countSetBitsRec($num)); // This code is contributed by mits?>", "e": 51574, "s": 50877, "text": null }, { "code": "<script> // Javascript program to count set bits by pre-storing// count set bits in nibbles. var num_to_bits =[ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ]; /* Recursively get nibble of a given numberand map them in the array */function countSetBitsRec(num){ var nibble = 0; if (0 == num) return num_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codevar num = 31;document.write(countSetBitsRec(num)); // This code is contributed by 29AjayKumar </script>", "e": 52258, "s": 51574, "text": null }, { "code": null, "e": 52268, "s": 52258, "text": "Output : " }, { "code": null, "e": 52270, "s": 52268, "text": "5" }, { "code": null, "e": 52485, "s": 52270, "text": "Time Complexity: O(log n), because we have log(16, n) levels of recursion.Storage Complexity: O(1) Whether the given number is short, int, long, or long long we require an array of 16 sizes only, which is constant." }, { "code": null, "e": 52520, "s": 52485, "text": "5. Checking each bit in a number: " }, { "code": null, "e": 52731, "s": 52520, "text": "Each bit in the number is checked for whether it is set or not. The number is bitwise AND with powers of 2, so if the result is not equal to zero, we come to know that the particular bit in the position is set." }, { "code": null, "e": 52733, "s": 52731, "text": "C" }, { "code": null, "e": 52737, "s": 52733, "text": "C++" }, { "code": null, "e": 52742, "s": 52737, "text": "Java" }, { "code": null, "e": 52750, "s": 52742, "text": "Python3" }, { "code": null, "e": 52753, "s": 52750, "text": "C#" }, { "code": null, "e": 52764, "s": 52753, "text": "Javascript" }, { "code": "#include <stdio.h> // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){ int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < sizeof(int) * 8; i++) { if (N & (1 << i)) count++; } return count;} // Driver Codeint main(){ int N = 15; printf(\"%d\", countSetBits(N)); return 0;}", "e": 53150, "s": 52764, "text": null }, { "code": "#include <iostream>using namespace std; // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){ int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < sizeof(int) * 8; i++) { if (N & (1 << i)) count++; } return count;} int main(){ int N = 15; cout << countSetBits(N) << endl; return 0;}", "e": 53543, "s": 53150, "text": null }, { "code": "public class GFG{ // Check each bit in a number is set or not // and return the total count of the set bits. static int countSetBits(int N) { int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code public static void main(String[] args) { int N = 15; System.out.println(countSetBits(N)); }} // This code is contributed by divyeshrabadiya07.", "e": 54017, "s": 53543, "text": null }, { "code": "# Check each bit in a number is set or not# and return the total count of the set bitsdef countSetBits(N): count = 0 # (1 << i) = pow(2, i) for i in range(4*8): if(N & (1 << i)): count += 1 return count # Driver code N = 15 print(countSetBits(N)) # This code is contributed by avanitrachhadiya2155", "e": 54346, "s": 54017, "text": null }, { "code": "using System;class GFG{ // Check each bit in a number is set or not // and return the total count of the set bits. static int countSetBits(int N) { int count = 0; // (1 << i) = pow(2, i) for (int i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code static void Main() { int N = 15; Console.WriteLine(countSetBits(N)); }} // This code is contributed by divyesh072019.", "e": 54800, "s": 54346, "text": null }, { "code": "<script> // Check each bit in a number is set or not // and return the total count of the set bits. function countSetBits(N) { var count = 0; // (1 << i) = pow(2, i) for (i = 0; i < 4 * 8; i++) { if ((N & (1 << i)) != 0) count++; } return count; } // Driver code var N = 15; document.write(countSetBits(N)); // This code is contributed by Amit Katiyar</script>", "e": 55207, "s": 54800, "text": null }, { "code": null, "e": 55209, "s": 55207, "text": "4" }, { "code": null, "e": 55257, "s": 55209, "text": "Count set bits in an integer Using Lookup Table" }, { "code": null, "e": 55266, "s": 55259, "text": "Sam007" }, { "code": null, "e": 55272, "s": 55266, "text": "jit_t" }, { "code": null, "e": 55278, "s": 55272, "text": "R_Raj" }, { "code": null, "e": 55290, "s": 55278, "text": "NileshAwate" }, { "code": null, "e": 55307, "s": 55290, "text": "BabisSarantoglou" }, { "code": null, "e": 55320, "s": 55307, "text": "Mithun Kumar" }, { "code": null, "e": 55333, "s": 55320, "text": "Akanksha_Rai" }, { "code": null, "e": 55346, "s": 55333, "text": "SoumikMondal" }, { "code": null, "e": 55360, "s": 55346, "text": "rathbhupendra" }, { "code": null, "e": 55370, "s": 55360, "text": "likeicare" }, { "code": null, "e": 55383, "s": 55370, "text": "Ankitkashyap" }, { "code": null, "e": 55397, "s": 55383, "text": "Sanjit_Prasad" }, { "code": null, "e": 55412, "s": 55397, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 55424, "s": 55412, "text": "29AjayKumar" }, { "code": null, "e": 55436, "s": 55424, "text": "paulsonraja" }, { "code": null, "e": 55454, "s": 55436, "text": "divyeshrabadiya07" }, { "code": null, "e": 55468, "s": 55454, "text": "divyesh072019" }, { "code": null, "e": 55489, "s": 55468, "text": "avanitrachhadiya2155" }, { "code": null, "e": 55499, "s": 55489, "text": "rutvik_56" }, { "code": null, "e": 55508, "s": 55499, "text": "noob2000" }, { "code": null, "e": 55524, "s": 55508, "text": "mayanktyagi1709" }, { "code": null, "e": 55539, "s": 55524, "text": "amit143katiyar" }, { "code": null, "e": 55549, "s": 55539, "text": "ytxmobile" }, { "code": null, "e": 55565, "s": 55549, "text": "rishavmahato348" }, { "code": null, "e": 55575, "s": 55565, "text": "subham348" }, { "code": null, "e": 55581, "s": 55575, "text": "Adobe" }, { "code": null, "e": 55589, "s": 55581, "text": "Brocade" }, { "code": null, "e": 55595, "s": 55589, "text": "Cisco" }, { "code": null, "e": 55612, "s": 55595, "text": "Juniper Networks" }, { "code": null, "e": 55621, "s": 55612, "text": "Qualcomm" }, { "code": null, "e": 55629, "s": 55621, "text": "Samsung" }, { "code": null, "e": 55641, "s": 55629, "text": "setBitCount" }, { "code": null, "e": 55647, "s": 55641, "text": "Wipro" }, { "code": null, "e": 55657, "s": 55647, "text": "Bit Magic" }, { "code": null, "e": 55665, "s": 55657, "text": "Samsung" }, { "code": null, "e": 55671, "s": 55665, "text": "Adobe" }, { "code": null, "e": 55677, "s": 55671, "text": "Wipro" }, { "code": null, "e": 55685, "s": 55677, "text": "Brocade" }, { "code": null, "e": 55702, "s": 55685, "text": "Juniper Networks" }, { "code": null, "e": 55708, "s": 55702, "text": "Cisco" }, { "code": null, "e": 55717, "s": 55708, "text": "Qualcomm" }, { "code": null, "e": 55727, "s": 55717, "text": "Bit Magic" }, { "code": null, "e": 55825, "s": 55727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55871, "s": 55825, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 55922, "s": 55871, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 55973, "s": 55922, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 55989, "s": 55973, "text": "Bit Fields in C" }, { "code": null, "e": 56027, "s": 55989, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 56062, "s": 56027, "text": "Find the element that appears once" }, { "code": null, "e": 56138, "s": 56062, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 56169, "s": 56138, "text": "C++ bitset and its application" }, { "code": null, "e": 56211, "s": 56169, "text": "1's and 2's complement of a Binary Number" } ]
Java Program to Print the Elements of an Array Present on Odd Position - GeeksforGeeks
27 Nov, 2020 An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are “N” elements, the array iteration starts from 0 and ends with “N-1”. The odd positions in the array are those with even indexing and vice versa. Example: Input : arr[] = { 10,20,30,40,50 } Output : 10 30 50 Input : arr1[] = { -5,0,2,5,76,9 } Output : -5 2 76 We will be printing elements at an odd position by two approaches: By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0), then print the elements.By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1. By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0), then print the elements. By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1. Approach 1: By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0 in the array), then print the elements. Java // Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int[] { 100, -500, 450, -200, 1000, -213, 750 }; System.out.println("Existing array elements .."); for (int i = 0; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( "Array elements at odd position.."); // Though the logic looks like taking even position, // if 10,20,30,40,50 are elements we need to get // 10,30,50. So followed the logic like this for (int i = 0; i < inputArray.length; i++) { if (i % 2 == 0) { System.out.println(inputArray[i]); } } }} Existing array elements .. 100 -500 450 -200 1000 -213 750 Array elements at odd position.. 100 450 1000 750 Time Complexity: O(n) Space Complexity: O(1) Approach 2: By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1. Java // Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int[] { 100, -500, 450, -200, 1000, -213, 750 }; System.out.println("Existing array elements .."); for (int i = 0; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( "Array elements at odd position.."); int flag = 1; for (int i = 0; i < inputArray.length; i++) { if (flag == 1) { System.out.print(inputArray[i] + " "); flag = 0; } else flag = 1; } }} Existing array elements .. 100 -500 450 -200 1000 -213 750 Array elements at odd position.. 100 450 1000 750 Time Complexity: O(n) Space Complexity: O(1) Java-Array-Programs Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 26677, "s": 26649, "text": "\n27 Nov, 2020" }, { "code": null, "e": 26900, "s": 26677, "text": "An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are “N” elements, the array iteration starts from 0 and ends with “N-1”." }, { "code": null, "e": 26976, "s": 26900, "text": "The odd positions in the array are those with even indexing and vice versa." }, { "code": null, "e": 26985, "s": 26976, "text": "Example:" }, { "code": null, "e": 27093, "s": 26985, "text": "Input : arr[] = { 10,20,30,40,50 }\nOutput : 10 30 50\n\nInput : arr1[] = { -5,0,2,5,76,9 }\nOutput : -5 2 76" }, { "code": null, "e": 27160, "s": 27093, "text": "We will be printing elements at an odd position by two approaches:" }, { "code": null, "e": 27482, "s": 27160, "text": "By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0), then print the elements.By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1." }, { "code": null, "e": 27603, "s": 27482, "text": "By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0), then print the elements." }, { "code": null, "e": 27805, "s": 27603, "text": "By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1." }, { "code": null, "e": 27818, "s": 27805, "text": "Approach 1: " }, { "code": null, "e": 27952, "s": 27818, "text": "By checking if the position is odd i.e divisible by 2 or not(since the indexing starts from 0 in the array), then print the elements." }, { "code": null, "e": 27957, "s": 27952, "text": "Java" }, { "code": "// Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int[] { 100, -500, 450, -200, 1000, -213, 750 }; System.out.println(\"Existing array elements ..\"); for (int i = 0; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( \"Array elements at odd position..\"); // Though the logic looks like taking even position, // if 10,20,30,40,50 are elements we need to get // 10,30,50. So followed the logic like this for (int i = 0; i < inputArray.length; i++) { if (i % 2 == 0) { System.out.println(inputArray[i]); } } }}", "e": 28889, "s": 27957, "text": null }, { "code": null, "e": 28998, "s": 28889, "text": "Existing array elements ..\n100\n-500\n450\n-200\n1000\n-213\n750\nArray elements at odd position..\n100\n450\n1000\n750" }, { "code": null, "e": 29020, "s": 28998, "text": "Time Complexity: O(n)" }, { "code": null, "e": 29043, "s": 29020, "text": "Space Complexity: O(1)" }, { "code": null, "e": 29056, "s": 29043, "text": "Approach 2: " }, { "code": null, "e": 29258, "s": 29056, "text": "By maintaining a flag pointer that will be initialized to 1 and start iterating over the array. If the flag is 1, print that element and change the flag to 0, else if the flag is 0, make the flag to 1." }, { "code": null, "e": 29263, "s": 29258, "text": "Java" }, { "code": "// Java program to print the elements at odd positions import java.util.*; public class PrintOddElementsInArray { public static void main(String[] args) { // Initialized array int inputArray[] = new int[] { 100, -500, 450, -200, 1000, -213, 750 }; System.out.println(\"Existing array elements ..\"); for (int i = 0; i < inputArray.length; i++) { System.out.println(inputArray[i]); } System.out.println( \"Array elements at odd position..\"); int flag = 1; for (int i = 0; i < inputArray.length; i++) { if (flag == 1) { System.out.print(inputArray[i] + \" \"); flag = 0; } else flag = 1; } }}", "e": 30113, "s": 29263, "text": null }, { "code": null, "e": 30222, "s": 30113, "text": "Existing array elements ..\n100\n-500\n450\n-200\n1000\n-213\n750\nArray elements at odd position..\n100 450 1000 750" }, { "code": null, "e": 30244, "s": 30222, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30267, "s": 30244, "text": "Space Complexity: O(1)" }, { "code": null, "e": 30287, "s": 30267, "text": "Java-Array-Programs" }, { "code": null, "e": 30294, "s": 30287, "text": "Picked" }, { "code": null, "e": 30318, "s": 30294, "text": "Technical Scripter 2020" }, { "code": null, "e": 30323, "s": 30318, "text": "Java" }, { "code": null, "e": 30337, "s": 30323, "text": "Java Programs" }, { "code": null, "e": 30356, "s": 30337, "text": "Technical Scripter" }, { "code": null, "e": 30361, "s": 30356, "text": "Java" }, { "code": null, "e": 30459, "s": 30361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30510, "s": 30459, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30540, "s": 30510, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30555, "s": 30540, "text": "Stream In Java" }, { "code": null, "e": 30574, "s": 30555, "text": "Interfaces in Java" }, { "code": null, "e": 30605, "s": 30574, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30633, "s": 30605, "text": "Initializing a List in Java" }, { "code": null, "e": 30677, "s": 30633, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 30703, "s": 30677, "text": "Java Programming Examples" }, { "code": null, "e": 30737, "s": 30703, "text": "Convert Double to Integer in Java" } ]
Direction of a Point from a Line Segment - GeeksforGeeks
24 Nov, 2021 Direction of given point P from a line segment simply means given the co-ordinates of a point P and line segment (say AB), and we have to determine the direction of point P from the line segment. That is whether the Point lies to the Right of Line Segment or to the Left of Line Segment. The point might lie behind the line segment, in that case we assume imaginary line by extending the line segment and determine the direction of point. * There are only three cases, either the point is on left side, or right side or on the line segment itself.This is a very fundamental Problem and is commonly encountered for directions in online map, Example : Suppose a user A has to go to Point C in the following map, the user first reaches point B but after that how does user A know that whether he has to make a right turn or left turn. Knowing the direction of a point from a line segment also acts a building block to solve more complicated problem such as : Line segment Intersection : finding if two line segment intersect Convex Hull of a set of Points. The co-ordinate system we’ll use is a cartesian plane, as most 2-Dimensional problem uses cartesian plane and since this is a 2-Dimensional Problem.This Problem can be solved using cross-product of vector algebra Cross-Product of two point A and B is : Ax * By – Ay * Bx where Ax and Ay are x and y co-ordinates of A respectively. Similarly Bx and By are x and y co-ordinates of B respectively. The Cross-Product has an interesting Property which will be used to determine direction of a point from a line segment. That is, the cross-product of two points is positive if and only if the angle of those point at origin (0, 0) is in counter-clockwise. And conversely the cross-product is negative if and only if the angle of those point at origin is in clockwise direction.An example would certainly clarify it, In the following figure, the angle BOP is anti-clockwise and the cross-product of B X P = 29*28 – 15*(-15) = 1037 which is positive. This helps us to make a conclusion that a point on right side must a have positive cross-product and a point on left side must have a negative cross product. Also note that we assumed one point of line segment to be origin and hence we need to convert any three point system such that one point of line segment is origin. Following example explains the concept : The three point A, B and P were converted into A’, B’ and P’ so as to make A as origin (this can be simply done by subtracting co-ordinates of A from point P and B), and then calculate the cross-product : 59*18 – (-25)*18 = 2187 Since this is positive, the Point P is on right side of line Segment AB. C++ Java Python3 C# Javascript // C++ Program to Determine Direction of Point// from line segment#include <iostream>using namespace std; // structure for point in cartesian plane.struct point { int x, y;}; // constant integers for directionsconst int RIGHT = 1, LEFT = -1, ZERO = 0; int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A from // B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codeint main(){ point A, B, P; A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) cout << "Right Direction" << endl; else if (direction == -1) cout << "Left Direction" << endl; else cout << "Point is on the Line" << endl; return 0;} // Java Program to Determine Direction of Point// from line segmentclass GFG { // structure for point in cartesian plane.static class point { int x, y;}; // constant integers for directionsstatic int RIGHT = 1, LEFT = -1, ZERO = 0; static int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codepublic static void main(String[] args) { point A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) System.out.println("Right Direction"); else if (direction == -1) System.out.println("Left Direction"); else System.out.println("Point is on the Line"); }} // This code is contributed// by Princi Singh # Python3 program to determine direction # of point from line segment # Structure for point in cartesian plane.class point: def __init__(self): self.x = 0 self.y = 0 # Constant integers for directionsRIGHT = 1LEFT = -1ZERO = 0 def directionOfPoint(A, B, P): global RIGHT, LEFT, ZERO # Subtracting co-ordinates of # point A from B and P, to # make A as origin B.x -= A.x B.y -= A.y P.x -= A.x P.y -= A.y # Determining cross Product cross_product = B.x * P.y - B.y * P.x # Return RIGHT if cross product is positive if (cross_product > 0): return RIGHT # Return LEFT if cross product is negative if (cross_product < 0): return LEFT # Return ZERO if cross product is zero return ZERO # Driver code if __name__=="__main__": A = point() B = point() P = point() A.x = -30 A.y = 10 # A(-30, 10) B.x = 29 B.y = -15 # B(29, -15) P.x = 15 P.y = 28 # P(15, 28) direction = directionOfPoint(A, B, P) if (direction == 1): print("Right Direction") elif (direction == -1): print("Left Direction") else: print("Point is on the Line") # This code is contributed by rutvik_56 // C# Program to Determine Direction of Point// from line segmentusing System;using System.Collections.Generic; class GFG { // structure for point in cartesian plane.public class point { public int x, y;}; // constant integers for directionsstatic int RIGHT = 1, LEFT = -1, ZERO = 0; static int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codepublic static void Main(String[] args) { point A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) Console.WriteLine("Right Direction"); else if (direction == -1) Console.WriteLine("Left Direction"); else Console.WriteLine("Point is on the Line"); }} // This code is contributed by 29AjayKumar <script> // JavaScript Program to Determine Direction of Point// from line segment // structure for point in cartesian plane.class point{ constructor() { this.x=0; this.y=0; }} // constant integers for directionslet RIGHT = 1, LEFT = -1, ZERO = 0; function directionOfPoint(A,B,P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product let cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO;} // Driver codelet A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) let direction = directionOfPoint(A, B, P); if (direction == 1) document.write("Right Direction<br>"); else if (direction == -1) document.write("Left Direction"); else document.write("Point is on the Line"); // This code is contributed by rag2127 </script> Output: Right Direction This article is contributed by Shubham Rana. 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. princi singh 29AjayKumar rutvik_56 rag2127 Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Optimum location of point to minimize total distance Check whether a given point lies inside a triangle or not Closest Pair of Points | O(nlogn) Implementation Given n line segments, find if any two segments intersect Polygon Clipping | Sutherland–Hodgman Algorithm Program for Point of Intersection of Two Lines Program to find area of a triangle Find K Closest Points to the Origin Window to Viewport Transformation in Computer Graphics with Implementation
[ { "code": null, "e": 26219, "s": 26191, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26508, "s": 26219, "text": "Direction of given point P from a line segment simply means given the co-ordinates of a point P and line segment (say AB), and we have to determine the direction of point P from the line segment. That is whether the Point lies to the Right of Line Segment or to the Left of Line Segment. " }, { "code": null, "e": 26660, "s": 26508, "text": "The point might lie behind the line segment, in that case we assume imaginary line by extending the line segment and determine the direction of point. " }, { "code": null, "e": 27055, "s": 26660, "text": "* There are only three cases, either the point is on left side, or right side or on the line segment itself.This is a very fundamental Problem and is commonly encountered for directions in online map, Example : Suppose a user A has to go to Point C in the following map, the user first reaches point B but after that how does user A know that whether he has to make a right turn or left turn. " }, { "code": null, "e": 27181, "s": 27055, "text": "Knowing the direction of a point from a line segment also acts a building block to solve more complicated problem such as : " }, { "code": null, "e": 27247, "s": 27181, "text": "Line segment Intersection : finding if two line segment intersect" }, { "code": null, "e": 27279, "s": 27247, "text": "Convex Hull of a set of Points." }, { "code": null, "e": 28223, "s": 27279, "text": "The co-ordinate system we’ll use is a cartesian plane, as most 2-Dimensional problem uses cartesian plane and since this is a 2-Dimensional Problem.This Problem can be solved using cross-product of vector algebra Cross-Product of two point A and B is : Ax * By – Ay * Bx where Ax and Ay are x and y co-ordinates of A respectively. Similarly Bx and By are x and y co-ordinates of B respectively. The Cross-Product has an interesting Property which will be used to determine direction of a point from a line segment. That is, the cross-product of two points is positive if and only if the angle of those point at origin (0, 0) is in counter-clockwise. And conversely the cross-product is negative if and only if the angle of those point at origin is in clockwise direction.An example would certainly clarify it, In the following figure, the angle BOP is anti-clockwise and the cross-product of B X P = 29*28 – 15*(-15) = 1037 which is positive. " }, { "code": null, "e": 28545, "s": 28223, "text": "This helps us to make a conclusion that a point on right side must a have positive cross-product and a point on left side must have a negative cross product. Also note that we assumed one point of line segment to be origin and hence we need to convert any three point system such that one point of line segment is origin." }, { "code": null, "e": 28889, "s": 28545, "text": "Following example explains the concept : The three point A, B and P were converted into A’, B’ and P’ so as to make A as origin (this can be simply done by subtracting co-ordinates of A from point P and B), and then calculate the cross-product : 59*18 – (-25)*18 = 2187 Since this is positive, the Point P is on right side of line Segment AB. " }, { "code": null, "e": 28893, "s": 28889, "text": "C++" }, { "code": null, "e": 28898, "s": 28893, "text": "Java" }, { "code": null, "e": 28906, "s": 28898, "text": "Python3" }, { "code": null, "e": 28909, "s": 28906, "text": "C#" }, { "code": null, "e": 28920, "s": 28909, "text": "Javascript" }, { "code": "// C++ Program to Determine Direction of Point// from line segment#include <iostream>using namespace std; // structure for point in cartesian plane.struct point { int x, y;}; // constant integers for directionsconst int RIGHT = 1, LEFT = -1, ZERO = 0; int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A from // B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codeint main(){ point A, B, P; A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) cout << \"Right Direction\" << endl; else if (direction == -1) cout << \"Left Direction\" << endl; else cout << \"Point is on the Line\" << endl; return 0;}", "e": 30124, "s": 28920, "text": null }, { "code": "// Java Program to Determine Direction of Point// from line segmentclass GFG { // structure for point in cartesian plane.static class point { int x, y;}; // constant integers for directionsstatic int RIGHT = 1, LEFT = -1, ZERO = 0; static int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codepublic static void main(String[] args) { point A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) System.out.println(\"Right Direction\"); else if (direction == -1) System.out.println(\"Left Direction\"); else System.out.println(\"Point is on the Line\"); }} // This code is contributed// by Princi Singh", "e": 31476, "s": 30124, "text": null }, { "code": "# Python3 program to determine direction # of point from line segment # Structure for point in cartesian plane.class point: def __init__(self): self.x = 0 self.y = 0 # Constant integers for directionsRIGHT = 1LEFT = -1ZERO = 0 def directionOfPoint(A, B, P): global RIGHT, LEFT, ZERO # Subtracting co-ordinates of # point A from B and P, to # make A as origin B.x -= A.x B.y -= A.y P.x -= A.x P.y -= A.y # Determining cross Product cross_product = B.x * P.y - B.y * P.x # Return RIGHT if cross product is positive if (cross_product > 0): return RIGHT # Return LEFT if cross product is negative if (cross_product < 0): return LEFT # Return ZERO if cross product is zero return ZERO # Driver code if __name__==\"__main__\": A = point() B = point() P = point() A.x = -30 A.y = 10 # A(-30, 10) B.x = 29 B.y = -15 # B(29, -15) P.x = 15 P.y = 28 # P(15, 28) direction = directionOfPoint(A, B, P) if (direction == 1): print(\"Right Direction\") elif (direction == -1): print(\"Left Direction\") else: print(\"Point is on the Line\") # This code is contributed by rutvik_56", "e": 32750, "s": 31476, "text": null }, { "code": "// C# Program to Determine Direction of Point// from line segmentusing System;using System.Collections.Generic; class GFG { // structure for point in cartesian plane.public class point { public int x, y;}; // constant integers for directionsstatic int RIGHT = 1, LEFT = -1, ZERO = 0; static int directionOfPoint(point A, point B, point P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product int cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO; } // Driver codepublic static void Main(String[] args) { point A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) int direction = directionOfPoint(A, B, P); if (direction == 1) Console.WriteLine(\"Right Direction\"); else if (direction == -1) Console.WriteLine(\"Left Direction\"); else Console.WriteLine(\"Point is on the Line\"); }} // This code is contributed by 29AjayKumar", "e": 34158, "s": 32750, "text": null }, { "code": "<script> // JavaScript Program to Determine Direction of Point// from line segment // structure for point in cartesian plane.class point{ constructor() { this.x=0; this.y=0; }} // constant integers for directionslet RIGHT = 1, LEFT = -1, ZERO = 0; function directionOfPoint(A,B,P){ // subtracting co-ordinates of point A // from B and P, to make A as origin B.x -= A.x; B.y -= A.y; P.x -= A.x; P.y -= A.y; // Determining cross Product let cross_product = B.x * P.y - B.y * P.x; // return RIGHT if cross product is positive if (cross_product > 0) return RIGHT; // return LEFT if cross product is negative if (cross_product < 0) return LEFT; // return ZERO if cross product is zero. return ZERO;} // Driver codelet A = new point(), B = new point(), P = new point(); A.x = -30; A.y = 10; // A(-30, 10) B.x = 29; B.y = -15; // B(29, -15) P.x = 15; P.y = 28; // P(15, 28) let direction = directionOfPoint(A, B, P); if (direction == 1) document.write(\"Right Direction<br>\"); else if (direction == -1) document.write(\"Left Direction\"); else document.write(\"Point is on the Line\"); // This code is contributed by rag2127 </script>", "e": 35444, "s": 34158, "text": null }, { "code": null, "e": 35453, "s": 35444, "text": "Output: " }, { "code": null, "e": 35469, "s": 35453, "text": "Right Direction" }, { "code": null, "e": 35890, "s": 35469, "text": "This article is contributed by Shubham Rana. 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": 35903, "s": 35890, "text": "princi singh" }, { "code": null, "e": 35915, "s": 35903, "text": "29AjayKumar" }, { "code": null, "e": 35925, "s": 35915, "text": "rutvik_56" }, { "code": null, "e": 35933, "s": 35925, "text": "rag2127" }, { "code": null, "e": 35943, "s": 35933, "text": "Geometric" }, { "code": null, "e": 35953, "s": 35943, "text": "Geometric" }, { "code": null, "e": 36051, "s": 35953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36102, "s": 36051, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 36155, "s": 36102, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 36213, "s": 36155, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 36262, "s": 36213, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 36320, "s": 36262, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 36368, "s": 36320, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 36415, "s": 36368, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 36450, "s": 36415, "text": "Program to find area of a triangle" }, { "code": null, "e": 36486, "s": 36450, "text": "Find K Closest Points to the Origin" } ]
Print Binary Tree in 2-Dimensions - GeeksforGeeks
14 Dec, 2021 Given a Binary Tree, print it in two dimension.Examples: Input : Pointer to root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 3 6 1 5 2 4 We strongly recommend you to minimize your browser and try this yourself first.If we take a closer look at the pattern, we can notice following. 1) Rightmost node is printed in first line and leftmost node is printed in last line. 2) Space count increases by a fixed amount at every level.So we do a reverse inorder traversal (right – root – left) and print tree nodes. We increase space by a fixed amount at every level.Below is the implementation. C++ C Java Python3 C# Javascript // C++ Program to print binary tree in 2D#include<bits/stdc++.h> using namespace std;#define COUNT 10 // A binary tree nodeclass Node{ public: int data; Node* left, *right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ Node(int data){ this->data = data; this->left = NULL; this->right = NULL; }}; // Function to print binary tree in 2D// It does reverse inorder traversalvoid print2DUtil(Node *root, int space){ // Base case if (root == NULL) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root->right, space); // Print current node after space // count cout<<endl; for (int i = COUNT; i < space; i++) cout<<" "; cout<<root->data<<"\n"; // Process left child print2DUtil(root->left, space);} // Wrapper over print2DUtil()void print2D(Node *root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codeint main(){ Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); root->left->left->left = new Node(8); root->left->left->right = new Node(9); root->left->right->left = new Node(10); root->left->right->right = new Node(11); root->right->left->left = new Node(12); root->right->left->right = new Node(13); root->right->right->left = new Node(14); root->right->right->right = new Node(15); print2D(root); return 0;} // This code is contributed by rathbhupendra // Program to print binary tree in 2D#include<stdio.h>#include<malloc.h>#define COUNT 10 // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // Helper function to allocates a new nodestruct Node* newNode(int data){ struct Node* node = malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Function to print binary tree in 2D// It does reverse inorder traversalvoid print2DUtil(struct Node *root, int space){ // Base case if (root == NULL) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root->right, space); // Print current node after space // count printf("\n"); for (int i = COUNT; i < space; i++) printf(" "); printf("%d\n", root->data); // Process left child print2DUtil(root->left, space);} // Wrapper over print2DUtil()void print2D(struct Node *root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); print2D(root); return 0;} // Java Program to print binary tree in 2Dclass GFG{ static final int COUNT = 10; // A binary tree nodestatic class Node{ int data; Node left, right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print binary tree in 2D// It does reverse inorder traversalstatic void print2DUtil(Node root, int space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count System.out.print("\n"); for (int i = COUNT; i < space; i++) System.out.print(" "); System.out.print(root.data + "\n"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()static void print2D(Node root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codepublic static void main(String args[]){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.left.left.right = new Node(9); root.left.right.left = new Node(10); root.left.right.right = new Node(11); root.right.left.left = new Node(12); root.right.left.right = new Node(13); root.right.right.left = new Node(14); root.right.right.right = new Node(15); print2D(root);}} // This code is contributed by Arnab Kundu # Python3 Program to print binary tree in 2DCOUNT = [10] # Binary Tree Node""" utility that allocates a newNodewith the given key """class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # Function to print binary tree in 2D# It does reverse inorder traversaldef print2DUtil(root, space) : # Base case if (root == None) : return # Increase distance between levels space += COUNT[0] # Process right child first print2DUtil(root.right, space) # Print current node after space # count print() for i in range(COUNT[0], space): print(end = " ") print(root.data) # Process left child print2DUtil(root.left, space) # Wrapper over print2DUtil()def print2D(root) : # space=[0] # Pass initial space count as 0 print2DUtil(root, 0) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.left.left.right = newNode(9) root.left.right.left = newNode(10) root.left.right.right = newNode(11) root.right.left.left = newNode(12) root.right.left.right = newNode(13) root.right.right.left = newNode(14) root.right.right.right = newNode(15) print2D(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# Program to print binary tree in 2Dusing System; class GFG{ static readonly int COUNT = 10; // A binary tree nodepublic class Node{ public int data; public Node left, right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print binary tree in 2D// It does reverse inorder traversalstatic void print2DUtil(Node root, int space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count Console.Write("\n"); for (int i = COUNT; i < space; i++) Console.Write(" "); Console.Write(root.data + "\n"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()static void print2D(Node root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codepublic static void Main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.left.left.right = new Node(9); root.left.right.left = new Node(10); root.left.right.right = new Node(11); root.right.left.left = new Node(12); root.right.left.right = new Node(13); root.right.right.left = new Node(14); root.right.right.right = new Node(15); print2D(root);}} // This code is contributed by Princi Singh <script> // JavaScript Program to print binary tree in 2D let COUNT = 10; // A binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Function to print binary tree in 2D// It does reverse inorder traversalfunction print2DUtil(root,space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count document.write("<br>"); for (let i = COUNT; i < space; i++) document.write(" "); document.write(root.data + "\n"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()function print2D(root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3); root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);root.right.right.right = new Node(15); print2D(root); // This code is contributed by patel2127 </script> Output: 15 7 14 3 13 6 12 1 11 5 10 2 9 4 8 Another solution using level order traversal: Java import java.util.LinkedList; public class Tree1 { public static void main(String[] args) { Tree1.Node root = new Tree1.Node(1); Tree1.Node temp = null; temp = new Tree1.Node(2); root.left=temp; temp = new Tree1.Node(3); root.right=temp; temp = new Tree1.Node(4); root.left.left = temp; temp=new Tree1.Node(5); root.left.right =temp; temp=new Tree1.Node(6); root.right.left =temp; temp=new Tree1.Node(7); root.right.right = temp; temp = new Tree1.Node(8); root.left.left.left = temp; temp = new Tree1.Node(9); root.left.left.right = temp; temp=new Tree1.Node(10); root.left.right.left = temp; temp=new Tree1.Node(11); root.left.right.right = temp; temp=new Tree1.Node(12); root.right.left.left = temp; temp=new Tree1.Node(13); root.right.left.right = temp; temp=new Tree1.Node(14); root.right.right.left = temp; temp=new Tree1.Node(15); root.right.right.right = temp; printBinaryTree(root); } public static class Node{ public Node(int data){ this.data = data; } int data; Node left; Node right;} public static void printBinaryTree(Node root) { LinkedList<Node> treeLevel = new LinkedList<Node>(); treeLevel.add(root); LinkedList<Node> temp = new LinkedList<Node>(); int counter = 0; int height = heightOfTree(root)-1; //System.out.println(height); double numberOfElements = (Math.pow(2 , (height + 1)) - 1); //System.out.println(numberOfElements); while (counter <= height) { Node removed = treeLevel.removeFirst(); if (temp.isEmpty()) { printSpace(numberOfElements / Math.pow(2 , counter + 1), removed); } else { printSpace(numberOfElements / Math.pow(2 , counter), removed); } if (removed == null) { temp.add(null); temp.add(null); } else { temp.add(removed.left); temp.add(removed.right); } if (treeLevel.isEmpty()) { System.out.println(""); System.out.println(""); treeLevel = temp; temp = new LinkedList<>(); counter++; } } } public static void printSpace(double n, Node removed){ for(;n>0;n--) { System.out.print("\t"); } if(removed == null){ System.out.print(" "); } else { System.out.print(removed.data); }} public static int heightOfTree(Node root){ if(root==null){ return 0; } return 1+ Math.max(heightOfTree(root.left),heightOfTree(root.right));} } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Output: YouTubeGeeksforGeeks507K subscribersPrint Binary Tree in 2-Dimensions | 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 / 4:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=eY3SZLGCK2E" 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 Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 rathbhupendra andrew1234 princi singh SnehanjanChatterjee avanitrachhadiya2155 rishabsrivastava Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree Binary Tree (Array implementation) BFS vs DFS for Binary Tree AVL Tree | Set 2 (Deletion) Insertion in a Binary Tree in level order
[ { "code": null, "e": 26217, "s": 26189, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26276, "s": 26217, "text": "Given a Binary Tree, print it in two dimension.Examples: " }, { "code": null, "e": 26537, "s": 26276, "text": "Input : Pointer to root of below tree\n 1\n / \\\n 2 3 \n / \\ / \\\n 4 5 6 7 \n\nOutput :\n 7\n\n 3\n\n 6\n\n1\n\n 5\n\n 2\n\n 4" }, { "code": null, "e": 26989, "s": 26537, "text": "We strongly recommend you to minimize your browser and try this yourself first.If we take a closer look at the pattern, we can notice following. 1) Rightmost node is printed in first line and leftmost node is printed in last line. 2) Space count increases by a fixed amount at every level.So we do a reverse inorder traversal (right – root – left) and print tree nodes. We increase space by a fixed amount at every level.Below is the implementation. " }, { "code": null, "e": 26993, "s": 26989, "text": "C++" }, { "code": null, "e": 26995, "s": 26993, "text": "C" }, { "code": null, "e": 27000, "s": 26995, "text": "Java" }, { "code": null, "e": 27008, "s": 27000, "text": "Python3" }, { "code": null, "e": 27011, "s": 27008, "text": "C#" }, { "code": null, "e": 27022, "s": 27011, "text": "Javascript" }, { "code": "// C++ Program to print binary tree in 2D#include<bits/stdc++.h> using namespace std;#define COUNT 10 // A binary tree nodeclass Node{ public: int data; Node* left, *right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ Node(int data){ this->data = data; this->left = NULL; this->right = NULL; }}; // Function to print binary tree in 2D// It does reverse inorder traversalvoid print2DUtil(Node *root, int space){ // Base case if (root == NULL) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root->right, space); // Print current node after space // count cout<<endl; for (int i = COUNT; i < space; i++) cout<<\" \"; cout<<root->data<<\"\\n\"; // Process left child print2DUtil(root->left, space);} // Wrapper over print2DUtil()void print2D(Node *root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codeint main(){ Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); root->left->left->left = new Node(8); root->left->left->right = new Node(9); root->left->right->left = new Node(10); root->left->right->right = new Node(11); root->right->left->left = new Node(12); root->right->left->right = new Node(13); root->right->right->left = new Node(14); root->right->right->right = new Node(15); print2D(root); return 0;} // This code is contributed by rathbhupendra", "e": 28730, "s": 27022, "text": null }, { "code": "// Program to print binary tree in 2D#include<stdio.h>#include<malloc.h>#define COUNT 10 // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // Helper function to allocates a new nodestruct Node* newNode(int data){ struct Node* node = malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Function to print binary tree in 2D// It does reverse inorder traversalvoid print2DUtil(struct Node *root, int space){ // Base case if (root == NULL) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root->right, space); // Print current node after space // count printf(\"\\n\"); for (int i = COUNT; i < space; i++) printf(\" \"); printf(\"%d\\n\", root->data); // Process left child print2DUtil(root->left, space);} // Wrapper over print2DUtil()void print2D(struct Node *root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); print2D(root); return 0;}", "e": 30420, "s": 28730, "text": null }, { "code": "// Java Program to print binary tree in 2Dclass GFG{ static final int COUNT = 10; // A binary tree nodestatic class Node{ int data; Node left, right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print binary tree in 2D// It does reverse inorder traversalstatic void print2DUtil(Node root, int space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count System.out.print(\"\\n\"); for (int i = COUNT; i < space; i++) System.out.print(\" \"); System.out.print(root.data + \"\\n\"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()static void print2D(Node root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codepublic static void main(String args[]){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.left.left.right = new Node(9); root.left.right.left = new Node(10); root.left.right.right = new Node(11); root.right.left.left = new Node(12); root.right.left.right = new Node(13); root.right.right.left = new Node(14); root.right.right.right = new Node(15); print2D(root);}} // This code is contributed by Arnab Kundu", "e": 32131, "s": 30420, "text": null }, { "code": "# Python3 Program to print binary tree in 2DCOUNT = [10] # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\"class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # Function to print binary tree in 2D# It does reverse inorder traversaldef print2DUtil(root, space) : # Base case if (root == None) : return # Increase distance between levels space += COUNT[0] # Process right child first print2DUtil(root.right, space) # Print current node after space # count print() for i in range(COUNT[0], space): print(end = \" \") print(root.data) # Process left child print2DUtil(root.left, space) # Wrapper over print2DUtil()def print2D(root) : # space=[0] # Pass initial space count as 0 print2DUtil(root, 0) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.left.left.right = newNode(9) root.left.right.left = newNode(10) root.left.right.right = newNode(11) root.right.left.left = newNode(12) root.right.left.right = newNode(13) root.right.right.left = newNode(14) root.right.right.right = newNode(15) print2D(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 33655, "s": 32131, "text": null }, { "code": "// C# Program to print binary tree in 2Dusing System; class GFG{ static readonly int COUNT = 10; // A binary tree nodepublic class Node{ public int data; public Node left, right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print binary tree in 2D// It does reverse inorder traversalstatic void print2DUtil(Node root, int space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count Console.Write(\"\\n\"); for (int i = COUNT; i < space; i++) Console.Write(\" \"); Console.Write(root.data + \"\\n\"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()static void print2D(Node root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codepublic static void Main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.left.left.right = new Node(9); root.left.right.left = new Node(10); root.left.right.right = new Node(11); root.right.left.left = new Node(12); root.right.left.right = new Node(13); root.right.right.left = new Node(14); root.right.right.right = new Node(15); print2D(root);}} // This code is contributed by Princi Singh", "e": 35394, "s": 33655, "text": null }, { "code": "<script> // JavaScript Program to print binary tree in 2D let COUNT = 10; // A binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Function to print binary tree in 2D// It does reverse inorder traversalfunction print2DUtil(root,space){ // Base case if (root == null) return; // Increase distance between levels space += COUNT; // Process right child first print2DUtil(root.right, space); // Print current node after space // count document.write(\"<br>\"); for (let i = COUNT; i < space; i++) document.write(\" \"); document.write(root.data + \"\\n\"); // Process left child print2DUtil(root.left, space);} // Wrapper over print2DUtil()function print2D(root){ // Pass initial space count as 0 print2DUtil(root, 0);} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3); root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);root.right.right.right = new Node(15); print2D(root); // This code is contributed by patel2127 </script>", "e": 36829, "s": 35394, "text": null }, { "code": null, "e": 36838, "s": 36829, "text": "Output: " }, { "code": null, "e": 37228, "s": 36838, "text": " 15\n\n 7\n\n 14\n\n 3\n\n 13\n\n 6\n\n 12\n\n1\n\n 11\n\n 5\n\n 10\n\n 2\n\n 9\n\n 4\n\n 8" }, { "code": null, "e": 37274, "s": 37228, "text": "Another solution using level order traversal:" }, { "code": null, "e": 37279, "s": 37274, "text": "Java" }, { "code": "import java.util.LinkedList; public class Tree1 { public static void main(String[] args) { Tree1.Node root = new Tree1.Node(1); Tree1.Node temp = null; temp = new Tree1.Node(2); root.left=temp; temp = new Tree1.Node(3); root.right=temp; temp = new Tree1.Node(4); root.left.left = temp; temp=new Tree1.Node(5); root.left.right =temp; temp=new Tree1.Node(6); root.right.left =temp; temp=new Tree1.Node(7); root.right.right = temp; temp = new Tree1.Node(8); root.left.left.left = temp; temp = new Tree1.Node(9); root.left.left.right = temp; temp=new Tree1.Node(10); root.left.right.left = temp; temp=new Tree1.Node(11); root.left.right.right = temp; temp=new Tree1.Node(12); root.right.left.left = temp; temp=new Tree1.Node(13); root.right.left.right = temp; temp=new Tree1.Node(14); root.right.right.left = temp; temp=new Tree1.Node(15); root.right.right.right = temp; printBinaryTree(root); } public static class Node{ public Node(int data){ this.data = data; } int data; Node left; Node right;} public static void printBinaryTree(Node root) { LinkedList<Node> treeLevel = new LinkedList<Node>(); treeLevel.add(root); LinkedList<Node> temp = new LinkedList<Node>(); int counter = 0; int height = heightOfTree(root)-1; //System.out.println(height); double numberOfElements = (Math.pow(2 , (height + 1)) - 1); //System.out.println(numberOfElements); while (counter <= height) { Node removed = treeLevel.removeFirst(); if (temp.isEmpty()) { printSpace(numberOfElements / Math.pow(2 , counter + 1), removed); } else { printSpace(numberOfElements / Math.pow(2 , counter), removed); } if (removed == null) { temp.add(null); temp.add(null); } else { temp.add(removed.left); temp.add(removed.right); } if (treeLevel.isEmpty()) { System.out.println(\"\"); System.out.println(\"\"); treeLevel = temp; temp = new LinkedList<>(); counter++; } } } public static void printSpace(double n, Node removed){ for(;n>0;n--) { System.out.print(\"\\t\"); } if(removed == null){ System.out.print(\" \"); } else { System.out.print(removed.data); }} public static int heightOfTree(Node root){ if(root==null){ return 0; } return 1+ Math.max(heightOfTree(root.left),heightOfTree(root.right));} }", "e": 40093, "s": 37279, "text": null }, { "code": null, "e": 40317, "s": 40093, "text": " 1\n\n 2 3\n\n 4 5 6 7\n\n 8 9 10 11 12 13 14 15" }, { "code": null, "e": 40326, "s": 40317, "text": " Output:" }, { "code": null, "e": 41158, "s": 40326, "text": "YouTubeGeeksforGeeks507K subscribersPrint Binary Tree in 2-Dimensions | 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 / 4:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=eY3SZLGCK2E\" 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": 41548, "s": 41158, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 41563, "s": 41548, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 41577, "s": 41563, "text": "rathbhupendra" }, { "code": null, "e": 41588, "s": 41577, "text": "andrew1234" }, { "code": null, "e": 41601, "s": 41588, "text": "princi singh" }, { "code": null, "e": 41621, "s": 41601, "text": "SnehanjanChatterjee" }, { "code": null, "e": 41642, "s": 41621, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41659, "s": 41642, "text": "rishabsrivastava" }, { "code": null, "e": 41664, "s": 41659, "text": "Tree" }, { "code": null, "e": 41669, "s": 41664, "text": "Tree" }, { "code": null, "e": 41767, "s": 41669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41781, "s": 41767, "text": "Decision Tree" }, { "code": null, "e": 41817, "s": 41781, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41865, "s": 41817, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 41948, "s": 41865, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 41964, "s": 41948, "text": "Expression Tree" }, { "code": null, "e": 41990, "s": 41964, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 42025, "s": 41990, "text": "Binary Tree (Array implementation)" }, { "code": null, "e": 42052, "s": 42025, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 42080, "s": 42052, "text": "AVL Tree | Set 2 (Deletion)" } ]
JQuery deferred.then() method - GeeksforGeeks
16 Jul, 2020 This deferred.then() method in JQuery is used to add handlers which are to be called when the Deferred object is resolved, rejected, or in progress. Syntax: deferred.then(doneCallbacks[, failCallbacks][, progressCallbacks]) Parameters: doneCallbacks: This is a function, or an array of functions, which is called when the Deferred is resolved. failCallbacks: This is a function, or an array of functions, which is called when the Deferred is rejected. progressCallbacks: This is a function, or an array of functions, which is called when progress notifications are being sent to the Deferred object. Return Value: This method method returns the deferred object. There are two examples discussed below: Example: In this example, the then() method is called with notify and resolve method.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.then() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>' , '#GFG_DOWN'); def.resolve('Deferred "def" is resolved.<br/>' , '#GFG_DOWN'); } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.then() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>' , '#GFG_DOWN'); def.resolve('Deferred "def" is resolved.<br/>' , '#GFG_DOWN'); } </script> </body> </html> Output: Example: In this example, the then() method is called with notify and reject method.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.then() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>', '#GFG_DOWN'); def.reject('Deferred "def" is rejected.<br/>', '#GFG_DOWN'); } </script> </body> </html> Example: In this example, the then() method is called with notify and reject method. <!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick = "Geeks();"> click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); el_up.innerHTML = "JQuery | deferred.then() method"; function Func1(val, div){ $(div).append("From doneCallbacks - " + val); } function Func2(val, div){ $(div).append("From failCallbacks - " + val); } function Func3(val, div){ $(div).append("From progressCallbacks - " + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred "def" is notified.<br/>', '#GFG_DOWN'); def.reject('Deferred "def" is rejected.<br/>', '#GFG_DOWN'); } </script> </body> </html> Output: jQuery-Methods JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 25652, "s": 25624, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25801, "s": 25652, "text": "This deferred.then() method in JQuery is used to add handlers which are to be called when the Deferred object is resolved, rejected, or in progress." }, { "code": null, "e": 25809, "s": 25801, "text": "Syntax:" }, { "code": null, "e": 25877, "s": 25809, "text": "deferred.then(doneCallbacks[, failCallbacks][, progressCallbacks])\n" }, { "code": null, "e": 25889, "s": 25877, "text": "Parameters:" }, { "code": null, "e": 25997, "s": 25889, "text": "doneCallbacks: This is a function, or an array of functions, which is called when the Deferred is resolved." }, { "code": null, "e": 26105, "s": 25997, "text": "failCallbacks: This is a function, or an array of functions, which is called when the Deferred is rejected." }, { "code": null, "e": 26253, "s": 26105, "text": "progressCallbacks: This is a function, or an array of functions, which is called when progress notifications are being sent to the Deferred object." }, { "code": null, "e": 26315, "s": 26253, "text": "Return Value: This method method returns the deferred object." }, { "code": null, "e": 26355, "s": 26315, "text": "There are two examples discussed below:" }, { "code": null, "e": 27590, "s": 26355, "text": "Example: In this example, the then() method is called with notify and resolve method.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.then() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>' , '#GFG_DOWN'); def.resolve('Deferred \"def\" is resolved.<br/>' , '#GFG_DOWN'); } </script> </body> </html> " }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.then() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>' , '#GFG_DOWN'); def.resolve('Deferred \"def\" is resolved.<br/>' , '#GFG_DOWN'); } </script> </body> </html> ", "e": 28740, "s": 27590, "text": null }, { "code": null, "e": 28748, "s": 28740, "text": "Output:" }, { "code": null, "e": 29977, "s": 28748, "text": "Example: In this example, the then() method is called with notify and reject method.<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.then() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>', '#GFG_DOWN'); def.reject('Deferred \"def\" is rejected.<br/>', '#GFG_DOWN'); } </script> </body> </html> " }, { "code": null, "e": 30062, "s": 29977, "text": "Example: In this example, the then() method is called with notify and reject method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | deferred.then() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick = \"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); el_up.innerHTML = \"JQuery | deferred.then() method\"; function Func1(val, div){ $(div).append(\"From doneCallbacks - \" + val); } function Func2(val, div){ $(div).append(\"From failCallbacks - \" + val); } function Func3(val, div){ $(div).append(\"From progressCallbacks - \" + val); } function Geeks() { var def = $.Deferred(); def.then(Func1, Func2, Func3); def.notify('Deferred \"def\" is notified.<br/>', '#GFG_DOWN'); def.reject('Deferred \"def\" is rejected.<br/>', '#GFG_DOWN'); } </script> </body> </html> ", "e": 31207, "s": 30062, "text": null }, { "code": null, "e": 31215, "s": 31207, "text": "Output:" }, { "code": null, "e": 31230, "s": 31215, "text": "jQuery-Methods" }, { "code": null, "e": 31241, "s": 31230, "text": "JavaScript" }, { "code": null, "e": 31248, "s": 31241, "text": "JQuery" }, { "code": null, "e": 31265, "s": 31248, "text": "Web Technologies" }, { "code": null, "e": 31363, "s": 31265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31403, "s": 31363, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31448, "s": 31403, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31509, "s": 31448, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31581, "s": 31509, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31633, "s": 31581, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31679, "s": 31633, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 31708, "s": 31679, "text": "Form validation using jQuery" }, { "code": null, "e": 31771, "s": 31708, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 31848, "s": 31771, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Minimum, maximum and average price values for all the items of given type - GeeksforGeeks
28 Oct, 2019 Given a string array item[] and an integer array price[] where price[i] is the price of the item[i] when purchased from the ith shop. The task is find the lowest, the highest and the average price value for all the purchsed items. Examples: Input: item[] = {“toy”, “pen”, “notebook”, “pen”}, price[] = {2, 1, 3, 2}Output:Item Min Max Averagepen 1 2 1.5toy 2 2 2.0notebook 3 3 3.0 Input: item[] = {“car”, “car”}, price[] = {20000, 30000};Output:Item Min Max Averagecar 20000 30000 25000.0 Approach: Create a HashMap where the name of the item will be a string and the value will be an object which will store four types of values for every item i.e. min: To store the minimum value for an item of current type.max: To store the maximum value for an item of current type.total: Total item of the current type.sum: Sum of the prices of the items of current type. min: To store the minimum value for an item of current type. max: To store the maximum value for an item of current type. total: Total item of the current type. sum: Sum of the prices of the items of current type. Now, for every item stored in the Hashmap, the minimum and the maximum price is store in the value object and the average can be calculated as sum / total. Below is the implementation of the above approach: Java C# // Java implementation of the approachimport java.util.*;class GFG { // To store an item static class Item { // To store the minimum and the // maximum price for the item int min, max; // To store the total number of items // of the current type and the // total cost of buying them int total, sum; // Initializing an element Item(int price) { min = price; max = price; total = 1; this.sum = price; } } // Function to find the minimum, the maximum // and the average price for every item static void findPrices(String item[], int price[], int n) { // To store the distinct items HashMap<String, Item> map = new HashMap<>(); // For every item for (int i = 0; i < n; i++) { // If the current item has aready been // purchased earlier from a different shop if (map.containsKey(item[i])) { // Get the item Item currItem = map.get(item[i]); // Update its minimum and maximum price so far currItem.min = Math.min(currItem.min, price[i]); currItem.max = Math.max(currItem.max, price[i]); // Increment the total count of the current item currItem.total++; // Add the current price to the sum currItem.sum += price[i]; } else { // The item has been purchased for the first time Item currItem = new Item(price[i]); map.put(item[i], currItem); } } // Print all the items with their // minimum, maximum and average prices System.out.println("Item Min Max Average"); for (Map.Entry<String, Item> ob : map.entrySet()) { String key = ob.getKey(); Item currItem = ob.getValue(); System.out.println(key + " " + currItem.min + " " + currItem.max + " " + ((float)currItem.sum / (float)currItem.total)); } } // Driver code public static void main(String args[]) { String item[] = { "toy", "pen", "notebook", "pen" }; int n = item.length; int price[] = { 2, 1, 3, 2 }; findPrices(item, price, n); }} // C# implementation of the approach using System; using System.Collections.Generic; class GFG { // To store an item public class Item { // To store the minimum and the // maximum price for the item public int min, max; // To store the total number of items // of the current type and the // total cost of buying them public int total, sum; // Initializing an element public Item(int price) { min = price; max = price; total = 1; this.sum = price; } } // Function to find the minimum, the maximum // and the average price for every item static void findPrices(String []item, int []price, int n) { // To store the distinct items Dictionary<String, Item> map = new Dictionary<String, Item>(); // For every item for (int i = 0; i < n; i++) { // If the current item has aready been // purchased earlier from a different shop if (map.ContainsKey(item[i])) { // Get the item Item currItem = map[item[i]]; // Update its minimum and // maximum price so far currItem.min = Math.Min(currItem.min, price[i]); currItem.max = Math.Max(currItem.max, price[i]); // Increment the total count of // the current item currItem.total++; // Add the current price to the sum currItem.sum += price[i]; } else { // The item has been purchased // for the first time Item currItem = new Item(price[i]); map.Add(item[i], currItem); } } // Print all the items with their // minimum, maximum and average prices Console.WriteLine("Item Min Max Average"); foreach(KeyValuePair<String, Item> ob in map) { String key = ob.Key; Item currItem = ob.Value; Console.WriteLine(key + " " + currItem.min + " " + currItem.max + " " + ((float)currItem.sum / (float)currItem.total)); } } // Driver code public static void Main(String []args) { String []item = { "toy", "pen", "notebook", "pen" }; int n = item.Length; int []price = { 2, 1, 3, 2 }; findPrices(item, price, n); }} // This code is contributed by 29AjayKumar Item Min Max Average pen 1 2 1.5 toy 2 2 2.0 notebook 3 3 3.0 29AjayKumar Java-HashMap math Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26271, "s": 26243, "text": "\n28 Oct, 2019" }, { "code": null, "e": 26502, "s": 26271, "text": "Given a string array item[] and an integer array price[] where price[i] is the price of the item[i] when purchased from the ith shop. The task is find the lowest, the highest and the average price value for all the purchsed items." }, { "code": null, "e": 26512, "s": 26502, "text": "Examples:" }, { "code": null, "e": 26651, "s": 26512, "text": "Input: item[] = {“toy”, “pen”, “notebook”, “pen”}, price[] = {2, 1, 3, 2}Output:Item Min Max Averagepen 1 2 1.5toy 2 2 2.0notebook 3 3 3.0" }, { "code": null, "e": 26759, "s": 26651, "text": "Input: item[] = {“car”, “car”}, price[] = {20000, 30000};Output:Item Min Max Averagecar 20000 30000 25000.0" }, { "code": null, "e": 26920, "s": 26759, "text": "Approach: Create a HashMap where the name of the item will be a string and the value will be an object which will store four types of values for every item i.e." }, { "code": null, "e": 27131, "s": 26920, "text": "min: To store the minimum value for an item of current type.max: To store the maximum value for an item of current type.total: Total item of the current type.sum: Sum of the prices of the items of current type." }, { "code": null, "e": 27192, "s": 27131, "text": "min: To store the minimum value for an item of current type." }, { "code": null, "e": 27253, "s": 27192, "text": "max: To store the maximum value for an item of current type." }, { "code": null, "e": 27292, "s": 27253, "text": "total: Total item of the current type." }, { "code": null, "e": 27345, "s": 27292, "text": "sum: Sum of the prices of the items of current type." }, { "code": null, "e": 27501, "s": 27345, "text": "Now, for every item stored in the Hashmap, the minimum and the maximum price is store in the value object and the average can be calculated as sum / total." }, { "code": null, "e": 27552, "s": 27501, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27557, "s": 27552, "text": "Java" }, { "code": null, "e": 27560, "s": 27557, "text": "C#" }, { "code": "// Java implementation of the approachimport java.util.*;class GFG { // To store an item static class Item { // To store the minimum and the // maximum price for the item int min, max; // To store the total number of items // of the current type and the // total cost of buying them int total, sum; // Initializing an element Item(int price) { min = price; max = price; total = 1; this.sum = price; } } // Function to find the minimum, the maximum // and the average price for every item static void findPrices(String item[], int price[], int n) { // To store the distinct items HashMap<String, Item> map = new HashMap<>(); // For every item for (int i = 0; i < n; i++) { // If the current item has aready been // purchased earlier from a different shop if (map.containsKey(item[i])) { // Get the item Item currItem = map.get(item[i]); // Update its minimum and maximum price so far currItem.min = Math.min(currItem.min, price[i]); currItem.max = Math.max(currItem.max, price[i]); // Increment the total count of the current item currItem.total++; // Add the current price to the sum currItem.sum += price[i]; } else { // The item has been purchased for the first time Item currItem = new Item(price[i]); map.put(item[i], currItem); } } // Print all the items with their // minimum, maximum and average prices System.out.println(\"Item Min Max Average\"); for (Map.Entry<String, Item> ob : map.entrySet()) { String key = ob.getKey(); Item currItem = ob.getValue(); System.out.println(key + \" \" + currItem.min + \" \" + currItem.max + \" \" + ((float)currItem.sum / (float)currItem.total)); } } // Driver code public static void main(String args[]) { String item[] = { \"toy\", \"pen\", \"notebook\", \"pen\" }; int n = item.length; int price[] = { 2, 1, 3, 2 }; findPrices(item, price, n); }}", "e": 29965, "s": 27560, "text": null }, { "code": "// C# implementation of the approach using System; using System.Collections.Generic; class GFG { // To store an item public class Item { // To store the minimum and the // maximum price for the item public int min, max; // To store the total number of items // of the current type and the // total cost of buying them public int total, sum; // Initializing an element public Item(int price) { min = price; max = price; total = 1; this.sum = price; } } // Function to find the minimum, the maximum // and the average price for every item static void findPrices(String []item, int []price, int n) { // To store the distinct items Dictionary<String, Item> map = new Dictionary<String, Item>(); // For every item for (int i = 0; i < n; i++) { // If the current item has aready been // purchased earlier from a different shop if (map.ContainsKey(item[i])) { // Get the item Item currItem = map[item[i]]; // Update its minimum and // maximum price so far currItem.min = Math.Min(currItem.min, price[i]); currItem.max = Math.Max(currItem.max, price[i]); // Increment the total count of // the current item currItem.total++; // Add the current price to the sum currItem.sum += price[i]; } else { // The item has been purchased // for the first time Item currItem = new Item(price[i]); map.Add(item[i], currItem); } } // Print all the items with their // minimum, maximum and average prices Console.WriteLine(\"Item Min Max Average\"); foreach(KeyValuePair<String, Item> ob in map) { String key = ob.Key; Item currItem = ob.Value; Console.WriteLine(key + \" \" + currItem.min + \" \" + currItem.max + \" \" + ((float)currItem.sum / (float)currItem.total)); } } // Driver code public static void Main(String []args) { String []item = { \"toy\", \"pen\", \"notebook\", \"pen\" }; int n = item.Length; int []price = { 2, 1, 3, 2 }; findPrices(item, price, n); }} // This code is contributed by 29AjayKumar", "e": 32797, "s": 29965, "text": null }, { "code": null, "e": 32860, "s": 32797, "text": "Item Min Max Average\npen 1 2 1.5\ntoy 2 2 2.0\nnotebook 3 3 3.0\n" }, { "code": null, "e": 32872, "s": 32860, "text": "29AjayKumar" }, { "code": null, "e": 32885, "s": 32872, "text": "Java-HashMap" }, { "code": null, "e": 32890, "s": 32885, "text": "math" }, { "code": null, "e": 32897, "s": 32890, "text": "Arrays" }, { "code": null, "e": 32905, "s": 32897, "text": "Strings" }, { "code": null, "e": 32912, "s": 32905, "text": "Arrays" }, { "code": null, "e": 32920, "s": 32912, "text": "Strings" }, { "code": null, "e": 33018, "s": 32920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33086, "s": 33018, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33130, "s": 33086, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33178, "s": 33130, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33201, "s": 33178, "text": "Introduction to Arrays" }, { "code": null, "e": 33233, "s": 33201, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33258, "s": 33233, "text": "Reverse a string in Java" }, { "code": null, "e": 33318, "s": 33258, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33333, "s": 33318, "text": "C++ Data Types" }, { "code": null, "e": 33367, "s": 33333, "text": "Longest Common Subsequence | DP-4" } ]
p5.js | windowWidth - GeeksforGeeks
15 Apr, 2019 The windowWidth variable in p5.js is a system variable that is used to store the width of the inner window and it maps to window.innerWidth.Syntax: windowWidth Parameters: This function does not accept any parameter. Below program illustrates the windowWidth variable in p5.js:Example-1: function setup() { createCanvas(1000, 400); // Set text size to 40px textSize(20);} function draw() { background(200); rect(mouseX, mouseY, 30, 30); //Use of windowWidth Variable text("Window Width is " + windowWidth, 30, 40);} Output: Example-2: function setup() { // set height to window width width = windowWidth; //create Canvas of size 380*80 createCanvas(width, 100);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); //use of windowWidth variable text("windowWidth of Canvas is : " + width, width / 2, height / 2);} Output: Reference: https://p5js.org/reference/#/p5/windowWidth JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 44937, "s": 44909, "text": "\n15 Apr, 2019" }, { "code": null, "e": 45085, "s": 44937, "text": "The windowWidth variable in p5.js is a system variable that is used to store the width of the inner window and it maps to window.innerWidth.Syntax:" }, { "code": null, "e": 45098, "s": 45085, "text": "windowWidth\n" }, { "code": null, "e": 45155, "s": 45098, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 45226, "s": 45155, "text": "Below program illustrates the windowWidth variable in p5.js:Example-1:" }, { "code": "function setup() { createCanvas(1000, 400); // Set text size to 40px textSize(20);} function draw() { background(200); rect(mouseX, mouseY, 30, 30); //Use of windowWidth Variable text(\"Window Width is \" + windowWidth, 30, 40);}", "e": 45492, "s": 45226, "text": null }, { "code": null, "e": 45500, "s": 45492, "text": "Output:" }, { "code": null, "e": 45511, "s": 45500, "text": "Example-2:" }, { "code": "function setup() { // set height to window width width = windowWidth; //create Canvas of size 380*80 createCanvas(width, 100);} function draw() { background(220); textSize(16); textAlign(CENTER); fill(color('Green')); //use of windowWidth variable text(\"windowWidth of Canvas is : \" + width, width / 2, height / 2);}", "e": 45875, "s": 45511, "text": null }, { "code": null, "e": 45883, "s": 45875, "text": "Output:" }, { "code": null, "e": 45938, "s": 45883, "text": "Reference: https://p5js.org/reference/#/p5/windowWidth" }, { "code": null, "e": 45955, "s": 45938, "text": "JavaScript-p5.js" }, { "code": null, "e": 45966, "s": 45955, "text": "JavaScript" }, { "code": null, "e": 45983, "s": 45966, "text": "Web Technologies" }, { "code": null, "e": 46081, "s": 45983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46121, "s": 46081, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46166, "s": 46121, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46227, "s": 46166, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 46299, "s": 46227, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 46368, "s": 46299, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 46408, "s": 46368, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46441, "s": 46408, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46486, "s": 46441, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46529, "s": 46486, "text": "How to fetch data from an API in ReactJS ?" } ]
Swap Alternate Boundary Pairs - GeeksforGeeks
26 Feb, 2021 Given an array arr[] of N integers, the task is to swap the first and the last element then the third and the third last element then fifth and fifth last and so on. Print the final array after all the valid operations. Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 6 2 4 3 5 1 Operation 1: Swap 1 and 6 Operation 2: Swap 3 and 4Input: arr[] = {5, 54, 12, 63, 45} Output: 45 54 12 63 5 Approach: Initialize pointer i = 0 and j = N – 1 then swap the elements at these pointers and update i = i + 2 and j = j – 2. Repeat these steps while i < j. Finally print the updated array.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to update the arrayvoid UpdateArr(int arr[], int n){ // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); UpdateArr(arr, n); return 0;} // Java implementation of the above approachclass GFG{ // Utility function to print // the contents of an array static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Function to update the array static void UpdateArr(int arr[], int n) { // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n); } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; UpdateArr(arr, n); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(n): print(arr[i], end = " "); # Function to update the arraydef UpdateArr(arr, n): # Initialize the pointers i = 0; j = n - 1; # While there are elements to swap while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; # Update the pointers i += 2; j -= 2; # Print the updated array printArr(arr, n); # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6 ]; n = len(arr); UpdateArr(arr, n); # This code is contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Utility function to print // the contents of an array static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Function to update the array static void UpdateArr(int []arr, int n) { // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n); } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; UpdateArr(arr, n); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to update the arrayfunction UpdateArr(arr, n){ // Initialize the pointers let i = 0, j = n - 1; // While there are elements to swap while (i < j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n);} // Driver code let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length;; UpdateArr(arr, n); // This code is contributed by Surbhi Tyagi </script> 6 2 4 3 5 1 ankthon 29AjayKumar princiraj1992 Akanksha_Rai surbhityagi15 Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26066, "s": 26038, "text": "\n26 Feb, 2021" }, { "code": null, "e": 26287, "s": 26066, "text": "Given an array arr[] of N integers, the task is to swap the first and the last element then the third and the third last element then fifth and fifth last and so on. Print the final array after all the valid operations. " }, { "code": null, "e": 26451, "s": 26287, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 6 2 4 3 5 1 Operation 1: Swap 1 and 6 Operation 2: Swap 3 and 4Input: arr[] = {5, 54, 12, 63, 45} Output: 45 54 12 63 5 " }, { "code": null, "e": 26696, "s": 26453, "text": "Approach: Initialize pointer i = 0 and j = N – 1 then swap the elements at these pointers and update i = i + 2 and j = j – 2. Repeat these steps while i < j. Finally print the updated array.Below is the implementation of the above approach: " }, { "code": null, "e": 26700, "s": 26696, "text": "C++" }, { "code": null, "e": 26705, "s": 26700, "text": "Java" }, { "code": null, "e": 26713, "s": 26705, "text": "Python3" }, { "code": null, "e": 26716, "s": 26713, "text": "C#" }, { "code": null, "e": 26727, "s": 26716, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to update the arrayvoid UpdateArr(int arr[], int n){ // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); UpdateArr(arr, n); return 0;}", "e": 27472, "s": 26727, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Utility function to print // the contents of an array static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Function to update the array static void UpdateArr(int arr[], int n) { // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n); } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; UpdateArr(arr, n); }} // This code is contributed by AnkitRai01", "e": 28416, "s": 27472, "text": null }, { "code": "# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(n): print(arr[i], end = \" \"); # Function to update the arraydef UpdateArr(arr, n): # Initialize the pointers i = 0; j = n - 1; # While there are elements to swap while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; # Update the pointers i += 2; j -= 2; # Print the updated array printArr(arr, n); # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6 ]; n = len(arr); UpdateArr(arr, n); # This code is contributed by PrinciRaj1992", "e": 29089, "s": 28416, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Utility function to print // the contents of an array static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Function to update the array static void UpdateArr(int []arr, int n) { // Initialize the pointers int i = 0, j = n - 1; // While there are elements to swap while (i < j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n); } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; UpdateArr(arr, n); }} // This code is contributed by 29AjayKumar", "e": 30041, "s": 29089, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to update the arrayfunction UpdateArr(arr, n){ // Initialize the pointers let i = 0, j = n - 1; // While there are elements to swap while (i < j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Update the pointers i += 2; j -= 2; } // Print the updated array printArr(arr, n);} // Driver code let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length;; UpdateArr(arr, n); // This code is contributed by Surbhi Tyagi </script>", "e": 30763, "s": 30041, "text": null }, { "code": null, "e": 30775, "s": 30763, "text": "6 2 4 3 5 1" }, { "code": null, "e": 30785, "s": 30777, "text": "ankthon" }, { "code": null, "e": 30797, "s": 30785, "text": "29AjayKumar" }, { "code": null, "e": 30811, "s": 30797, "text": "princiraj1992" }, { "code": null, "e": 30824, "s": 30811, "text": "Akanksha_Rai" }, { "code": null, "e": 30838, "s": 30824, "text": "surbhityagi15" }, { "code": null, "e": 30845, "s": 30838, "text": "Arrays" }, { "code": null, "e": 30853, "s": 30845, "text": "Sorting" }, { "code": null, "e": 30860, "s": 30853, "text": "Arrays" }, { "code": null, "e": 30868, "s": 30860, "text": "Sorting" }, { "code": null, "e": 30966, "s": 30868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30993, "s": 30966, "text": "Count pairs with given sum" }, { "code": null, "e": 31024, "s": 30993, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31049, "s": 31024, "text": "Window Sliding Technique" }, { "code": null, "e": 31087, "s": 31049, "text": "Reversal algorithm for array rotation" } ]
ReactJS UI Ant Design Anchor Component - GeeksforGeeks
30 May, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. Anchor Component is used to allow the hyperlinks to scroll on one page. It is useful when we want to display the anchor hyperlinks on the page and allow the user to jumps between them easily. We can use the following approach in ReactJS to use the Ant Design Anchor Component. Anchor Props: affix: It is used to denote the fixed mode of Anchor. bounds: It is used to bound the distance of the anchor area. getContainer: It is a function to get the scrolling container. getCurrentAnchor: It is used to customize the anchor highlight. offsetTop: When calculating the position of the scroll, it is used to denote the pixels to offset from top. showInkInFixed: It is used to indicate whether to show ink-balls or not when affix is set to false. targetOffset: It is used to denote the Anchor scroll offset. onChange: It is a callback function that is triggered on the anchor link change. onClick: It is a callback function that is used to set the handler to handle click event. Link Props: href: It is used to denote the target of hyperlinks. target: It is used to specify where to display the linked URL. title: It is used to define the content of hyperlinks. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import "antd/dist/antd.css";import { Anchor } from 'antd'; const { Link } = Anchor; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30, height: 1000, }}> <h4>ReactJS Ant-Design Anchor Component</h4> <Anchor> <Link href="#" title="Course Link" /> <Link href="#" title="Exam Link"> <Link href="#" title="Study Material" /> <Link href="#" title="Exam Prepration" /> <Link href="#" title="Test Link" /> </Link> </Anchor> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/anchor/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 35483, "s": 35455, "text": "\n30 May, 2021" }, { "code": null, "e": 35851, "s": 35483, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Anchor Component is used to allow the hyperlinks to scroll on one page. It is useful when we want to display the anchor hyperlinks on the page and allow the user to jumps between them easily. We can use the following approach in ReactJS to use the Ant Design Anchor Component." }, { "code": null, "e": 35865, "s": 35851, "text": "Anchor Props:" }, { "code": null, "e": 35919, "s": 35865, "text": "affix: It is used to denote the fixed mode of Anchor." }, { "code": null, "e": 35980, "s": 35919, "text": "bounds: It is used to bound the distance of the anchor area." }, { "code": null, "e": 36043, "s": 35980, "text": "getContainer: It is a function to get the scrolling container." }, { "code": null, "e": 36107, "s": 36043, "text": "getCurrentAnchor: It is used to customize the anchor highlight." }, { "code": null, "e": 36215, "s": 36107, "text": "offsetTop: When calculating the position of the scroll, it is used to denote the pixels to offset from top." }, { "code": null, "e": 36315, "s": 36215, "text": "showInkInFixed: It is used to indicate whether to show ink-balls or not when affix is set to false." }, { "code": null, "e": 36376, "s": 36315, "text": "targetOffset: It is used to denote the Anchor scroll offset." }, { "code": null, "e": 36457, "s": 36376, "text": "onChange: It is a callback function that is triggered on the anchor link change." }, { "code": null, "e": 36547, "s": 36457, "text": "onClick: It is a callback function that is used to set the handler to handle click event." }, { "code": null, "e": 36559, "s": 36547, "text": "Link Props:" }, { "code": null, "e": 36612, "s": 36559, "text": "href: It is used to denote the target of hyperlinks." }, { "code": null, "e": 36675, "s": 36612, "text": "target: It is used to specify where to display the linked URL." }, { "code": null, "e": 36730, "s": 36675, "text": "title: It is used to define the content of hyperlinks." }, { "code": null, "e": 36780, "s": 36730, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 36875, "s": 36780, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 36939, "s": 36875, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 36971, "s": 36939, "text": "npx create-react-app foldername" }, { "code": null, "e": 37084, "s": 36971, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 37184, "s": 37084, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 37198, "s": 37184, "text": "cd foldername" }, { "code": null, "e": 37319, "s": 37198, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 37424, "s": 37319, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 37441, "s": 37424, "text": "npm install antd" }, { "code": null, "e": 37493, "s": 37441, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 37511, "s": 37493, "text": "Project Structure" }, { "code": null, "e": 37641, "s": 37511, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 37648, "s": 37641, "text": "App.js" }, { "code": "import React from 'react'import \"antd/dist/antd.css\";import { Anchor } from 'antd'; const { Link } = Anchor; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30, height: 1000, }}> <h4>ReactJS Ant-Design Anchor Component</h4> <Anchor> <Link href=\"#\" title=\"Course Link\" /> <Link href=\"#\" title=\"Exam Link\"> <Link href=\"#\" title=\"Study Material\" /> <Link href=\"#\" title=\"Exam Prepration\" /> <Link href=\"#\" title=\"Test Link\" /> </Link> </Anchor> </div> );}", "e": 38228, "s": 37648, "text": null }, { "code": null, "e": 38341, "s": 38228, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 38351, "s": 38341, "text": "npm start" }, { "code": null, "e": 38450, "s": 38351, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 38499, "s": 38450, "text": "Reference: https://ant.design/components/anchor/" }, { "code": null, "e": 38518, "s": 38499, "text": "ReactJS-Ant Design" }, { "code": null, "e": 38526, "s": 38518, "text": "ReactJS" }, { "code": null, "e": 38543, "s": 38526, "text": "Web Technologies" }, { "code": null, "e": 38641, "s": 38543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38684, "s": 38641, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38729, "s": 38684, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 38794, "s": 38729, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 38862, "s": 38794, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 38903, "s": 38862, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 38943, "s": 38903, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 38976, "s": 38943, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39021, "s": 38976, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39064, "s": 39021, "text": "How to fetch data from an API in ReactJS ?" } ]
Linked complete binary tree & its creation - GeeksforGeeks
10 Nov, 2020 A complete binary tree is a binary tree where each level ‘l’ except the last has 2^l nodes and the nodes at the last level are all left-aligned. Complete binary trees are mainly used in heap-based data structures. The nodes in the complete binary tree are inserted from left to right in one level at a time. If a level is full, the node is inserted in a new level.Below are some complete binary trees. 1 / \ 2 3 1 / \ 2 3 / \ / 4 5 6 Below binary trees are not complete: 1 / \ 2 3 / / 4 5 1 / \ 2 3 / \ / 4 5 6 / 7 Complete binary trees are generally represented using arrays. The array representation is better because it doesn’t contain any empty slots. Given parent index i, its left child is given by 2 * i + 1, and its right child is given by 2 * i + 2. So no extra space is wasted and space to store left and right pointers is saved. However, it may be an interesting programming question to create a Complete Binary Tree using linked representation. Here Linked means a non-array representation where the left and right pointers(or references) are used to refer left and right children respectively. How to write an insert function that always adds a new node in the last level and at the leftmost available position? To create a linked complete binary tree, we need to keep track of the nodes in a level order fashion such that the next node to be inserted lies in the leftmost position. A queue data structure can be used to keep track of the inserted nodes. The following are steps to insert a new node in Complete Binary Tree. 1. If the tree is empty, initialize the root with a new node.2. Else, get the front node of the queue. .......If the left child of this front node doesn’t exist, set the left child as the new node. .......else if the right child of this front node doesn’t exist, set the right child as the new node.3. If the front node has both the left child and right child, Dequeue() it.4. Enqueue() the new node.Below is the implementation: C C++ Python3 // Program for linked implementation of complete binary tree#include <stdio.h>#include <stdlib.h> // For Queue Size#define SIZE 50 // A tree nodestruct node{ int data; struct node *right,*left;}; // A queue nodestruct Queue{ int front, rear; int size; struct node* *array;}; // A utility function to create a new tree nodestruct node* newNode(int data){ struct node* temp = (struct node*) malloc(sizeof( struct node )); temp->data = data; temp->left = temp->right = NULL; return temp;} // A utility function to create a new Queuestruct Queue* createQueue(int size){ struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue )); queue->front = queue->rear = -1; queue->size = size; queue->array = (struct node**) malloc (queue->size * sizeof( struct node* )); int i; for (i = 0; i < size; ++i) queue->array[i] = NULL; return queue;} // Standard Queue Functionsint isEmpty(struct Queue* queue){ return queue->front == -1;} int isFull(struct Queue* queue){ return queue->rear == queue->size - 1; } int hasOnlyOneItem(struct Queue* queue){ return queue->front == queue->rear; } void Enqueue(struct node *root, struct Queue* queue){ if (isFull(queue)) return; queue->array[++queue->rear] = root; if (isEmpty(queue)) ++queue->front;} struct node* Dequeue(struct Queue* queue){ if (isEmpty(queue)) return NULL; struct node* temp = queue->array[queue->front]; if (hasOnlyOneItem(queue)) queue->front = queue->rear = -1; else ++queue->front; return temp;} struct node* getFront(struct Queue* queue){ return queue->array[queue->front]; } // A utility function to check if a tree node// has both left and right childrenint hasBothChild(struct node* temp){ return temp && temp->left && temp->right;} // Function to insert a new node in complete binary treevoid insert(struct node **root, int data, struct Queue* queue){ // Create a new node for given data struct node *temp = newNode(data); // If the tree is empty, initialize the root with new node. if (!*root) *root = temp; else { // get the front node of the queue. struct node* front = getFront(queue); // If the left child of this front node doesn’t exist, set the // left child as the new node if (!front->left) front->left = temp; // If the right child of this front node doesn’t exist, set the // right child as the new node else if (!front->right) front->right = temp; // If the front node has both the left child and right child, // Dequeue() it. if (hasBothChild(front)) Dequeue(queue); } // Enqueue() the new node for later insertions Enqueue(temp, queue);} // Standard level order traversal to test above functionvoid levelOrder(struct node* root){ struct Queue* queue = createQueue(SIZE); Enqueue(root, queue); while (!isEmpty(queue)) { struct node* temp = Dequeue(queue); printf("%d ", temp->data); if (temp->left) Enqueue(temp->left, queue); if (temp->right) Enqueue(temp->right, queue); }} // Driver program to test above functionsint main(){ struct node* root = NULL; struct Queue* queue = createQueue(SIZE); int i; for(i = 1; i <= 12; ++i) insert(&root, i, queue); levelOrder(root); return 0;} // Program for linked implementation of complete binary tree#include <bits/stdc++.h>using namespace std; // For Queue Size#define SIZE 50 // A tree nodeclass node{ public: int data; node *right,*left;}; // A queue nodeclass Queue{ public: int front, rear; int size; node**array;}; // A 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;} // A utility function to create a new QueueQueue* createQueue(int size){ Queue* queue = new Queue(); queue->front = queue->rear = -1; queue->size = size; queue->array = new node*[queue->size * sizeof( node* )]; int i; for (i = 0; i < size; ++i) queue->array[i] = NULL; return queue;} // Standard Queue Functionsint isEmpty(Queue* queue){ return queue->front == -1;} int isFull(Queue* queue){ return queue->rear == queue->size - 1; } int hasOnlyOneItem(Queue* queue){ return queue->front == queue->rear; } void Enqueue(node *root, Queue* queue){ if (isFull(queue)) return; queue->array[++queue->rear] = root; if (isEmpty(queue)) ++queue->front;} node* Dequeue(Queue* queue){ if (isEmpty(queue)) return NULL; node* temp = queue->array[queue->front]; if (hasOnlyOneItem(queue)) queue->front = queue->rear = -1; else ++queue->front; return temp;} node* getFront(Queue* queue){ return queue->array[queue->front]; } // A utility function to check if a tree node// has both left and right childrenint hasBothChild(node* temp){ return temp && temp->left && temp->right;} // Function to insert a new node in complete binary treevoid insert(node **root, int data, Queue* queue){ // Create a new node for given data node *temp = newNode(data); // If the tree is empty, initialize the root with new node. if (!*root) *root = temp; else { // get the front node of the queue. node* front = getFront(queue); // If the left child of this front node doesn’t exist, set the // left child as the new node if (!front->left) front->left = temp; // If the right child of this front node doesn’t exist, set the // right child as the new node else if (!front->right) front->right = temp; // If the front node has both the left child and right child, // Dequeue() it. if (hasBothChild(front)) Dequeue(queue); } // Enqueue() the new node for later insertions Enqueue(temp, queue);} // Standard level order traversal to test above functionvoid levelOrder(node* root){ Queue* queue = createQueue(SIZE); Enqueue(root, queue); while (!isEmpty(queue)) { node* temp = Dequeue(queue); cout<<temp->data<<" "; if (temp->left) Enqueue(temp->left, queue); if (temp->right) Enqueue(temp->right, queue); }} // Driver program to test above functionsint main(){ node* root = NULL; Queue* queue = createQueue(SIZE); int i; for(i = 1; i <= 12; ++i) insert(&root, i, queue); levelOrder(root); return 0;} //This code is contributed by rathbhupendra # Program for linked implementation# of complete binary tree # For Queue SizeSIZE = 50 # A tree nodeclass node: def __init__(self, data): self.data = data self.right = None self.left = None # A queue nodeclass Queue: def __init__(self): self.front = None self.rear = None self.size = 0 self.array = [] # A utility function to# create a new tree nodedef newNode(data): temp = node(data) return temp # A utility function to# create a new Queuedef createQueue(size): global queue queue = Queue(); queue.front = queue.rear = -1; queue.size = size; queue.array = [None for i in range(size)] return queue; # Standard Queue Functionsdef isEmpty(queue): return queue.front == -1 def isFull(queue): return queue.rear == queue.size - 1; def hasOnlyOneItem(queue): return queue.front == queue.rear; def Enqueue(root): if (isFull(queue)): return; queue.rear+=1 queue.array[queue.rear] = root; if (isEmpty(queue)): queue.front+=1; def Dequeue(): if (isEmpty(queue)): return None; temp = queue.array[queue.front]; if(hasOnlyOneItem(queue)): queue.front = queue.rear = -1; else: queue.front+=1 return temp; def getFront(queue): return queue.array[queue.front]; # A utility function to check# if a tree node has both left# and right childrendef hasBothChild(temp): return (temp and temp.left and temp.right); # Function to insert a new# node in complete binary treedef insert(root, data, queue): # Create a new node for # given data temp = newNode(data); # If the tree is empty, # initialize the root # with new node. if not root: root = temp; else: # get the front node of # the queue. front = getFront(queue); # If the left child of this # front node doesn’t exist, # set the left child as the # new node if (not front.left): front.left = temp; # If the right child of this # front node doesn’t exist, set # the right child as the new node elif (not front.right): front.right = temp; # If the front node has both the # left child and right child, # Dequeue() it. if (hasBothChild(front)): Dequeue(); # Enqueue() the new node for # later insertions Enqueue(temp); return root # Standard level order# traversal to test above# functiondef levelOrder(root): queue = createQueue(SIZE); Enqueue(root); while (not isEmpty(queue)): temp = Dequeue(); print(temp.data, end = ' ') if (temp.left): Enqueue(temp.left); if (temp.right): Enqueue(temp.right); # Driver code if __name__ == "__main__": root = None queue = createQueue(SIZE); for i in range(1, 13): root=insert(root, i, queue); levelOrder(root); # This code is contributed by Rutvik_56 1 2 3 4 5 6 7 8 9 10 11 12 This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra rutvik_56 Complete Binary Tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure DFS traversal of a tree using recursion Difference between B tree and B+ tree Construct Complete Binary Tree from its Linked List Representation 2-3 Trees | (Search, Insert and Deletion) Difference between Min Heap and Max Heap Iterative Postorder Traversal | Set 2 (Using One Stack) Find the node with minimum value in a Binary Search Tree Binary Tree to Binary Search Tree Conversion Threaded Binary Tree
[ { "code": null, "e": 24860, "s": 24832, "text": "\n10 Nov, 2020" }, { "code": null, "e": 25264, "s": 24860, "text": "A complete binary tree is a binary tree where each level ‘l’ except the last has 2^l nodes and the nodes at the last level are all left-aligned. Complete binary trees are mainly used in heap-based data structures. The nodes in the complete binary tree are inserted from left to right in one level at a time. If a level is full, the node is inserted in a new level.Below are some complete binary trees. " }, { "code": null, "e": 25354, "s": 25264, "text": " 1\n / \\\n 2 3\n\n 1\n / \\\n 2 3\n / \\ / \n 4 5 6\n\n" }, { "code": null, "e": 25394, "s": 25354, "text": "Below binary trees are not complete: " }, { "code": null, "e": 25495, "s": 25394, "text": " 1\n / \\\n 2 3\n / /\n 4 5\n\n 1\n / \\\n 2 3\n / \\ /\n 4 5 6\n /\n 7\n" }, { "code": null, "e": 26949, "s": 25495, "text": "Complete binary trees are generally represented using arrays. The array representation is better because it doesn’t contain any empty slots. Given parent index i, its left child is given by 2 * i + 1, and its right child is given by 2 * i + 2. So no extra space is wasted and space to store left and right pointers is saved. However, it may be an interesting programming question to create a Complete Binary Tree using linked representation. Here Linked means a non-array representation where the left and right pointers(or references) are used to refer left and right children respectively. How to write an insert function that always adds a new node in the last level and at the leftmost available position? To create a linked complete binary tree, we need to keep track of the nodes in a level order fashion such that the next node to be inserted lies in the leftmost position. A queue data structure can be used to keep track of the inserted nodes. The following are steps to insert a new node in Complete Binary Tree. 1. If the tree is empty, initialize the root with a new node.2. Else, get the front node of the queue. .......If the left child of this front node doesn’t exist, set the left child as the new node. .......else if the right child of this front node doesn’t exist, set the right child as the new node.3. If the front node has both the left child and right child, Dequeue() it.4. Enqueue() the new node.Below is the implementation: " }, { "code": null, "e": 26951, "s": 26949, "text": "C" }, { "code": null, "e": 26955, "s": 26951, "text": "C++" }, { "code": null, "e": 26963, "s": 26955, "text": "Python3" }, { "code": "// Program for linked implementation of complete binary tree#include <stdio.h>#include <stdlib.h> // For Queue Size#define SIZE 50 // A tree nodestruct node{ int data; struct node *right,*left;}; // A queue nodestruct Queue{ int front, rear; int size; struct node* *array;}; // A utility function to create a new tree nodestruct node* newNode(int data){ struct node* temp = (struct node*) malloc(sizeof( struct node )); temp->data = data; temp->left = temp->right = NULL; return temp;} // A utility function to create a new Queuestruct Queue* createQueue(int size){ struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue )); queue->front = queue->rear = -1; queue->size = size; queue->array = (struct node**) malloc (queue->size * sizeof( struct node* )); int i; for (i = 0; i < size; ++i) queue->array[i] = NULL; return queue;} // Standard Queue Functionsint isEmpty(struct Queue* queue){ return queue->front == -1;} int isFull(struct Queue* queue){ return queue->rear == queue->size - 1; } int hasOnlyOneItem(struct Queue* queue){ return queue->front == queue->rear; } void Enqueue(struct node *root, struct Queue* queue){ if (isFull(queue)) return; queue->array[++queue->rear] = root; if (isEmpty(queue)) ++queue->front;} struct node* Dequeue(struct Queue* queue){ if (isEmpty(queue)) return NULL; struct node* temp = queue->array[queue->front]; if (hasOnlyOneItem(queue)) queue->front = queue->rear = -1; else ++queue->front; return temp;} struct node* getFront(struct Queue* queue){ return queue->array[queue->front]; } // A utility function to check if a tree node// has both left and right childrenint hasBothChild(struct node* temp){ return temp && temp->left && temp->right;} // Function to insert a new node in complete binary treevoid insert(struct node **root, int data, struct Queue* queue){ // Create a new node for given data struct node *temp = newNode(data); // If the tree is empty, initialize the root with new node. if (!*root) *root = temp; else { // get the front node of the queue. struct node* front = getFront(queue); // If the left child of this front node doesn’t exist, set the // left child as the new node if (!front->left) front->left = temp; // If the right child of this front node doesn’t exist, set the // right child as the new node else if (!front->right) front->right = temp; // If the front node has both the left child and right child, // Dequeue() it. if (hasBothChild(front)) Dequeue(queue); } // Enqueue() the new node for later insertions Enqueue(temp, queue);} // Standard level order traversal to test above functionvoid levelOrder(struct node* root){ struct Queue* queue = createQueue(SIZE); Enqueue(root, queue); while (!isEmpty(queue)) { struct node* temp = Dequeue(queue); printf(\"%d \", temp->data); if (temp->left) Enqueue(temp->left, queue); if (temp->right) Enqueue(temp->right, queue); }} // Driver program to test above functionsint main(){ struct node* root = NULL; struct Queue* queue = createQueue(SIZE); int i; for(i = 1; i <= 12; ++i) insert(&root, i, queue); levelOrder(root); return 0;}", "e": 30422, "s": 26963, "text": null }, { "code": "// Program for linked implementation of complete binary tree#include <bits/stdc++.h>using namespace std; // For Queue Size#define SIZE 50 // A tree nodeclass node{ public: int data; node *right,*left;}; // A queue nodeclass Queue{ public: int front, rear; int size; node**array;}; // A 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;} // A utility function to create a new QueueQueue* createQueue(int size){ Queue* queue = new Queue(); queue->front = queue->rear = -1; queue->size = size; queue->array = new node*[queue->size * sizeof( node* )]; int i; for (i = 0; i < size; ++i) queue->array[i] = NULL; return queue;} // Standard Queue Functionsint isEmpty(Queue* queue){ return queue->front == -1;} int isFull(Queue* queue){ return queue->rear == queue->size - 1; } int hasOnlyOneItem(Queue* queue){ return queue->front == queue->rear; } void Enqueue(node *root, Queue* queue){ if (isFull(queue)) return; queue->array[++queue->rear] = root; if (isEmpty(queue)) ++queue->front;} node* Dequeue(Queue* queue){ if (isEmpty(queue)) return NULL; node* temp = queue->array[queue->front]; if (hasOnlyOneItem(queue)) queue->front = queue->rear = -1; else ++queue->front; return temp;} node* getFront(Queue* queue){ return queue->array[queue->front]; } // A utility function to check if a tree node// has both left and right childrenint hasBothChild(node* temp){ return temp && temp->left && temp->right;} // Function to insert a new node in complete binary treevoid insert(node **root, int data, Queue* queue){ // Create a new node for given data node *temp = newNode(data); // If the tree is empty, initialize the root with new node. if (!*root) *root = temp; else { // get the front node of the queue. node* front = getFront(queue); // If the left child of this front node doesn’t exist, set the // left child as the new node if (!front->left) front->left = temp; // If the right child of this front node doesn’t exist, set the // right child as the new node else if (!front->right) front->right = temp; // If the front node has both the left child and right child, // Dequeue() it. if (hasBothChild(front)) Dequeue(queue); } // Enqueue() the new node for later insertions Enqueue(temp, queue);} // Standard level order traversal to test above functionvoid levelOrder(node* root){ Queue* queue = createQueue(SIZE); Enqueue(root, queue); while (!isEmpty(queue)) { node* temp = Dequeue(queue); cout<<temp->data<<\" \"; if (temp->left) Enqueue(temp->left, queue); if (temp->right) Enqueue(temp->right, queue); }} // Driver program to test above functionsint main(){ node* root = NULL; Queue* queue = createQueue(SIZE); int i; for(i = 1; i <= 12; ++i) insert(&root, i, queue); levelOrder(root); return 0;} //This code is contributed by rathbhupendra", "e": 33653, "s": 30422, "text": null }, { "code": "# Program for linked implementation# of complete binary tree # For Queue SizeSIZE = 50 # A tree nodeclass node: def __init__(self, data): self.data = data self.right = None self.left = None # A queue nodeclass Queue: def __init__(self): self.front = None self.rear = None self.size = 0 self.array = [] # A utility function to# create a new tree nodedef newNode(data): temp = node(data) return temp # A utility function to# create a new Queuedef createQueue(size): global queue queue = Queue(); queue.front = queue.rear = -1; queue.size = size; queue.array = [None for i in range(size)] return queue; # Standard Queue Functionsdef isEmpty(queue): return queue.front == -1 def isFull(queue): return queue.rear == queue.size - 1; def hasOnlyOneItem(queue): return queue.front == queue.rear; def Enqueue(root): if (isFull(queue)): return; queue.rear+=1 queue.array[queue.rear] = root; if (isEmpty(queue)): queue.front+=1; def Dequeue(): if (isEmpty(queue)): return None; temp = queue.array[queue.front]; if(hasOnlyOneItem(queue)): queue.front = queue.rear = -1; else: queue.front+=1 return temp; def getFront(queue): return queue.array[queue.front]; # A utility function to check# if a tree node has both left# and right childrendef hasBothChild(temp): return (temp and temp.left and temp.right); # Function to insert a new# node in complete binary treedef insert(root, data, queue): # Create a new node for # given data temp = newNode(data); # If the tree is empty, # initialize the root # with new node. if not root: root = temp; else: # get the front node of # the queue. front = getFront(queue); # If the left child of this # front node doesn’t exist, # set the left child as the # new node if (not front.left): front.left = temp; # If the right child of this # front node doesn’t exist, set # the right child as the new node elif (not front.right): front.right = temp; # If the front node has both the # left child and right child, # Dequeue() it. if (hasBothChild(front)): Dequeue(); # Enqueue() the new node for # later insertions Enqueue(temp); return root # Standard level order# traversal to test above# functiondef levelOrder(root): queue = createQueue(SIZE); Enqueue(root); while (not isEmpty(queue)): temp = Dequeue(); print(temp.data, end = ' ') if (temp.left): Enqueue(temp.left); if (temp.right): Enqueue(temp.right); # Driver code if __name__ == \"__main__\": root = None queue = createQueue(SIZE); for i in range(1, 13): root=insert(root, i, queue); levelOrder(root); # This code is contributed by Rutvik_56", "e": 36743, "s": 33653, "text": null }, { "code": null, "e": 36777, "s": 36743, "text": "1 2 3 4 5 6 7 8 9 10 11 12\n\n\n\n\n\n\n" }, { "code": null, "e": 36985, "s": 36779, "text": "This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36999, "s": 36985, "text": "rathbhupendra" }, { "code": null, "e": 37009, "s": 36999, "text": "rutvik_56" }, { "code": null, "e": 37030, "s": 37009, "text": "Complete Binary Tree" }, { "code": null, "e": 37035, "s": 37030, "text": "Tree" }, { "code": null, "e": 37040, "s": 37035, "text": "Tree" }, { "code": null, "e": 37138, "s": 37040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37147, "s": 37138, "text": "Comments" }, { "code": null, "e": 37160, "s": 37147, "text": "Old Comments" }, { "code": null, "e": 37196, "s": 37160, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 37236, "s": 37196, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 37274, "s": 37236, "text": "Difference between B tree and B+ tree" }, { "code": null, "e": 37341, "s": 37274, "text": "Construct Complete Binary Tree from its Linked List Representation" }, { "code": null, "e": 37383, "s": 37341, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 37424, "s": 37383, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 37480, "s": 37424, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 37537, "s": 37480, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 37582, "s": 37537, "text": "Binary Tree to Binary Search Tree Conversion" } ]
Python - Join tuple elements in a list
In this article, we are going to learn how to join tuple elements in a list. It's a straightforward thing using join and map methods. Follow the below steps to complete the task. Initialize list with tuples that contain strings. Write a function called join_tuple_string that takes a tuple as arguments and return a string. Join the tuples in the list using map(join_tuple_string, list) method. Convert the result to list. Print the result. # initializing the list with tuples string_tuples = [('A', 'B', 'C'), ('Tutorialspoint', 'is a', 'popular', 'site', 'for tech learnings')] # function that converts tuple to string def join_tuple_string(strings_tuple) -> str: return ' '.join(strings_tuple) # joining all the tuples result = map(join_tuple_string, string_tuples) # converting and printing the result print(list(result)) If you run the above code, then you will get the following result. ['A B C', 'Tutorialspoint is a popular site for tech learnings'] If you have any queries in the article, mention them in the comment section.
[ { "code": null, "e": 1241, "s": 1062, "text": "In this article, we are going to learn how to join tuple elements in a list. It's a straightforward thing using join and map methods. Follow the below steps to complete the task." }, { "code": null, "e": 1291, "s": 1241, "text": "Initialize list with tuples that contain strings." }, { "code": null, "e": 1386, "s": 1291, "text": "Write a function called join_tuple_string that takes a tuple as arguments and return a string." }, { "code": null, "e": 1457, "s": 1386, "text": "Join the tuples in the list using map(join_tuple_string, list) method." }, { "code": null, "e": 1485, "s": 1457, "text": "Convert the result to list." }, { "code": null, "e": 1503, "s": 1485, "text": "Print the result." }, { "code": null, "e": 1894, "s": 1503, "text": "# initializing the list with tuples\nstring_tuples = [('A', 'B', 'C'), ('Tutorialspoint', 'is a', 'popular', 'site', 'for tech learnings')]\n\n# function that converts tuple to string\ndef join_tuple_string(strings_tuple) -> str:\n return ' '.join(strings_tuple)\n\n# joining all the tuples\nresult = map(join_tuple_string, string_tuples)\n\n# converting and printing the result\nprint(list(result))" }, { "code": null, "e": 1961, "s": 1894, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2027, "s": 1961, "text": "['A B C', 'Tutorialspoint is a popular site for tech learnings']\n" }, { "code": null, "e": 2104, "s": 2027, "text": "If you have any queries in the article, mention them in the comment section." } ]
Hide scroll bar, but while still being able to scroll using CSS - GeeksforGeeks
30 Jul, 2021 To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below: -webkit- (Chrome, Safari, newer versions of Opera):.element::-webkit-scrollbar { width: 0 !important } .element::-webkit-scrollbar { width: 0 !important } -moz- (Firefox):.element { overflow: -moz-scrollbars-none; } .element { overflow: -moz-scrollbars-none; } -ms- (Internet Explorer +10):.element { -ms-overflow-style: none; } .element { -ms-overflow-style: none; } Important Points to be considered before hiding the Scroll bar : Preferably Hide scrollbars only when if all content is visible else user may skip the contentAvoid horizontal scrolling on Web pages and do not hide horizontal scroll bar as they can make content difficult to readIf at all , hiding scroll is required : Display all important information above the fold. Users may often decide if they want to stay or not on what they can see without scrolling.Note: The practical example of hiding the scroll bar is Facebook chat window.Example:<!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> Output:Example:<!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png"> </div> </div> </div> </body></html> Output:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave Preferably Hide scrollbars only when if all content is visible else user may skip the content Avoid horizontal scrolling on Web pages and do not hide horizontal scroll bar as they can make content difficult to read If at all , hiding scroll is required : Display all important information above the fold. Users may often decide if they want to stay or not on what they can see without scrolling.Note: The practical example of hiding the scroll bar is Facebook chat window.Example:<!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> Output:Example:<!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png"> </div> </div> </div> </body></html> Output:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave Note: The practical example of hiding the scroll bar is Facebook chat window. Example: <!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> Output: Example: <!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class="outer-border"> <div class="inner-border"> <div class="content"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png"> </div> </div> </div> </body></html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24359, "s": 24331, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24564, "s": 24359, "text": "To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:" }, { "code": null, "e": 24667, "s": 24564, "text": "-webkit- (Chrome, Safari, newer versions of Opera):.element::-webkit-scrollbar { width: 0 !important }" }, { "code": null, "e": 24719, "s": 24667, "text": ".element::-webkit-scrollbar { width: 0 !important }" }, { "code": null, "e": 24780, "s": 24719, "text": "-moz- (Firefox):.element { overflow: -moz-scrollbars-none; }" }, { "code": null, "e": 24825, "s": 24780, "text": ".element { overflow: -moz-scrollbars-none; }" }, { "code": null, "e": 24893, "s": 24825, "text": "-ms- (Internet Explorer +10):.element { -ms-overflow-style: none; }" }, { "code": null, "e": 24932, "s": 24893, "text": ".element { -ms-overflow-style: none; }" }, { "code": null, "e": 24997, "s": 24932, "text": "Important Points to be considered before hiding the Scroll bar :" }, { "code": null, "e": 28449, "s": 24997, "text": "Preferably Hide scrollbars only when if all content is visible else user may skip the contentAvoid horizontal scrolling on Web pages and do not hide horizontal scroll bar as they can make content difficult to readIf at all , hiding scroll is required : Display all important information above the fold. Users may often decide if they want to stay or not on what they can see without scrolling.Note: The practical example of hiding the scroll bar is Facebook chat window.Example:<!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> Output:Example:<!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png\"> </div> </div> </div> </body></html> Output:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28543, "s": 28449, "text": "Preferably Hide scrollbars only when if all content is visible else user may skip the content" }, { "code": null, "e": 28664, "s": 28543, "text": "Avoid horizontal scrolling on Web pages and do not hide horizontal scroll bar as they can make content difficult to read" }, { "code": null, "e": 31903, "s": 28664, "text": "If at all , hiding scroll is required : Display all important information above the fold. Users may often decide if they want to stay or not on what they can see without scrolling.Note: The practical example of hiding the scroll bar is Facebook chat window.Example:<!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> Output:Example:<!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png\"> </div> </div> </div> </body></html> Output:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31981, "s": 31903, "text": "Note: The practical example of hiding the scroll bar is Facebook chat window." }, { "code": null, "e": 31990, "s": 31981, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> .content, .outer-border { width: 240px; height: 150px; text-align:justify; background-color:green; color:white; padding-left:10px; padding-right:10px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\">GeeksforGeeks is a computer science portal. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free onlineplacement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </div> </div> </div> </body></html> ", "e": 33377, "s": 31990, "text": null }, { "code": null, "e": 33385, "s": 33377, "text": "Output:" }, { "code": null, "e": 33394, "s": 33385, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>hide scrollbar</title> <style> .content, .outer-border { width: 500px; height: 210px; } .outer-border { border: 2px solid black; position: relative; overflow: hidden; } .inner-border { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-border::-webkit-scrollbar { display: none; } </style> </head> <body> <div class=\"outer-border\"> <div class=\"inner-border\"> <div class=\"content\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-73-1.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/Screenshot-74-4.png\"> </div> </div> </div> </body></html> ", "e": 34411, "s": 33394, "text": null }, { "code": null, "e": 34419, "s": 34411, "text": "Output:" }, { "code": null, "e": 34613, "s": 34419, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 34799, "s": 34613, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 34936, "s": 34799, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34945, "s": 34936, "text": "CSS-Misc" }, { "code": null, "e": 34952, "s": 34945, "text": "Picked" }, { "code": null, "e": 34976, "s": 34952, "text": "Technical Scripter 2018" }, { "code": null, "e": 34980, "s": 34976, "text": "CSS" }, { "code": null, "e": 34985, "s": 34980, "text": "HTML" }, { "code": null, "e": 35004, "s": 34985, "text": "Technical Scripter" }, { "code": null, "e": 35021, "s": 35004, "text": "Web Technologies" }, { "code": null, "e": 35026, "s": 35021, "text": "HTML" }, { "code": null, "e": 35124, "s": 35026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35133, "s": 35124, "text": "Comments" }, { "code": null, "e": 35146, "s": 35133, "text": "Old Comments" }, { "code": null, "e": 35208, "s": 35146, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35258, "s": 35208, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35316, "s": 35258, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 35364, "s": 35316, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35401, "s": 35364, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 35463, "s": 35401, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35513, "s": 35463, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35573, "s": 35513, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35621, "s": 35573, "text": "How to update Node.js and NPM to next version ?" } ]
Check that the element is clickable or not in Selenium WebDriver
We can check if the element is clickable or not in Selenium webdriver using synchronization. In synchronization, there is an explicit wait where the driver waits till an expected condition for an element is met. To verify, if the element can be clicked, we shall use the elementToBeClickable condition. A timeout exception is thrown if the criteria for the element is not satisfied till the driver wait time. WebDriverWait wt = new WebDriverWait(driver, 5); wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy"))); We have to add - import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait statements to implement ExpectedConditions in our code. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ElemntClickable{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); WebElement n=driver.findElement(By.className("mui-btn")); n.click(); // explicit wait WebDriverWait wt = new WebDriverWait(driver,6); // elementToBeClickable expected criteria wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy"))); System.out.println("Current page title:" + driver.getTitle()); driver.close(); } }
[ { "code": null, "e": 1274, "s": 1062, "text": "We can check if the element is clickable or not in Selenium webdriver using synchronization. In synchronization, there is an explicit wait where the driver waits till an expected condition for an element is met." }, { "code": null, "e": 1471, "s": 1274, "text": "To verify, if the element can be clicked, we shall use the elementToBeClickable condition. A timeout exception is thrown if the criteria for the element is not satisfied till the driver wait time." }, { "code": null, "e": 1595, "s": 1471, "text": "WebDriverWait wt = new WebDriverWait(driver, 5);\nwt.until(ExpectedConditions.elementToBeClickable (By.className(\"s-buy\")));" }, { "code": null, "e": 1781, "s": 1595, "text": "We have to add - import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait statements to implement ExpectedConditions in our code." }, { "code": null, "e": 2871, "s": 1781, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class ElemntClickable{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n WebElement n=driver.findElement(By.className(\"mui-btn\"));\n n.click();\n // explicit wait\n WebDriverWait wt = new WebDriverWait(driver,6);\n // elementToBeClickable expected criteria\n wt.until(ExpectedConditions.elementToBeClickable (By.className(\"s-buy\")));\n System.out.println(\"Current page title:\" + driver.getTitle());\n driver.close();\n }\n}" } ]
XML DOM - Add Node
In this chapter, we will discuss the nodes to the existing element. It provides a means to − append new child nodes before or after the existing child nodes append new child nodes before or after the existing child nodes insert data within the text node insert data within the text node add attribute node add attribute node Following methods can be used to add/append the nodes to an element in a DOM − appendChild() insertBefore() insertData() The method appendChild() adds the new child node after the existing child node. Syntax of appendChild() method is as follows − Node appendChild(Node newChild) throws DOMException Where, newChild − Is the node to add newChild − Is the node to add This method returns the Node added. This method returns the Node added. The following example (appendchildnode_example.htm) parses an XML document (node.xml) into an XML DOM object and appends new child PhoneNo to the element <FirstName>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("PhoneNo"); x = xmlDoc.getElementsByTagName("FirstName")[0]; x.appendChild(create_e); document.write(x.getElementsByTagName("PhoneNo")[0].nodeName); </script> </body> </html> In the above example − using the method createElement(), a new element PhoneNo is created. using the method createElement(), a new element PhoneNo is created. The new element PhoneNo is added to the element FirstName using the method appendChild(). The new element PhoneNo is added to the element FirstName using the method appendChild(). Save this file as appendchildnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as PhoneNo. The method insertBefore(), inserts the new child nodes before the specified child nodes. Syntax of insertBefore() method is as follows − Node insertBefore(Node newChild, Node refChild) throws DOMException Where, newChild − Is the node to insert newChild − Is the node to insert refChild − Is the reference node, i.e., the node before which the new node must be inserted. refChild − Is the reference node, i.e., the node before which the new node must be inserted. This method returns the Node being inserted. This method returns the Node being inserted. The following example (insertnodebefore_example.htm) parses an XML document (node.xml) into an XML DOM object and inserts new child Email before the specified element <Email>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("Email"); x = xmlDoc.documentElement; y = xmlDoc.getElementsByTagName("Email"); document.write("No of Email elements before inserting was: " + y.length); document.write("<br>"); x.insertBefore(create_e,y[3]); y=xmlDoc.getElementsByTagName("Email"); document.write("No of Email elements after inserting is: " + y.length); </script> </body> </html> In the above example − using the method createElement(), a new element Email is created. using the method createElement(), a new element Email is created. The new element Email is added before the element Email using the method insertBefore(). The new element Email is added before the element Email using the method insertBefore(). y.length gives the total number of elements added before and after the new element. y.length gives the total number of elements added before and after the new element. Save this file as insertnodebefore_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following output − No of Email elements before inserting was: 3 No of Email elements after inserting is: 4 The method insertData(), inserts a string at the specified 16-bit unit offset. The insertData() has the following syntax − void insertData(int offset, java.lang.String arg) throws DOMException Where, offset − is the character offset at which to insert. offset − is the character offset at which to insert. arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma. arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma. The following example (addtext_example.htm) parses an XML document ("node.xml") into an XML DOM object and inserts new data MiddleName at the specified position to the element <FirstName>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0]; document.write(x.nodeValue); x.insertData(6,"MiddleName"); document.write("<br>"); document.write(x.nodeValue); </script> </body> </html> x.insertData(6,"MiddleName"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data "MiddleName" starting from position 6. x.insertData(6,"MiddleName"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data "MiddleName" starting from position 6. Save this file as addtext_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following in the output − Tanmay TanmayMiddleName 41 Lectures 5 hours Abhishek And Pukhraj 33 Lectures 3.5 hours Abhishek And Pukhraj 15 Lectures 1 hours Zach Miller 15 Lectures 4 hours Prof. Paul Cline, Ed.D 13 Lectures 4 hours Prof. Paul Cline, Ed.D 17 Lectures 2 hours Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2288, "text": "In this chapter, we will discuss the nodes to the existing element. It provides a means to −" }, { "code": null, "e": 2445, "s": 2381, "text": "append new child nodes before or after the existing child nodes" }, { "code": null, "e": 2509, "s": 2445, "text": "append new child nodes before or after the existing child nodes" }, { "code": null, "e": 2542, "s": 2509, "text": "insert data within the text node" }, { "code": null, "e": 2575, "s": 2542, "text": "insert data within the text node" }, { "code": null, "e": 2594, "s": 2575, "text": "add attribute node" }, { "code": null, "e": 2613, "s": 2594, "text": "add attribute node" }, { "code": null, "e": 2692, "s": 2613, "text": "Following methods can be used to add/append the nodes to an element in a DOM −" }, { "code": null, "e": 2706, "s": 2692, "text": "appendChild()" }, { "code": null, "e": 2721, "s": 2706, "text": "insertBefore()" }, { "code": null, "e": 2734, "s": 2721, "text": "insertData()" }, { "code": null, "e": 2814, "s": 2734, "text": "The method appendChild() adds the new child node after the existing child node." }, { "code": null, "e": 2861, "s": 2814, "text": "Syntax of appendChild() method is as follows −" }, { "code": null, "e": 2914, "s": 2861, "text": "Node appendChild(Node newChild) throws DOMException\n" }, { "code": null, "e": 2921, "s": 2914, "text": "Where," }, { "code": null, "e": 2951, "s": 2921, "text": "newChild − Is the node to add" }, { "code": null, "e": 2981, "s": 2951, "text": "newChild − Is the node to add" }, { "code": null, "e": 3017, "s": 2981, "text": "This method returns the Node added." }, { "code": null, "e": 3053, "s": 3017, "text": "This method returns the Node added." }, { "code": null, "e": 3220, "s": 3053, "text": "The following example (appendchildnode_example.htm) parses an XML document (node.xml) into an XML DOM object and appends new child PhoneNo to the element <FirstName>." }, { "code": null, "e": 3992, "s": 3220, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"PhoneNo\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n x.appendChild(create_e);\n\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 4015, "s": 3992, "text": "In the above example −" }, { "code": null, "e": 4083, "s": 4015, "text": "using the method createElement(), a new element PhoneNo is created." }, { "code": null, "e": 4151, "s": 4083, "text": "using the method createElement(), a new element PhoneNo is created." }, { "code": null, "e": 4241, "s": 4151, "text": "The new element PhoneNo is added to the element FirstName using the method appendChild()." }, { "code": null, "e": 4331, "s": 4241, "text": "The new element PhoneNo is added to the element FirstName using the method appendChild()." }, { "code": null, "e": 4518, "s": 4331, "text": "Save this file as appendchildnode_example.htm on the server path (this file and node.xml should be on the same path in your server). In the output, we get the attribute value as PhoneNo." }, { "code": null, "e": 4607, "s": 4518, "text": "The method insertBefore(), inserts the new child nodes before the specified child nodes." }, { "code": null, "e": 4655, "s": 4607, "text": "Syntax of insertBefore() method is as follows −" }, { "code": null, "e": 4724, "s": 4655, "text": "Node insertBefore(Node newChild, Node refChild) throws DOMException\n" }, { "code": null, "e": 4731, "s": 4724, "text": "Where," }, { "code": null, "e": 4764, "s": 4731, "text": "newChild − Is the node to insert" }, { "code": null, "e": 4797, "s": 4764, "text": "newChild − Is the node to insert" }, { "code": null, "e": 4890, "s": 4797, "text": "refChild − Is the reference node, i.e., the node before which the new node must be inserted." }, { "code": null, "e": 4983, "s": 4890, "text": "refChild − Is the reference node, i.e., the node before which the new node must be inserted." }, { "code": null, "e": 5028, "s": 4983, "text": "This method returns the Node being inserted." }, { "code": null, "e": 5073, "s": 5028, "text": "This method returns the Node being inserted." }, { "code": null, "e": 5249, "s": 5073, "text": "The following example (insertnodebefore_example.htm) parses an XML document (node.xml) into an XML DOM object and inserts new child Email before the specified element <Email>." }, { "code": null, "e": 6230, "s": 5249, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"Email\");\n\n x = xmlDoc.documentElement;\n y = xmlDoc.getElementsByTagName(\"Email\");\n\n document.write(\"No of Email elements before inserting was: \" + y.length);\n document.write(\"<br>\");\n x.insertBefore(create_e,y[3]);\n\n y=xmlDoc.getElementsByTagName(\"Email\");\n document.write(\"No of Email elements after inserting is: \" + y.length);\n </script>\n </body>\n</html>" }, { "code": null, "e": 6253, "s": 6230, "text": "In the above example −" }, { "code": null, "e": 6319, "s": 6253, "text": "using the method createElement(), a new element Email is created." }, { "code": null, "e": 6385, "s": 6319, "text": "using the method createElement(), a new element Email is created." }, { "code": null, "e": 6474, "s": 6385, "text": "The new element Email is added before the element Email using the method insertBefore()." }, { "code": null, "e": 6563, "s": 6474, "text": "The new element Email is added before the element Email using the method insertBefore()." }, { "code": null, "e": 6647, "s": 6563, "text": "y.length gives the total number of elements added before and after the new element." }, { "code": null, "e": 6731, "s": 6647, "text": "y.length gives the total number of elements added before and after the new element." }, { "code": null, "e": 6904, "s": 6731, "text": "Save this file as insertnodebefore_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following output −" }, { "code": null, "e": 6994, "s": 6904, "text": "No of Email elements before inserting was: 3\nNo of Email elements after inserting is: 4 \n" }, { "code": null, "e": 7073, "s": 6994, "text": "The method insertData(), inserts a string at the specified 16-bit unit offset." }, { "code": null, "e": 7117, "s": 7073, "text": "The insertData() has the following syntax −" }, { "code": null, "e": 7188, "s": 7117, "text": "void insertData(int offset, java.lang.String arg) throws DOMException\n" }, { "code": null, "e": 7195, "s": 7188, "text": "Where," }, { "code": null, "e": 7248, "s": 7195, "text": "offset − is the character offset at which to insert." }, { "code": null, "e": 7301, "s": 7248, "text": "offset − is the character offset at which to insert." }, { "code": null, "e": 7435, "s": 7301, "text": "arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma." }, { "code": null, "e": 7569, "s": 7435, "text": "arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma." }, { "code": null, "e": 7758, "s": 7569, "text": "The following example (addtext_example.htm) parses an XML document (\"node.xml\") into an XML DOM object and inserts new data MiddleName at the specified position to the element <FirstName>." }, { "code": null, "e": 8521, "s": 7758, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0];\n document.write(x.nodeValue);\n x.insertData(6,\"MiddleName\");\n document.write(\"<br>\");\n document.write(x.nodeValue);\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 8704, "s": 8521, "text": "x.insertData(6,\"MiddleName\"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data \"MiddleName\" starting from position 6." }, { "code": null, "e": 8887, "s": 8704, "text": "x.insertData(6,\"MiddleName\"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data \"MiddleName\" starting from position 6." }, { "code": null, "e": 9058, "s": 8887, "text": "Save this file as addtext_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following in the output −" }, { "code": null, "e": 9084, "s": 9058, "text": "Tanmay\nTanmayMiddleName \n" }, { "code": null, "e": 9117, "s": 9084, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 9139, "s": 9117, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9174, "s": 9139, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9196, "s": 9174, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9229, "s": 9196, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 9242, "s": 9229, "text": " Zach Miller" }, { "code": null, "e": 9275, "s": 9242, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 9299, "s": 9275, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 9332, "s": 9299, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 9356, "s": 9332, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 9389, "s": 9356, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 9406, "s": 9389, "text": " Laurence Svekis" }, { "code": null, "e": 9413, "s": 9406, "text": " Print" }, { "code": null, "e": 9424, "s": 9413, "text": " Add Notes" } ]
Grid Search with/without Sklearn code | Towards Data Science
Table of Contents 1. Introduction2. Grid Search without Sklearn Library3. Grid Search with Sklearn Library4. Grid Search with Validation Dataset5. Grid Search with Cross-Validation6. Customized Grid Search7. Different Cross-Validation types in Grid Search8. Nested Cross-Validation9. Summary The model and the preprocessing are individual for each project. Hyperparameters are tuned according to the dataset and using the same hyperparameters for each project compromises the accuracy of the results. For example, there are different hyperparameters such as ‘solver’, ‘C’, ‘penalty’ in the Logistic Regression algorithm, and different combinations of these give different results. Similarly, there are adjustable parameters for Support Vector Machine such as gamma value, C value, and combination of them also gives different results. These hyperparameters of the algorithms are available on the sklearn website. The goal of the developer is to design a model with generalizing as well as high accuracy so, detection of the best combination of hyperparameters is important for improving accuracy. This article involves evaluating all combinations of hypermeters to improve the accuracy of the model and the reliability of the resulting accuracy. Combinations that are requested to be evaluated by the user are tested with the GridSearchCV in the Sklearn library. In fact, the model fits each combination individually, revealing the best result and parameters. For example, when we consider LogisticRegression, if 4 different values are selected for C and 2 different values are selected for penalty, the model will fit 8 times and the result of each will represent. Now let’s create a grid search on the cancer dataset without using the sklearn library: IN[1]cancer=load_breast_cancer()cancer_data =cancer.datacancer_target =cancer.targetIN[2]x_train,x_test,y_train,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)best_lr=0for C in [0.001,0.1,1,10]: for penalty in ['l1','l2']: lr=LogisticRegression(solver='saga',C=C,penalty=penalty) lr.fit(x_train,y_train) lr_score=lr.score(x_test,y_test) print("C: ",C,"penalty:",penalty,'acc {:.3f}'.format(lr_score)) if lr_score>best_lr: best_lr=lr_score best_lr_combination=(C,penalty)print("best score LogisticRegression",best_lr)print("C and penalty",best_lr_combination)OUT[2]C: 0.001 penalty: l1 acc:0.912C: 0.001 penalty: l2 acc:0.895C: 0.1 penalty: l1 acc:0.904C: 0.1 penalty: l2 acc:0.904C: 1 penalty: l1 acc:0.895C: 1 penalty: l2 acc:0.904C: 10 penalty: l1 acc:0.904C: 10 penalty: l2 acc:0.904best score LogisticRegression 0.9122807017543859C and penalty (0.001, 'l1') All hyperparameters and more for Logistic Regression can be accessed from this link. As can be seen, the accuracy value was created for each combination. The developer can improve the accuracy of the model by choosing the best combination of hyperparameters. OUT[2] indicates the best combination of hyperparameters is C=0.001 and penalty=L1. Let’s create the same process using Support Vector Classifier and Decision Tree Classifier. IN[3]#SVCbest_svc=0for gamma in [0.001,0.1,1,100]: for C in[0.01,0.1,1,100]: svm=SVC(gamma=gamma,C=C) svm.fit(x_train,y_train) score=svm.score(x_test,y_test) #print("gamma:",gamma,"C:",C,"acc",score) if score>best_svc: best_svc=score best_svc_combination=(gamma, C)print("best score SVM",best_svc)print("gamma and C",best_svc_combination)OUT[3]best score SVM 0.9210526315789473gamma and C (0.001, 100)IN[4]#DTbest_dt=0for max_depth in [1,2,3,5,7,9,11,13,15]: dt = DecisionTreeClassifier(max_depth=max_depth, random_state=2021) dt.fit(x_train,y_train) dt_score=dt.score(x_test,y_test) #print("max_depth:",max_depth,dt_score) if dt_score>best_dt: best_dt=dt_score best_dt_depth=(max_depth) print("best dt_score:",best_dt)print("best dt depth:", best_dt_depth)OUT[4]best dt_score: 0.9473684210526315best dt depth: 3 All hyperparameters and more for Decision Tree Classifier can be accessed from this link and for Support Vector Classifier from this link. OUT[3] indicates the best combination for SVC is gamma=0.001 and C=100. OUT[4] indicates the best combination for DTC is max_depth=3. Let’s do the same using the sklearn library: IN[5]param_grid_lr = {'C': [0.001,0.1,1,10],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr)x_train,x_test,y_train,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)gs_lr.fit(x_train,y_train)test_score=gs_lr.score(x_test,y_test)print("test score:",test_score)print("best combination: ",gs_lr.best_params_)print("best score: ", gs_lr.best_score_)print("best all parameters:",gs_lr.best_estimator_)print("everything ",gs_lr.cv_results_)OUT[5]test score: 0.9122807017543859best combination: {'C': 0.001, 'penalty': 'l1'}best score: 0.9054945054945055best all parameters: LogisticRegression(C=0.001, penalty='l1', solver='saga') The dataset is split with the train_test_split as above. The training dataset has been trained with a Logistic Regression algorithm with various combinations of hyperparameters by using GridSearchCV. It is seen that the accuracy rate and the best parameters are the same as above. GridSearchCV has a lot of attributes and all of these are available on the sklearn website. In previous studies, data were separated as test set and training set. The training dataset was tried with all combinations and the highest rate was applied to the test dataset. However, it is explained in this link that splitting train_test_split with random is a gamble and may not give reliable results. Now, after separating the data as training set and test set to increase reliability, let’s separate the training dataset as training set and validation set. Let’s train the model with a training dataset and evaluate with validation data, and after determining the most suitable hyperparameters for the model, apply it to the test dataset that was originally allocated. Even if the accuracy value is lower, the model would be more generalized. This is preferable to the fake high accuracy. IN[6]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)x_train,x_val,y_train,y_val=train_test_split(x_valtrain,y_valtrain,test_size=0.2,random_state=2021)param_grid_lr = {'C': [0.001,0.1,1,10],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr)gs_lr.fit(x_train,y_train)val_score=gs_lr.score(x_val,y_val)print("val score:",val_score)print("best parameters: ",gs_lr.best_params_)print("best score: ", gs_lr.best_score_)new_lr=LogisticRegression(solver='saga', C=0.001, penalty='l2').fit(x_valtrain,y_valtrain)test_score=new_lr.score(x_test,y_test)print("test score", test_score)OUT[6]val score: 0.9010989010989011best parameters: {'C': 0.001, 'penalty': 'l2'}best score: 0.9092465753424659test score 0.9035087719298246 It was trained with a training dataset(x_train, y_train), evaluated with a validation dataset(x_val, y_val), and the best combination was determined. Then, the new model was created with the best combination was fit with the train dataset +validation dataset, more data was used, and finally, it was evaluated with the test dataset which is allocated in the first split. The same process can be done without using sklearn or by following the template above for other algorithms. The dataset is divided into a training set and a test set. Separation of the training dataset as training set + validation set is done by cross-validation. Let’s implement it without using the sklearn library to understand the system: IN[7]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)best_lr=0for C in [0.001,0.1,1,10]: for penalty in ['l1','l2']: lr=LogisticRegression(solver='saga',C=C,penalty=penalty) cv_scores=cross_val_score(lr,x_valtrain,y_valtrain,cv=5) mean_score=np.mean(cv_scores) if mean_score>best_lr: best_lr=mean_score best_lr_parameters=(C,penalty)print("best score LogisticRegression",best_lr)print("C and penalty",best_lr_parameters)print("**************************************")new_cv_lr=LogisticRegression(solver='saga',C=0.001,penalty='l1').fit(x_valtrain,y_valtrain)new_cv_score=new_cv_lr.score(x_test,y_test)print('test accuracy:',new_cv_score)OUT[7]best score LogisticRegression 0.9054945054945055C and penalty (0.001, 'l1')**************************************test accuracy: 0.9122807017543859 The x_valtrain(train+validation) dataset is split with the value CV=5 and the test data originally allocated is applied to the reconstructed model with the best parameters. The same process can be applied with the sklearn library: IN[8]param_grid_lr = {'C': [0.001,0.1,1,10,100],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr,cv=5)x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)gs_lr.fit(x_valtrain,y_valtrain)gs_lr_score=gs_lr.score(x_test,y_test)print('test acc:',gs_lr_score)print("best parameters: ",gs_lr.best_params_)print("best score: ", gs_lr.best_score_)OUT[8]test acc: 0.9122807017543859best parameters: {'C': 0.001, 'penalty': 'l1'}best score: 0.9054945054945055best all parameters LogisticRegression(C=0.001, penalty='l1', solver='saga') It is seen that the same results and the same best parameters were obtained. A combination of parameters is possible as long as it is allowed. Some parameters cannot be combined with each other. For example, when solver:’saga’ is selected in LogisticRegression, ‘L1’, ‘L2’ and ‘elasticnet’ can be applied, however for solver:’lbfgs’, the only penalty: ‘L2’ can be applied (or ‘none’). It is possible to overcome this disadvantage with GridSearch as follows: IN[9]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]gs_lr = GridSearchCV(LogisticRegression(),param_grid_lr,cv=5)gs_lr.fit(x_valtrain,y_valtrain)gs_lr_score=gs_lr.score(x_test,y_test)print("test score:",gs_lr_score)print("best parameters: ",gs_lr.best_params_)print("best score: ", gs_lr.best_score_)OUT[9]test score: 0.9210526315789473best parameters: {'C': 1, 'penalty': 'l2', 'solver': 'lbfgs'}best score: 0.9516483516483516 The new model was created according to the selected best parameters and the test data was applied by GridSearchCV. Cross-validation has been implemented as k-fold so far, but it is also possible to apply different cross-validation methods: IN[10]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]IN[11]gs_lr_loo = GridSearchCV(LogisticRegression(),param_grid_lr,cv=LeaveOneOut())gs_lr_loo.fit(x_valtrain,y_valtrain)gs_lr_loo_score=gs_lr_loo.score(x_test,y_test)print("loo-test score:",gs_lr_loo_score)print("loo-best parameters: ",gs_lr_loo.best_params_)print("**********************************************")OUT[11]loo-test score: 0.9122807017543859loo-best parameters: {'C': 0.1, 'penalty': 'l2', 'solver': 'lbfgs'}**********************************************IN[12]skf = StratifiedKFold(n_splits=5)gs_lr_skf = GridSearchCV(LogisticRegression(),param_grid_lr,cv=skf)gs_lr_skf.fit(x_valtrain,y_valtrain)gs_lr_skf_score=gs_lr_skf.score(x_test,y_test)print("skf-test score:",gs_lr_skf_score)print("skf-best parameters: ",gs_lr_skf.best_params_)print("**********************************************")OUT[12]skf-test score: 0.9210526315789473skf-best parameters: {'C': 1, 'penalty': 'l2', 'solver': 'lbfgs'}**********************************************IN[13]rkf = RepeatedKFold(n_splits=5, n_repeats=5, random_state=2021)gs_lr_rkf= GridSearchCV(LogisticRegression(),param_grid_lr,cv=rkf)gs_lr_rkf.fit(x_valtrain,y_valtrain)gs_lr_rkf_score=gs_lr_rkf.score(x_test,y_test)print("rkf-test score:",gs_lr_rkf_score)print("rkf-best parameters: ",gs_lr_rkf.best_params_)print("**********************************************")OUT[13]rkf-test score: 0.9298245614035088rkf-best parameters: {'C': 10, 'penalty': 'l2', 'solver': 'lbfgs'}********************************************** While the highest accuracy value was obtained with RepeatedKFold with C=10 and penalty=L2, it was determined that the C values of all the other results with accuracy values close to it were different. Test data has been separated by train_test_split and training data has been split into a training set and validation set with cross-validation so far. To further generalize this method, we can also split the test data with cross-validation: IN[14]param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]gs=GridSearchCV(LogisticRegression(),param_grid_lr,cv=5)nested_scores=cross_val_score(gs,cancer.data,cancer.target,cv=5)print("nested acc",nested_scores)print("Average acc: ", nested_scores.mean())OUT[14]nested acc [0.94736842 0.93859649 0.94736842 0.9122807 0.92920354]Average acc: 0.9349635149821456 For solver=’saga’, there are 3x3 combinations and for solver=’lbfgs’, there are 3x1 combinations. Model is fit 5 times in inner cross-validation and 5 times in outer cross-validation as well. So, the total fit number of the model is 9x5x5 + 3x5x5 = 300. The downside of grid search and cross-validation is that it takes a long time to fit dozens of models. The n_jobs value can be set by the user, and how many CPU cores to use can be assigned. If n_jobs=-1 is set, all available CPU cores are used.
[ { "code": null, "e": 463, "s": 171, "text": "Table of Contents 1. Introduction2. Grid Search without Sklearn Library3. Grid Search with Sklearn Library4. Grid Search with Validation Dataset5. Grid Search with Cross-Validation6. Customized Grid Search7. Different Cross-Validation types in Grid Search8. Nested Cross-Validation9. Summary" }, { "code": null, "e": 1268, "s": 463, "text": "The model and the preprocessing are individual for each project. Hyperparameters are tuned according to the dataset and using the same hyperparameters for each project compromises the accuracy of the results. For example, there are different hyperparameters such as ‘solver’, ‘C’, ‘penalty’ in the Logistic Regression algorithm, and different combinations of these give different results. Similarly, there are adjustable parameters for Support Vector Machine such as gamma value, C value, and combination of them also gives different results. These hyperparameters of the algorithms are available on the sklearn website. The goal of the developer is to design a model with generalizing as well as high accuracy so, detection of the best combination of hyperparameters is important for improving accuracy." }, { "code": null, "e": 1417, "s": 1268, "text": "This article involves evaluating all combinations of hypermeters to improve the accuracy of the model and the reliability of the resulting accuracy." }, { "code": null, "e": 1925, "s": 1417, "text": "Combinations that are requested to be evaluated by the user are tested with the GridSearchCV in the Sklearn library. In fact, the model fits each combination individually, revealing the best result and parameters. For example, when we consider LogisticRegression, if 4 different values are selected for C and 2 different values are selected for penalty, the model will fit 8 times and the result of each will represent. Now let’s create a grid search on the cancer dataset without using the sklearn library:" }, { "code": null, "e": 2893, "s": 1925, "text": "IN[1]cancer=load_breast_cancer()cancer_data =cancer.datacancer_target =cancer.targetIN[2]x_train,x_test,y_train,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)best_lr=0for C in [0.001,0.1,1,10]: for penalty in ['l1','l2']: lr=LogisticRegression(solver='saga',C=C,penalty=penalty) lr.fit(x_train,y_train) lr_score=lr.score(x_test,y_test) print(\"C: \",C,\"penalty:\",penalty,'acc {:.3f}'.format(lr_score)) if lr_score>best_lr: best_lr=lr_score best_lr_combination=(C,penalty)print(\"best score LogisticRegression\",best_lr)print(\"C and penalty\",best_lr_combination)OUT[2]C: 0.001 penalty: l1 acc:0.912C: 0.001 penalty: l2 acc:0.895C: 0.1 penalty: l1 acc:0.904C: 0.1 penalty: l2 acc:0.904C: 1 penalty: l1 acc:0.895C: 1 penalty: l2 acc:0.904C: 10 penalty: l1 acc:0.904C: 10 penalty: l2 acc:0.904best score LogisticRegression 0.9122807017543859C and penalty (0.001, 'l1')" }, { "code": null, "e": 2978, "s": 2893, "text": "All hyperparameters and more for Logistic Regression can be accessed from this link." }, { "code": null, "e": 3236, "s": 2978, "text": "As can be seen, the accuracy value was created for each combination. The developer can improve the accuracy of the model by choosing the best combination of hyperparameters. OUT[2] indicates the best combination of hyperparameters is C=0.001 and penalty=L1." }, { "code": null, "e": 3328, "s": 3236, "text": "Let’s create the same process using Support Vector Classifier and Decision Tree Classifier." }, { "code": null, "e": 4237, "s": 3328, "text": "IN[3]#SVCbest_svc=0for gamma in [0.001,0.1,1,100]: for C in[0.01,0.1,1,100]: svm=SVC(gamma=gamma,C=C) svm.fit(x_train,y_train) score=svm.score(x_test,y_test) #print(\"gamma:\",gamma,\"C:\",C,\"acc\",score) if score>best_svc: best_svc=score best_svc_combination=(gamma, C)print(\"best score SVM\",best_svc)print(\"gamma and C\",best_svc_combination)OUT[3]best score SVM 0.9210526315789473gamma and C (0.001, 100)IN[4]#DTbest_dt=0for max_depth in [1,2,3,5,7,9,11,13,15]: dt = DecisionTreeClassifier(max_depth=max_depth, random_state=2021) dt.fit(x_train,y_train) dt_score=dt.score(x_test,y_test) #print(\"max_depth:\",max_depth,dt_score) if dt_score>best_dt: best_dt=dt_score best_dt_depth=(max_depth) print(\"best dt_score:\",best_dt)print(\"best dt depth:\", best_dt_depth)OUT[4]best dt_score: 0.9473684210526315best dt depth: 3" }, { "code": null, "e": 4376, "s": 4237, "text": "All hyperparameters and more for Decision Tree Classifier can be accessed from this link and for Support Vector Classifier from this link." }, { "code": null, "e": 4510, "s": 4376, "text": "OUT[3] indicates the best combination for SVC is gamma=0.001 and C=100. OUT[4] indicates the best combination for DTC is max_depth=3." }, { "code": null, "e": 4555, "s": 4510, "text": "Let’s do the same using the sklearn library:" }, { "code": null, "e": 5256, "s": 4555, "text": "IN[5]param_grid_lr = {'C': [0.001,0.1,1,10],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr)x_train,x_test,y_train,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)gs_lr.fit(x_train,y_train)test_score=gs_lr.score(x_test,y_test)print(\"test score:\",test_score)print(\"best combination: \",gs_lr.best_params_)print(\"best score: \", gs_lr.best_score_)print(\"best all parameters:\",gs_lr.best_estimator_)print(\"everything \",gs_lr.cv_results_)OUT[5]test score: 0.9122807017543859best combination: {'C': 0.001, 'penalty': 'l1'}best score: 0.9054945054945055best all parameters: LogisticRegression(C=0.001, penalty='l1', solver='saga')" }, { "code": null, "e": 5629, "s": 5256, "text": "The dataset is split with the train_test_split as above. The training dataset has been trained with a Logistic Regression algorithm with various combinations of hyperparameters by using GridSearchCV. It is seen that the accuracy rate and the best parameters are the same as above. GridSearchCV has a lot of attributes and all of these are available on the sklearn website." }, { "code": null, "e": 6425, "s": 5629, "text": "In previous studies, data were separated as test set and training set. The training dataset was tried with all combinations and the highest rate was applied to the test dataset. However, it is explained in this link that splitting train_test_split with random is a gamble and may not give reliable results. Now, after separating the data as training set and test set to increase reliability, let’s separate the training dataset as training set and validation set. Let’s train the model with a training dataset and evaluate with validation data, and after determining the most suitable hyperparameters for the model, apply it to the test dataset that was originally allocated. Even if the accuracy value is lower, the model would be more generalized. This is preferable to the fake high accuracy." }, { "code": null, "e": 7245, "s": 6425, "text": "IN[6]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)x_train,x_val,y_train,y_val=train_test_split(x_valtrain,y_valtrain,test_size=0.2,random_state=2021)param_grid_lr = {'C': [0.001,0.1,1,10],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr)gs_lr.fit(x_train,y_train)val_score=gs_lr.score(x_val,y_val)print(\"val score:\",val_score)print(\"best parameters: \",gs_lr.best_params_)print(\"best score: \", gs_lr.best_score_)new_lr=LogisticRegression(solver='saga', C=0.001, penalty='l2').fit(x_valtrain,y_valtrain)test_score=new_lr.score(x_test,y_test)print(\"test score\", test_score)OUT[6]val score: 0.9010989010989011best parameters: {'C': 0.001, 'penalty': 'l2'}best score: 0.9092465753424659test score 0.9035087719298246" }, { "code": null, "e": 7616, "s": 7245, "text": "It was trained with a training dataset(x_train, y_train), evaluated with a validation dataset(x_val, y_val), and the best combination was determined. Then, the new model was created with the best combination was fit with the train dataset +validation dataset, more data was used, and finally, it was evaluated with the test dataset which is allocated in the first split." }, { "code": null, "e": 7724, "s": 7616, "text": "The same process can be done without using sklearn or by following the template above for other algorithms." }, { "code": null, "e": 7959, "s": 7724, "text": "The dataset is divided into a training set and a test set. Separation of the training dataset as training set + validation set is done by cross-validation. Let’s implement it without using the sklearn library to understand the system:" }, { "code": null, "e": 8865, "s": 7959, "text": "IN[7]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)best_lr=0for C in [0.001,0.1,1,10]: for penalty in ['l1','l2']: lr=LogisticRegression(solver='saga',C=C,penalty=penalty) cv_scores=cross_val_score(lr,x_valtrain,y_valtrain,cv=5) mean_score=np.mean(cv_scores) if mean_score>best_lr: best_lr=mean_score best_lr_parameters=(C,penalty)print(\"best score LogisticRegression\",best_lr)print(\"C and penalty\",best_lr_parameters)print(\"**************************************\")new_cv_lr=LogisticRegression(solver='saga',C=0.001,penalty='l1').fit(x_valtrain,y_valtrain)new_cv_score=new_cv_lr.score(x_test,y_test)print('test accuracy:',new_cv_score)OUT[7]best score LogisticRegression 0.9054945054945055C and penalty (0.001, 'l1')**************************************test accuracy: 0.9122807017543859" }, { "code": null, "e": 9038, "s": 8865, "text": "The x_valtrain(train+validation) dataset is split with the value CV=5 and the test data originally allocated is applied to the reconstructed model with the best parameters." }, { "code": null, "e": 9096, "s": 9038, "text": "The same process can be applied with the sklearn library:" }, { "code": null, "e": 9724, "s": 9096, "text": "IN[8]param_grid_lr = {'C': [0.001,0.1,1,10,100],'penalty': ['l1','l2']}gs_lr=GridSearchCV(LogisticRegression(solver='saga'),param_grid_lr,cv=5)x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)gs_lr.fit(x_valtrain,y_valtrain)gs_lr_score=gs_lr.score(x_test,y_test)print('test acc:',gs_lr_score)print(\"best parameters: \",gs_lr.best_params_)print(\"best score: \", gs_lr.best_score_)OUT[8]test acc: 0.9122807017543859best parameters: {'C': 0.001, 'penalty': 'l1'}best score: 0.9054945054945055best all parameters LogisticRegression(C=0.001, penalty='l1', solver='saga')" }, { "code": null, "e": 9801, "s": 9724, "text": "It is seen that the same results and the same best parameters were obtained." }, { "code": null, "e": 10182, "s": 9801, "text": "A combination of parameters is possible as long as it is allowed. Some parameters cannot be combined with each other. For example, when solver:’saga’ is selected in LogisticRegression, ‘L1’, ‘L2’ and ‘elasticnet’ can be applied, however for solver:’lbfgs’, the only penalty: ‘L2’ can be applied (or ‘none’). It is possible to overcome this disadvantage with GridSearch as follows:" }, { "code": null, "e": 10829, "s": 10182, "text": "IN[9]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]gs_lr = GridSearchCV(LogisticRegression(),param_grid_lr,cv=5)gs_lr.fit(x_valtrain,y_valtrain)gs_lr_score=gs_lr.score(x_test,y_test)print(\"test score:\",gs_lr_score)print(\"best parameters: \",gs_lr.best_params_)print(\"best score: \", gs_lr.best_score_)OUT[9]test score: 0.9210526315789473best parameters: {'C': 1, 'penalty': 'l2', 'solver': 'lbfgs'}best score: 0.9516483516483516" }, { "code": null, "e": 10944, "s": 10829, "text": "The new model was created according to the selected best parameters and the test data was applied by GridSearchCV." }, { "code": null, "e": 11069, "s": 10944, "text": "Cross-validation has been implemented as k-fold so far, but it is also possible to apply different cross-validation methods:" }, { "code": null, "e": 12816, "s": 11069, "text": "IN[10]x_valtrain,x_test,y_valtrain,y_test=train_test_split(cancer_data,cancer_target,test_size=0.2,random_state=2021)param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]IN[11]gs_lr_loo = GridSearchCV(LogisticRegression(),param_grid_lr,cv=LeaveOneOut())gs_lr_loo.fit(x_valtrain,y_valtrain)gs_lr_loo_score=gs_lr_loo.score(x_test,y_test)print(\"loo-test score:\",gs_lr_loo_score)print(\"loo-best parameters: \",gs_lr_loo.best_params_)print(\"**********************************************\")OUT[11]loo-test score: 0.9122807017543859loo-best parameters: {'C': 0.1, 'penalty': 'l2', 'solver': 'lbfgs'}**********************************************IN[12]skf = StratifiedKFold(n_splits=5)gs_lr_skf = GridSearchCV(LogisticRegression(),param_grid_lr,cv=skf)gs_lr_skf.fit(x_valtrain,y_valtrain)gs_lr_skf_score=gs_lr_skf.score(x_test,y_test)print(\"skf-test score:\",gs_lr_skf_score)print(\"skf-best parameters: \",gs_lr_skf.best_params_)print(\"**********************************************\")OUT[12]skf-test score: 0.9210526315789473skf-best parameters: {'C': 1, 'penalty': 'l2', 'solver': 'lbfgs'}**********************************************IN[13]rkf = RepeatedKFold(n_splits=5, n_repeats=5, random_state=2021)gs_lr_rkf= GridSearchCV(LogisticRegression(),param_grid_lr,cv=rkf)gs_lr_rkf.fit(x_valtrain,y_valtrain)gs_lr_rkf_score=gs_lr_rkf.score(x_test,y_test)print(\"rkf-test score:\",gs_lr_rkf_score)print(\"rkf-best parameters: \",gs_lr_rkf.best_params_)print(\"**********************************************\")OUT[13]rkf-test score: 0.9298245614035088rkf-best parameters: {'C': 10, 'penalty': 'l2', 'solver': 'lbfgs'}**********************************************" }, { "code": null, "e": 13017, "s": 12816, "text": "While the highest accuracy value was obtained with RepeatedKFold with C=10 and penalty=L2, it was determined that the C values of all the other results with accuracy values close to it were different." }, { "code": null, "e": 13258, "s": 13017, "text": "Test data has been separated by train_test_split and training data has been split into a training set and validation set with cross-validation so far. To further generalize this method, we can also split the test data with cross-validation:" }, { "code": null, "e": 13721, "s": 13258, "text": "IN[14]param_grid_lr=[{'solver':['saga'],'C':[0.1,1,10],'penalty':['elasticnet','l1','l2']}, {'solver':['lbfgs'],'C':[0.1,1,10],'penalty':['l2']}]gs=GridSearchCV(LogisticRegression(),param_grid_lr,cv=5)nested_scores=cross_val_score(gs,cancer.data,cancer.target,cv=5)print(\"nested acc\",nested_scores)print(\"Average acc: \", nested_scores.mean())OUT[14]nested acc [0.94736842 0.93859649 0.94736842 0.9122807 0.92920354]Average acc: 0.9349635149821456" }, { "code": null, "e": 13913, "s": 13721, "text": "For solver=’saga’, there are 3x3 combinations and for solver=’lbfgs’, there are 3x1 combinations. Model is fit 5 times in inner cross-validation and 5 times in outer cross-validation as well." }, { "code": null, "e": 13975, "s": 13913, "text": "So, the total fit number of the model is 9x5x5 + 3x5x5 = 300." } ]
Tryit Editor v3.7
Tryit: HTML JavaScript
[]
Julia - Files I/O
The functions namely open(), read(), and close() are the standard approach for extracting information from text files. If you want to read text from a text file, you need to first obtain the file handle. It can be done with the help of open() function as follows − foo = open("C://Users//Leekha//Desktop//NLP.txt") It shows that now foo is the Julia’s connection to the text file namely NLP.txt on the disk. Once we are done with the file, we should have to close the connection as follows − Close(foo) In Julia, it is recommended to wrap any file-processing functions inside a do block as follows − open("NLP.txt") do file # here you can work with the open file end The advantage of wrapping file-processing functions inside do block is that the open file will be automatically closed when this block finishes. An example to keep some of the information like total time to read the file and total lines in the files − julia> totaltime, totallines = open("C://Users//Leekha//Desktop//NLP.txt") do foo linecounter = 0 timetaken = @elapsed for l in eachline(foo) linecounter += 1 end (timetaken, linecounter) end (0.0001184, 87) With read() function, we can read the whole content of an open file at once, for example − ABC = read(foo, String) Similarly, the below will store the contents of the file in ABC − julia> ABC = open("C://Users//Leekha//Desktop//NLP.txt") do file read(file, String) end We can also read in the whole file as an array. Use readlines() as follows − julia> foo = open("C://Users//Leekha//Desktop//NLP.txt") IOStream(<file C://Users//Leekha//Desktop//NLP.txt>) julia> lines = readlines(foo) 87-element Array{String,1}: "Natural Language Processing: Semantic Analysis " "" "Introduction to semantic analysis:" "The purpose of semantic analysis is to draw exact meaning, or you can say dictionary meaning from the text. Semantic analyzer checks the text for meaningfulness. ".................................... We can also process a file line by line. For this task, Julia provides a function named eachline() which basically turns a source into an iterator. julia> open("C://USers/Leekha//Desktop//NLP.txt") do file for ln in eachline(file) println("$(length(ln)), $(ln)") end end 47, Natural Language Processing: Semantic Analysis 0, 34, Introduction to semantic analysis: ....................................... If you want to keep a track of which line you are on while reading the file, use the below given approach − julia> open("C://Users//Leekha//Desktop//NLP.txt") do f line = 1 while !eof(f) x = readline(f) println("$line $x") line += 1 end end 1 Natural Language Processing: Semantic Analysis 2 3 Introduction to semantic analysis: 4 The purpose of semantic analysis is to draw exact meaning, or you can say dictionary meaning from the text. Semantic analyzer checks the text for meaningfulness. 5 We know that lexical analysis also deals with the meaning of the words then how semantic analysis is different from lexical analysis? The answer is that Lexical analysis is based on smaller token but on the other side semantic analysis focuses on larger chunks. That is why semantic analysis can be divided into the following two parts: 6 Studying the meaning of individual word: It is the first part of the semantic analysis in which the study of the meaning of individual words is performed. This part is called lexical semantics. 7 Studying the combination of individual words: In this second part, the individual words will be combined to provide meaning in sentences. 8 The most important task of semantic analysis is to get the proper meaning of the sentence. For example, analyze the sentence “Ram is great.” In this sentence, the speaker is talking either about Lord Ram or about a person whose name is Ram. That is why the job, to get the proper meaning of the sentence, of semantic analyzer is important. 9 Elements of semantic analysis: 10 Following are the elements of semantic analysis:.......................... The table below shows functions that are useful for working with filenames − cd(path) This function changes the current directory. pwd() This function gets the current working directory. readdir(path) This function returns a list of the contents of a named directory, or the current directory. abspath(path) This function adds the current directory's path to a filename to make an absolute pathname. joinpath(str, str, ...) This function assembles a pathname from pieces. isdir(path) This function tells you whether the path is a directory. splitdir(path) This function splits a path into a tuple of the directory name and file name. splitdrive(path) This function, on Windows, split a path into the drive letter part and the path part. And, On Unix systems, the first component is always the empty string. splitext(path) This function, if the last component of a path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string. expanduser(path) This function replaces a tilde character at the start of a path with the current user's home directory. normpath(path) This function normalizes a path, removing "." and ".." entries. realpath(path) This function canonicalizes a path by expanding symbolic links and removing "." and ".." entries. homedir() This function gives the current user's home directory. dirname(path) This function gets the directory part of a path. basename(path) This function gets the file name part of a path. We can use stat(“pathname”) to get the information about a specific file. julia> for n in fieldnames(typeof(stat("C://Users//Leekha//Desktop//NLP.txt"))) println(n, ": ", getfield(stat("C://Users//Leekha//Desktop//NLP.txt"),n)) end device: 3262175189 inode: 17276 mode: 33206 nlink: 1 uid: 0 gid: 0 rdev: 0 size: 6293 blksize: 4096 blocks: 16 mtime: 1.6017034024103658e9 ctime: 1.6017034024103658e9 If you want to convert filenames to pathnames, you can use abspath() function. We can map this over a list of files in a directory as follows − julia> map(abspath, readdir()) 204-element Array{String,1}: "C:\\Users\\Leekha\\.anaconda" "C:\\Users\\Leekha\\.conda" "C:\\Users\\Leekha\\.condarc" "C:\\Users\\Leekha\\.config" "C:\\Users\\Leekha\\.idlerc" "C:\\Users\\Leekha\\.ipynb_checkpoints" "C:\\Users\\Leekha\\.ipython" "C:\\Users\\Leekha\\.julia" "C:\\Users\\Leekha\\.jupyter" "C:\\Users\\Leekha\\.keras" "C:\\Users\\Leekha\\.kindle".............................. A function writedlm(), a function in the DelimitedFiles package can be used to write the contents of an object to a text file. julia> test_numbers = rand(10,10) 10×10 Array{Float64,2}: 0.457071 0.41895 0.63602 0.812757 0.727214 0.156181 0.023817 0.286904 0.488069 0.232787 0.623791 0.946815 0.757186 0.822932 0.791591 0.67814 0.903542 0.664997 0.702893 0.924639 0.334988 0.511964 0.738595 0.631272 0.33401 0.634704 0.175641 0.0679822 0.350901 0.0773231 0.838656 0.140257 0.404624 0.346231 0.642377 0.404291 0.888538 0.356232 0.924593 0.791257 0.438514 0.70627 0.642209 0.196252 0.689652 0.929208 0.19364 0.19769 0.868283 0.258201 0.599995 0.349388 0.22805 0.0180824 0.0226505 0.0838017 0.363375 0.725694 0.224026 0.440138 0.526417 0.788251 0.866562 0.946811 0.834365 0.173869 0.279936 0.80839 0.325284 0.0737317 0.0805326 0.507168 0.388336 0.186871 0.612322 0.662037 0.331884 0.329227 0.355914 0.113426 0.527173 0.0799835 0.543556 0.332768 0.105341 0.409124 0.61811 0.623762 0.944456 0.0490737 0.281633 0.934487 0.257375 0.409263 0.206078 0.720507 0.867653 0.571467 0.705971 0.11014 julia> writedlm("C://Users//Leekha//Desktop//testfile.txt", test_numbers) 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2197, "s": 2078, "text": "The functions namely open(), read(), and close() are the standard approach for extracting information from text files." }, { "code": null, "e": 2343, "s": 2197, "text": "If you want to read text from a text file, you need to first obtain the file handle. It can be done with the help of open() function as follows −" }, { "code": null, "e": 2393, "s": 2343, "text": "foo = open(\"C://Users//Leekha//Desktop//NLP.txt\")" }, { "code": null, "e": 2486, "s": 2393, "text": "It shows that now foo is the Julia’s connection to the text file namely NLP.txt on the disk." }, { "code": null, "e": 2570, "s": 2486, "text": "Once we are done with the file, we should have to close the connection as follows −" }, { "code": null, "e": 2582, "s": 2570, "text": "Close(foo)\n" }, { "code": null, "e": 2679, "s": 2582, "text": "In Julia, it is recommended to wrap any file-processing functions inside a do block as follows −" }, { "code": null, "e": 2749, "s": 2679, "text": "open(\"NLP.txt\") do file\n # here you can work with the open file\nend" }, { "code": null, "e": 2894, "s": 2749, "text": "The advantage of wrapping file-processing functions inside do block is that the open file will be automatically closed when this block finishes." }, { "code": null, "e": 3001, "s": 2894, "text": "An example to keep some of the information like total time to read the file and total lines in the files −" }, { "code": null, "e": 3282, "s": 3001, "text": "julia> totaltime, totallines = open(\"C://Users//Leekha//Desktop//NLP.txt\") do foo\n\n linecounter = 0\n timetaken = @elapsed for l in eachline(foo)\n linecounter += 1\n end\n (timetaken, linecounter)\n end\n(0.0001184, 87)" }, { "code": null, "e": 3373, "s": 3282, "text": "With read() function, we can read the whole content of an open file at once, for example −" }, { "code": null, "e": 3398, "s": 3373, "text": "ABC = read(foo, String)\n" }, { "code": null, "e": 3464, "s": 3398, "text": "Similarly, the below will store the contents of the file in ABC −" }, { "code": null, "e": 3573, "s": 3464, "text": "julia> ABC = open(\"C://Users//Leekha//Desktop//NLP.txt\") do file\n read(file, String)\n end" }, { "code": null, "e": 3650, "s": 3573, "text": "We can also read in the whole file as an array. Use readlines() as follows −" }, { "code": null, "e": 4114, "s": 3650, "text": "julia> foo = open(\"C://Users//Leekha//Desktop//NLP.txt\")\nIOStream(<file C://Users//Leekha//Desktop//NLP.txt>)\n\n\njulia> lines = readlines(foo)\n87-element Array{String,1}:\n \"Natural Language Processing: Semantic Analysis \"\n \"\"\n \"Introduction to semantic analysis:\"\n\"The purpose of semantic analysis is to draw exact meaning, or you can say dictionary meaning from the text. Semantic analyzer checks the text for meaningfulness. \"...................................." }, { "code": null, "e": 4262, "s": 4114, "text": "We can also process a file line by line. For this task, Julia provides a function named eachline() which basically turns a source into an iterator." }, { "code": null, "e": 4554, "s": 4262, "text": "julia> open(\"C://USers/Leekha//Desktop//NLP.txt\") do file\n for ln in eachline(file)\n println(\"$(length(ln)), $(ln)\")\n end\n end\n47, Natural Language Processing: Semantic Analysis\n0,\n34, Introduction to semantic analysis:\n......................................." }, { "code": null, "e": 4662, "s": 4554, "text": "If you want to keep a track of which line you are on while reading the file, use the below given approach −" }, { "code": null, "e": 6244, "s": 4662, "text": "julia> open(\"C://Users//Leekha//Desktop//NLP.txt\") do f\n line = 1\n while !eof(f)\n x = readline(f)\n println(\"$line $x\")\n line += 1\n end\n end\n1 Natural Language Processing: Semantic Analysis\n2\n3 Introduction to semantic analysis:\n4 The purpose of semantic analysis is to draw exact meaning, or you can say dictionary meaning from the text. Semantic analyzer checks the text for meaningfulness.\n5 We know that lexical analysis also deals with the meaning of the words then how semantic analysis is different from lexical analysis? The answer is that Lexical analysis is based on smaller token but on the other side semantic analysis focuses on larger chunks. That is why semantic analysis can be divided into the following two parts:\n6 Studying the meaning of individual word: It is the first part of the semantic analysis in which the study of the meaning of individual words is performed. This part is called lexical semantics.\n7 Studying the combination of individual words: In this second part, the individual words will be combined to provide meaning in sentences.\n8 The most important task of semantic analysis is to get the proper meaning of the sentence. For example, analyze the sentence “Ram is great.” In this sentence, the speaker is talking either about Lord Ram or about a person whose name is Ram. That is why the job, to get the proper meaning of the sentence, of semantic analyzer is important.\n9 Elements of semantic analysis:\n10 Following are the elements of semantic analysis:.........................." }, { "code": null, "e": 6321, "s": 6244, "text": "The table below shows functions that are useful for working with filenames −" }, { "code": null, "e": 6330, "s": 6321, "text": "cd(path)" }, { "code": null, "e": 6375, "s": 6330, "text": "This function changes the current directory." }, { "code": null, "e": 6381, "s": 6375, "text": "pwd()" }, { "code": null, "e": 6431, "s": 6381, "text": "This function gets the current working directory." }, { "code": null, "e": 6445, "s": 6431, "text": "readdir(path)" }, { "code": null, "e": 6538, "s": 6445, "text": "This function returns a list of the contents of a named directory, or the current directory." }, { "code": null, "e": 6552, "s": 6538, "text": "abspath(path)" }, { "code": null, "e": 6644, "s": 6552, "text": "This function adds the current directory's path to a filename to make an absolute pathname." }, { "code": null, "e": 6668, "s": 6644, "text": "joinpath(str, str, ...)" }, { "code": null, "e": 6716, "s": 6668, "text": "This function assembles a pathname from pieces." }, { "code": null, "e": 6728, "s": 6716, "text": "isdir(path)" }, { "code": null, "e": 6785, "s": 6728, "text": "This function tells you whether the path is a directory." }, { "code": null, "e": 6800, "s": 6785, "text": "splitdir(path)" }, { "code": null, "e": 6878, "s": 6800, "text": "This function splits a path into a tuple of the directory name and file name." }, { "code": null, "e": 6895, "s": 6878, "text": "splitdrive(path)" }, { "code": null, "e": 7051, "s": 6895, "text": "This function, on Windows, split a path into the drive letter part and the path part. And, On Unix systems, the first component is always the empty string." }, { "code": null, "e": 7066, "s": 7051, "text": "splitext(path)" }, { "code": null, "e": 7294, "s": 7066, "text": "This function, if the last component of a path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string." }, { "code": null, "e": 7311, "s": 7294, "text": "expanduser(path)" }, { "code": null, "e": 7415, "s": 7311, "text": "This function replaces a tilde character at the start of a path with the current user's home directory." }, { "code": null, "e": 7430, "s": 7415, "text": "normpath(path)" }, { "code": null, "e": 7494, "s": 7430, "text": "This function normalizes a path, removing \".\" and \"..\" entries." }, { "code": null, "e": 7509, "s": 7494, "text": "realpath(path)" }, { "code": null, "e": 7607, "s": 7509, "text": "This function canonicalizes a path by expanding symbolic links and removing \".\" and \"..\" entries." }, { "code": null, "e": 7617, "s": 7607, "text": "homedir()" }, { "code": null, "e": 7672, "s": 7617, "text": "This function gives the current user's home directory." }, { "code": null, "e": 7686, "s": 7672, "text": "dirname(path)" }, { "code": null, "e": 7735, "s": 7686, "text": "This function gets the directory part of a path." }, { "code": null, "e": 7750, "s": 7735, "text": "basename(path)" }, { "code": null, "e": 7799, "s": 7750, "text": "This function gets the file name part of a path." }, { "code": null, "e": 7873, "s": 7799, "text": "We can use stat(“pathname”) to get the information about a specific file." }, { "code": null, "e": 8219, "s": 7873, "text": "julia> for n in fieldnames(typeof(stat(\"C://Users//Leekha//Desktop//NLP.txt\")))\n println(n, \": \", getfield(stat(\"C://Users//Leekha//Desktop//NLP.txt\"),n))\n end\ndevice: 3262175189\ninode: 17276\nmode: 33206\nnlink: 1\nuid: 0\ngid: 0\nrdev: 0\nsize: 6293\nblksize: 4096\nblocks: 16\nmtime: 1.6017034024103658e9\nctime: 1.6017034024103658e9" }, { "code": null, "e": 8363, "s": 8219, "text": "If you want to convert filenames to pathnames, you can use abspath() function. We can map this over a list of files in a directory as follows −" }, { "code": null, "e": 8796, "s": 8363, "text": "julia> map(abspath, readdir())\n204-element Array{String,1}:\n \"C:\\\\Users\\\\Leekha\\\\.anaconda\"\n \"C:\\\\Users\\\\Leekha\\\\.conda\"\n \"C:\\\\Users\\\\Leekha\\\\.condarc\"\n \"C:\\\\Users\\\\Leekha\\\\.config\"\n \"C:\\\\Users\\\\Leekha\\\\.idlerc\"\n \"C:\\\\Users\\\\Leekha\\\\.ipynb_checkpoints\"\n \"C:\\\\Users\\\\Leekha\\\\.ipython\"\n \"C:\\\\Users\\\\Leekha\\\\.julia\"\n \"C:\\\\Users\\\\Leekha\\\\.jupyter\"\n \"C:\\\\Users\\\\Leekha\\\\.keras\"\n \"C:\\\\Users\\\\Leekha\\\\.kindle\".............................." }, { "code": null, "e": 8923, "s": 8796, "text": "A function writedlm(), a function in the DelimitedFiles package can be used to write the contents of an object to a text file." }, { "code": null, "e": 9967, "s": 8923, "text": "julia> test_numbers = rand(10,10)\n10×10 Array{Float64,2}:\n 0.457071 0.41895 0.63602 0.812757 0.727214 0.156181 0.023817 0.286904 0.488069 0.232787\n 0.623791 0.946815 0.757186 0.822932 0.791591 0.67814 0.903542 0.664997 0.702893 0.924639\n 0.334988 0.511964 0.738595 0.631272 0.33401 0.634704 0.175641 0.0679822 0.350901 0.0773231\n 0.838656 0.140257 0.404624 0.346231 0.642377 0.404291 0.888538 0.356232 0.924593 0.791257\n 0.438514 0.70627 0.642209 0.196252 0.689652 0.929208 0.19364 0.19769 0.868283 0.258201\n 0.599995 0.349388 0.22805 0.0180824 0.0226505 0.0838017 0.363375 0.725694 0.224026 0.440138\n 0.526417 0.788251 0.866562 0.946811 0.834365 0.173869 0.279936 0.80839 0.325284 0.0737317\n 0.0805326 0.507168 0.388336 0.186871 0.612322 0.662037 0.331884 0.329227 0.355914 0.113426\n 0.527173 0.0799835 0.543556 0.332768 0.105341 0.409124 0.61811 0.623762 0.944456 0.0490737\n 0.281633 0.934487 0.257375 0.409263 0.206078 0.720507 0.867653 0.571467 0.705971 0.11014\n \njulia> writedlm(\"C://Users//Leekha//Desktop//testfile.txt\", test_numbers)" }, { "code": null, "e": 10000, "s": 9967, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 10017, "s": 10000, "text": " Lemuel Ogbunude" }, { "code": null, "e": 10050, "s": 10017, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 10067, "s": 10050, "text": " Mohammad Nauman" }, { "code": null, "e": 10102, "s": 10067, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10125, "s": 10102, "text": " Stone River ELearning" }, { "code": null, "e": 10132, "s": 10125, "text": " Print" }, { "code": null, "e": 10143, "s": 10132, "text": " Add Notes" } ]
HashSet vs TreeSet in Java - GeeksforGeeks
14 Sep, 2021 When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets while TreeSet is an implementation of SortedSet interface which as the name suggests uses the tree for storage purposes where here the ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. 1. Speed and internal implementation For operations like search, insert, and delete HashSet takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a self-balancing binary search tree (Red-Black Tree). TreeSet is backed by TreeMap in Java. 2. Ordering Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc. 3. Null Object HashSet allows null object. TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException. 4. Comparison HashSet uses the equals() method to compare two objects in Set and for detecting duplicates. TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, then it will break the contract of Set interface and will allow duplicates in Set implementations like TreeSet Note: If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it. Geek after going through their differences now you must be wondering out when to prefer TreeSet over HashSet? Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order. TreeSet has a greater locality than HashSet.If two entries are nearby in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to. TreeSet uses Red-Black tree algorithm underneath to sort out the elements. When one need to perform read/write operations frequently, then TreeSet is a good choice. LinkedHashSet is another data structure that is between these two. It provides time complexities like HashSet and maintains the order of insertion (Note that this is not sorted order, but the order in which elements are inserted). Implementation: Here we will be discussing them both with 2 examples for both of them. Let us start with HashSet later on dwelling on to TreeSet. HashSet examples TreeSet examples Example 1: Java // Java Program to Demonstrate Working of HashSet // Importing HashSet class from java.util packageimport java.util.HashSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a HashSet object of string type HashSet<String> hset = new HashSet<String>(); // Adding elements to HashSet // using add() method hset.add("geeks"); hset.add("for"); hset.add("practice"); hset.add("contribute"); // Duplicate removed hset.add("geeks"); // Printing HashSet elements using for each loop // Display command only System.out.println("HashSet contains: "); for (String temp : hset) { System.out.println(temp); } }} HashSet contains: practice geeks for contribute Example 2: Java // Java Program to Illustrate Working of HashSet// From another Collection // Importing utility classesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { ArrayList<String> ll = new ArrayList<String>(); // Adding elements to ArrayList ll.add("Computer"); ll.add("Science"); // Creating HashSet object of string type HashSet<String> hs = new HashSet(ll); hs.add("Portal"); hs.add("GFG"); // Iterating via iterators Iterator<String> iter = hs.iterator(); // Condition holds true till there is single element // in th List while (iter.hasNext()) { // Printing all elements inside objects System.out.println(iter.next()); } }} Output: Now it’s time to implement TreeSet to understand better via implementing it. Example 1: Java // Java program to demonstrate working of// TreeSet.import java.util.TreeSet;class TreeSetDemo { public static void main(String[] args) { // Create a TreeSet TreeSet<String> tset = new TreeSet<String>(); // add elements to HashSet tset.add("geeks"); tset.add("for"); tset.add("practice"); tset.add("contribute"); // Duplicate removed tset.add("geeks"); // Displaying TreeSet elements System.out.println("TreeSet contains: "); for (String temp : tset) { System.out.println(temp); } }} TreeSet contains: contribute for geeks practice Example 2: Java // Java Program to Illustrate Working of TreeSet// From another Collection // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { ArrayList<String> ll = new ArrayList<String>(); // Adding elements to ArrayList ll.add("Computer"); ll.add("Science"); // Creating TreeSet object of string type TreeSet<String> ts = new TreeSet(ll); ts.add("Portal"); ts.add("GFG"); // Iterating via iterators Iterator<String> iter = ts.iterator(); // Condition holds true till there is single element in th List while (iter.hasNext()) { // Printing all elements inside objects System.out.println(iter.next()); } }} Output: solankimayank ruhelaa48 anikakapoor Java-Collections java-hashset Java-Set-Programs java-treeset Picked Difference Between Hash Java Tree Hash Java Tree Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Process and Thread Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Clustered and Non-clustered index Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Count pairs with given sum
[ { "code": null, "e": 24504, "s": 24476, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25263, "s": 24504, "text": "When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets while TreeSet is an implementation of SortedSet interface which as the name suggests uses the tree for storage purposes where here the ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided." }, { "code": null, "e": 25301, "s": 25263, "text": "1. Speed and internal implementation " }, { "code": null, "e": 25895, "s": 25301, "text": "For operations like search, insert, and delete HashSet takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a self-balancing binary search tree (Red-Black Tree). TreeSet is backed by TreeMap in Java." }, { "code": null, "e": 25908, "s": 25895, "text": "2. Ordering " }, { "code": null, "e": 26209, "s": 25908, "text": "Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc." }, { "code": null, "e": 26225, "s": 26209, "text": "3. Null Object " }, { "code": null, "e": 26439, "s": 26225, "text": "HashSet allows null object. TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException." }, { "code": null, "e": 26454, "s": 26439, "text": "4. Comparison " }, { "code": null, "e": 26846, "s": 26454, "text": "HashSet uses the equals() method to compare two objects in Set and for detecting duplicates. TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, then it will break the contract of Set interface and will allow duplicates in Set implementations like TreeSet" }, { "code": null, "e": 27013, "s": 26846, "text": "Note: If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it." }, { "code": null, "e": 27123, "s": 27013, "text": "Geek after going through their differences now you must be wondering out when to prefer TreeSet over HashSet?" }, { "code": null, "e": 27250, "s": 27123, "text": "Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order." }, { "code": null, "e": 27511, "s": 27250, "text": "TreeSet has a greater locality than HashSet.If two entries are nearby in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to." }, { "code": null, "e": 27676, "s": 27511, "text": "TreeSet uses Red-Black tree algorithm underneath to sort out the elements. When one need to perform read/write operations frequently, then TreeSet is a good choice." }, { "code": null, "e": 27907, "s": 27676, "text": "LinkedHashSet is another data structure that is between these two. It provides time complexities like HashSet and maintains the order of insertion (Note that this is not sorted order, but the order in which elements are inserted)." }, { "code": null, "e": 27923, "s": 27907, "text": "Implementation:" }, { "code": null, "e": 28054, "s": 27923, "text": "Here we will be discussing them both with 2 examples for both of them. Let us start with HashSet later on dwelling on to TreeSet. " }, { "code": null, "e": 28071, "s": 28054, "text": "HashSet examples" }, { "code": null, "e": 28088, "s": 28071, "text": "TreeSet examples" }, { "code": null, "e": 28099, "s": 28088, "text": "Example 1:" }, { "code": null, "e": 28104, "s": 28099, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of HashSet // Importing HashSet class from java.util packageimport java.util.HashSet; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a HashSet object of string type HashSet<String> hset = new HashSet<String>(); // Adding elements to HashSet // using add() method hset.add(\"geeks\"); hset.add(\"for\"); hset.add(\"practice\"); hset.add(\"contribute\"); // Duplicate removed hset.add(\"geeks\"); // Printing HashSet elements using for each loop // Display command only System.out.println(\"HashSet contains: \"); for (String temp : hset) { System.out.println(temp); } }}", "e": 28888, "s": 28104, "text": null }, { "code": null, "e": 28937, "s": 28888, "text": "HashSet contains: \npractice\ngeeks\nfor\ncontribute" }, { "code": null, "e": 28950, "s": 28939, "text": "Example 2:" }, { "code": null, "e": 28955, "s": 28950, "text": "Java" }, { "code": "// Java Program to Illustrate Working of HashSet// From another Collection // Importing utility classesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { ArrayList<String> ll = new ArrayList<String>(); // Adding elements to ArrayList ll.add(\"Computer\"); ll.add(\"Science\"); // Creating HashSet object of string type HashSet<String> hs = new HashSet(ll); hs.add(\"Portal\"); hs.add(\"GFG\"); // Iterating via iterators Iterator<String> iter = hs.iterator(); // Condition holds true till there is single element // in th List while (iter.hasNext()) { // Printing all elements inside objects System.out.println(iter.next()); } }}", "e": 29760, "s": 28955, "text": null }, { "code": null, "e": 29768, "s": 29760, "text": "Output:" }, { "code": null, "e": 29845, "s": 29768, "text": "Now it’s time to implement TreeSet to understand better via implementing it." }, { "code": null, "e": 29856, "s": 29845, "text": "Example 1:" }, { "code": null, "e": 29861, "s": 29856, "text": "Java" }, { "code": "// Java program to demonstrate working of// TreeSet.import java.util.TreeSet;class TreeSetDemo { public static void main(String[] args) { // Create a TreeSet TreeSet<String> tset = new TreeSet<String>(); // add elements to HashSet tset.add(\"geeks\"); tset.add(\"for\"); tset.add(\"practice\"); tset.add(\"contribute\"); // Duplicate removed tset.add(\"geeks\"); // Displaying TreeSet elements System.out.println(\"TreeSet contains: \"); for (String temp : tset) { System.out.println(temp); } }}", "e": 30460, "s": 29861, "text": null }, { "code": null, "e": 30509, "s": 30460, "text": "TreeSet contains: \ncontribute\nfor\ngeeks\npractice" }, { "code": null, "e": 30523, "s": 30511, "text": "Example 2: " }, { "code": null, "e": 30528, "s": 30523, "text": "Java" }, { "code": "// Java Program to Illustrate Working of TreeSet// From another Collection // Importing utility classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { ArrayList<String> ll = new ArrayList<String>(); // Adding elements to ArrayList ll.add(\"Computer\"); ll.add(\"Science\"); // Creating TreeSet object of string type TreeSet<String> ts = new TreeSet(ll); ts.add(\"Portal\"); ts.add(\"GFG\"); // Iterating via iterators Iterator<String> iter = ts.iterator(); // Condition holds true till there is single element in th List while (iter.hasNext()) { // Printing all elements inside objects System.out.println(iter.next()); } }}", "e": 31346, "s": 30528, "text": null }, { "code": null, "e": 31354, "s": 31346, "text": "Output:" }, { "code": null, "e": 31368, "s": 31354, "text": "solankimayank" }, { "code": null, "e": 31378, "s": 31368, "text": "ruhelaa48" }, { "code": null, "e": 31390, "s": 31378, "text": "anikakapoor" }, { "code": null, "e": 31407, "s": 31390, "text": "Java-Collections" }, { "code": null, "e": 31420, "s": 31407, "text": "java-hashset" }, { "code": null, "e": 31438, "s": 31420, "text": "Java-Set-Programs" }, { "code": null, "e": 31451, "s": 31438, "text": "java-treeset" }, { "code": null, "e": 31458, "s": 31451, "text": "Picked" }, { "code": null, "e": 31477, "s": 31458, "text": "Difference Between" }, { "code": null, "e": 31482, "s": 31477, "text": "Hash" }, { "code": null, "e": 31487, "s": 31482, "text": "Java" }, { "code": null, "e": 31492, "s": 31487, "text": "Tree" }, { "code": null, "e": 31497, "s": 31492, "text": "Hash" }, { "code": null, "e": 31502, "s": 31497, "text": "Java" }, { "code": null, "e": 31507, "s": 31502, "text": "Tree" }, { "code": null, "e": 31524, "s": 31507, "text": "Java-Collections" }, { "code": null, "e": 31622, "s": 31524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31631, "s": 31622, "text": "Comments" }, { "code": null, "e": 31644, "s": 31631, "text": "Old Comments" }, { "code": null, "e": 31682, "s": 31644, "text": "Difference between Process and Thread" }, { "code": null, "e": 31743, "s": 31682, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31811, "s": 31743, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 31867, "s": 31811, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 31920, "s": 31867, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 32005, "s": 31920, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32036, "s": 32005, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 32070, "s": 32036, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 32106, "s": 32070, "text": "Hashing | Set 2 (Separate Chaining)" } ]
SQLite - Constraints
Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table. Following are commonly used constraints available in SQLite. NOT NULL Constraint − Ensures that a column cannot have NULL value. NOT NULL Constraint − Ensures that a column cannot have NULL value. DEFAULT Constraint − Provides a default value for a column when none is specified. DEFAULT Constraint − Provides a default value for a column when none is specified. UNIQUE Constraint − Ensures that all values in a column are different. UNIQUE Constraint − Ensures that all values in a column are different. PRIMARY Key − Uniquely identifies each row/record in a database table. PRIMARY Key − Uniquely identifies each row/record in a database table. CHECK Constraint − Ensures that all values in a column satisfies certain conditions. CHECK Constraint − Ensures that all values in a column satisfies certain conditions. By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column. A NULL is not the same as no data, rather, it represents unknown data. For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs. CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value. For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00. CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL DEFAULT 50000.00 ); The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age. For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age − CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL UNIQUE, ADDRESS CHAR(50), SALARY REAL DEFAULT 50000.00 ); The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs. We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases. A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s). You already have seen various examples above where we have created COMPANY table with ID as a primary key. CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table. For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero. CREATE TABLE COMPANY3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2840, "s": 2638, "text": "Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. " }, { "code": null, "e": 3011, "s": 2840, "text": "Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table." }, { "code": null, "e": 3072, "s": 3011, "text": "Following are commonly used constraints available in SQLite." }, { "code": null, "e": 3140, "s": 3072, "text": "NOT NULL Constraint − Ensures that a column cannot have NULL value." }, { "code": null, "e": 3208, "s": 3140, "text": "NOT NULL Constraint − Ensures that a column cannot have NULL value." }, { "code": null, "e": 3292, "s": 3208, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 3376, "s": 3292, "text": "DEFAULT Constraint − Provides a default value for a column when none is specified." }, { "code": null, "e": 3447, "s": 3376, "text": "UNIQUE Constraint − Ensures that all values in a column are different." }, { "code": null, "e": 3518, "s": 3447, "text": "UNIQUE Constraint − Ensures that all values in a column are different." }, { "code": null, "e": 3589, "s": 3518, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 3660, "s": 3589, "text": "PRIMARY Key − Uniquely identifies each row/record in a database table." }, { "code": null, "e": 3746, "s": 3660, "text": "CHECK Constraint − Ensures that all values in a column satisfies certain conditions. " }, { "code": null, "e": 3832, "s": 3746, "text": "CHECK Constraint − Ensures that all values in a column satisfies certain conditions. " }, { "code": null, "e": 4037, "s": 3832, "text": "By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column." }, { "code": null, "e": 4108, "s": 4037, "text": "A NULL is not the same as no data, rather, it represents unknown data." }, { "code": null, "e": 4278, "s": 4108, "text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs." }, { "code": null, "e": 4462, "s": 4278, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 4588, "s": 4462, "text": "The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value." }, { "code": null, "e": 4871, "s": 4588, "text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00." }, { "code": null, "e": 5075, "s": 4871, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL DEFAULT 50000.00\n);" }, { "code": null, "e": 5281, "s": 5075, "text": "The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age." }, { "code": null, "e": 5474, "s": 5281, "text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age −" }, { "code": null, "e": 5685, "s": 5474, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL UNIQUE,\n ADDRESS CHAR(50),\n SALARY REAL DEFAULT 50000.00\n);" }, { "code": null, "e": 5928, "s": 5685, "text": "The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs." }, { "code": null, "e": 6174, "s": 5928, "text": " We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases." }, { "code": null, "e": 6362, "s": 6174, "text": "A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values." }, { "code": null, "e": 6530, "s": 6362, "text": "A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key." }, { "code": null, "e": 6657, "s": 6530, "text": "If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s)." }, { "code": null, "e": 6764, "s": 6657, "text": "You already have seen various examples above where we have created COMPANY table with ID as a primary key." }, { "code": null, "e": 6948, "s": 6764, "text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 7139, "s": 6948, "text": "CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table." }, { "code": null, "e": 7313, "s": 7139, "text": "For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero." }, { "code": null, "e": 7519, "s": 7313, "text": "CREATE TABLE COMPANY3(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL CHECK(SALARY > 0)\n);" }, { "code": null, "e": 7777, "s": 7519, "text": "SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table." }, { "code": null, "e": 7812, "s": 7777, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7833, "s": 7812, "text": " Sandip Bhattacharya" }, { "code": null, "e": 7866, "s": 7833, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 7883, "s": 7866, "text": " Laurence Svekis" }, { "code": null, "e": 7914, "s": 7883, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 7927, "s": 7914, "text": " Vinay Kumar" }, { "code": null, "e": 7934, "s": 7927, "text": " Print" }, { "code": null, "e": 7945, "s": 7934, "text": " Add Notes" } ]
How to catch StopIteration Exception in Python?
When an iterator is done, it’s next method raises StopIteration. This exception is not considered an error. We re-write the given code as follows to catch the exception and know its type. import sys try: z = [5, 9, 7] i = iter(z) print i print i.next() print i.next() print i.next() print i.next() except Exception as e: print e print sys.exc_type <listiterator object at 0x0000000002AF23C8> 5 9 7 <type 'exceptions.StopIteration'>
[ { "code": null, "e": 1170, "s": 1062, "text": "When an iterator is done, it’s next method raises StopIteration. This exception is not considered an error." }, { "code": null, "e": 1250, "s": 1170, "text": "We re-write the given code as follows to catch the exception and know its type." }, { "code": null, "e": 1411, "s": 1250, "text": "import sys\ntry:\nz = [5, 9, 7]\ni = iter(z)\nprint i\nprint i.next()\nprint i.next()\nprint i.next()\nprint i.next()\nexcept Exception as e:\nprint e\nprint sys.exc_type\n" }, { "code": null, "e": 1495, "s": 1411, "text": "<listiterator object at 0x0000000002AF23C8>\n5\n9\n7\n<type 'exceptions.StopIteration'>" } ]
Scikit Learn - Boosting Methods
In this chapter, we will learn about the boosting methods in Sklearn, which enables building an ensemble model. Boosting methods build ensemble model in an increment way. The main principle is to build the model incrementally by training each base model estimator sequentially. In order to build powerful ensemble, these methods basically combine several week learners which are sequentially trained over multiple iterations of training data. The sklearn.ensemble module is having following two boosting methods. It is one of the most successful boosting ensemble method whose main key is in the way they give weights to the instances in dataset. That’s why the algorithm needs to pay less attention to the instances while constructing subsequent models. For creating a AdaBoost classifier, the Scikit-learn module provides sklearn.ensemble.AdaBoostClassifier. While building this classifier, the main parameter this module use is base_estimator. Here, base_estimator is the value of the base estimator from which the boosted ensemble is built. If we choose this parameter’s value to none then, the base estimator would be DecisionTreeClassifier(max_depth=1). In the following example, we are building a AdaBoost classifier by using sklearn.ensemble.AdaBoostClassifier and also predicting and checking its score. from sklearn.ensemble import AdaBoostClassifier from sklearn.datasets import make_classification X, y = make_classification(n_samples = 1000, n_features = 10,n_informative = 2, n_redundant = 0,random_state = 0, shuffle = False) ADBclf = AdaBoostClassifier(n_estimators = 100, random_state = 0) ADBclf.fit(X, y) AdaBoostClassifier(algorithm = 'SAMME.R', base_estimator = None, learning_rate = 1.0, n_estimators = 100, random_state = 0) Once fitted, we can predict for new values as follows − print(ADBclf.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]])) [1] Now we can check the score as follows − ADBclf.score(X, y) 0.995 We can also use the sklearn dataset to build classifier using Extra-Tree method. For example, in an example given below, we are using Pima-Indian dataset. from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import AdaBoostClassifier path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names = headernames) array = data.values X = array[:,0:8] Y = array[:,8] seed = 5 kfold = KFold(n_splits = 10, random_state = seed) num_trees = 100 max_features = 5 ADBclf = AdaBoostClassifier(n_estimators = num_trees, max_features = max_features) results = cross_val_score(ADBclf, X, Y, cv = kfold) print(results.mean()) 0.7851435406698566 For creating a regressor with Ada Boost method, the Scikit-learn library provides sklearn.ensemble.AdaBoostRegressor. While building regressor, it will use the same parameters as used by sklearn.ensemble.AdaBoostClassifier. In the following example, we are building a AdaBoost regressor by using sklearn.ensemble.AdaBoostregressor and also predicting for new values by using predict() method. from sklearn.ensemble import AdaBoostRegressor from sklearn.datasets import make_regression X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False) ADBregr = RandomForestRegressor(random_state = 0,n_estimators = 100) ADBregr.fit(X, y) AdaBoostRegressor(base_estimator = None, learning_rate = 1.0, loss = 'linear', n_estimators = 100, random_state = 0) Once fitted we can predict from regression model as follows − print(ADBregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]])) [85.50955817] It is also called Gradient Boosted Regression Trees (GRBT). It is basically a generalization of boosting to arbitrary differentiable loss functions. It produces a prediction model in the form of an ensemble of week prediction models. It can be used for the regression and classification problems. Their main advantage lies in the fact that they naturally handle the mixed type data. For creating a Gradient Tree Boost classifier, the Scikit-learn module provides sklearn.ensemble.GradientBoostingClassifier. While building this classifier, the main parameter this module use is ‘loss’. Here, ‘loss’ is the value of loss function to be optimized. If we choose loss = deviance, it refers to deviance for classification with probabilistic outputs. On the other hand, if we choose this parameter’s value to exponential then it recovers the AdaBoost algorithm. The parameter n_estimators will control the number of week learners. A hyper-parameter named learning_rate (in the range of (0.0, 1.0]) will control overfitting via shrinkage. In the following example, we are building a Gradient Boosting classifier by using sklearn.ensemble.GradientBoostingClassifier. We are fitting this classifier with 50 week learners. from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import GradientBoostingClassifier X, y = make_hastie_10_2(random_state = 0) X_train, X_test = X[:5000], X[5000:] y_train, y_test = y[:5000], y[5000:] GDBclf = GradientBoostingClassifier(n_estimators = 50, learning_rate = 1.0,max_depth = 1, random_state = 0).fit(X_train, y_train) GDBclf.score(X_test, y_test) 0.8724285714285714 We can also use the sklearn dataset to build classifier using Gradient Boosting Classifier. As in the following example we are using Pima-Indian dataset. from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import GradientBoostingClassifier path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names = headernames) array = data.values X = array[:,0:8] Y = array[:,8] seed = 5 kfold = KFold(n_splits = 10, random_state = seed) num_trees = 100 max_features = 5 ADBclf = GradientBoostingClassifier(n_estimators = num_trees, max_features = max_features) results = cross_val_score(ADBclf, X, Y, cv = kfold) print(results.mean()) 0.7946582356674234 For creating a regressor with Gradient Tree Boost method, the Scikit-learn library provides sklearn.ensemble.GradientBoostingRegressor. It can specify the loss function for regression via the parameter name loss. The default value for loss is ‘ls’. In the following example, we are building a Gradient Boosting regressor by using sklearn.ensemble.GradientBoostingregressor and also finding the mean squared error by using mean_squared_error() method. import numpy as np from sklearn.metrics import mean_squared_error from sklearn.datasets import make_friedman1 from sklearn.ensemble import GradientBoostingRegressor X, y = make_friedman1(n_samples = 2000, random_state = 0, noise = 1.0) X_train, X_test = X[:1000], X[1000:] y_train, y_test = y[:1000], y[1000:] GDBreg = GradientBoostingRegressor(n_estimators = 80, learning_rate=0.1, max_depth = 1, random_state = 0, loss = 'ls').fit(X_train, y_train) Once fitted we can find the mean squared error as follows − mean_squared_error(y_test, GDBreg.predict(X_test)) 5.391246106657164 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2221, "text": "In this chapter, we will learn about the boosting methods in Sklearn, which enables building an ensemble model." }, { "code": null, "e": 2734, "s": 2333, "text": "Boosting methods build ensemble model in an increment way. The main principle is to build the model incrementally by training each base model estimator sequentially. In order to build powerful ensemble, these methods basically combine several week learners which are sequentially trained over multiple iterations of training data. The sklearn.ensemble module is having following two boosting methods." }, { "code": null, "e": 2976, "s": 2734, "text": "It is one of the most successful boosting ensemble method whose main key is in the way they give weights to the instances in dataset. That’s why the algorithm needs to pay less attention to the instances while constructing subsequent models." }, { "code": null, "e": 3381, "s": 2976, "text": "For creating a AdaBoost classifier, the Scikit-learn module provides sklearn.ensemble.AdaBoostClassifier. While building this classifier, the main parameter this module use is base_estimator. Here, base_estimator is the value of the base estimator from which the boosted ensemble is built. If we choose this parameter’s value to none then, the base estimator would be DecisionTreeClassifier(max_depth=1)." }, { "code": null, "e": 3534, "s": 3381, "text": "In the following example, we are building a AdaBoost classifier by using sklearn.ensemble.AdaBoostClassifier and also predicting and checking its score." }, { "code": null, "e": 3845, "s": 3534, "text": "from sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.datasets import make_classification\nX, y = make_classification(n_samples = 1000, n_features = 10,n_informative = 2, n_redundant = 0,random_state = 0, shuffle = False)\nADBclf = AdaBoostClassifier(n_estimators = 100, random_state = 0)\nADBclf.fit(X, y)" }, { "code": null, "e": 3970, "s": 3845, "text": "AdaBoostClassifier(algorithm = 'SAMME.R', base_estimator = None,\nlearning_rate = 1.0, n_estimators = 100, random_state = 0)\n" }, { "code": null, "e": 4026, "s": 3970, "text": "Once fitted, we can predict for new values as follows −" }, { "code": null, "e": 4082, "s": 4026, "text": "print(ADBclf.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))" }, { "code": null, "e": 4087, "s": 4082, "text": "[1]\n" }, { "code": null, "e": 4127, "s": 4087, "text": "Now we can check the score as follows −" }, { "code": null, "e": 4146, "s": 4127, "text": "ADBclf.score(X, y)" }, { "code": null, "e": 4153, "s": 4146, "text": "0.995\n" }, { "code": null, "e": 4308, "s": 4153, "text": "We can also use the sklearn dataset to build classifier using Extra-Tree method. For example, in an example given below, we are using Pima-Indian dataset." }, { "code": null, "e": 4948, "s": 4308, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import AdaBoostClassifier\npath = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names = headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]\nseed = 5\nkfold = KFold(n_splits = 10, random_state = seed)\nnum_trees = 100\nmax_features = 5\nADBclf = AdaBoostClassifier(n_estimators = num_trees, max_features = max_features)\nresults = cross_val_score(ADBclf, X, Y, cv = kfold)\nprint(results.mean())" }, { "code": null, "e": 4968, "s": 4948, "text": "0.7851435406698566\n" }, { "code": null, "e": 5192, "s": 4968, "text": "For creating a regressor with Ada Boost method, the Scikit-learn library provides sklearn.ensemble.AdaBoostRegressor. While building regressor, it will use the same parameters as used by sklearn.ensemble.AdaBoostClassifier." }, { "code": null, "e": 5361, "s": 5192, "text": "In the following example, we are building a AdaBoost regressor by using sklearn.ensemble.AdaBoostregressor and also predicting for new values by using predict() method." }, { "code": null, "e": 5633, "s": 5361, "text": "from sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.datasets import make_regression\nX, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)\nADBregr = RandomForestRegressor(random_state = 0,n_estimators = 100)\nADBregr.fit(X, y)" }, { "code": null, "e": 5751, "s": 5633, "text": "AdaBoostRegressor(base_estimator = None, learning_rate = 1.0, loss = 'linear',\nn_estimators = 100, random_state = 0)\n" }, { "code": null, "e": 5813, "s": 5751, "text": "Once fitted we can predict from regression model as follows −" }, { "code": null, "e": 5870, "s": 5813, "text": "print(ADBregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))" }, { "code": null, "e": 5885, "s": 5870, "text": "[85.50955817]\n" }, { "code": null, "e": 6268, "s": 5885, "text": "It is also called Gradient Boosted Regression Trees (GRBT). It is basically a generalization of boosting to arbitrary differentiable loss functions. It produces a prediction model in the form of an ensemble of week prediction models. It can be used for the regression and classification problems. Their main advantage lies in the fact that they naturally handle the mixed type data." }, { "code": null, "e": 6630, "s": 6268, "text": "For creating a Gradient Tree Boost classifier, the Scikit-learn module provides sklearn.ensemble.GradientBoostingClassifier. While building this classifier, the main parameter this module use is ‘loss’. Here, ‘loss’ is the value of loss function to be optimized. If we choose loss = deviance, it refers to deviance for classification with probabilistic outputs." }, { "code": null, "e": 6917, "s": 6630, "text": "On the other hand, if we choose this parameter’s value to exponential then it recovers the AdaBoost algorithm. The parameter n_estimators will control the number of week learners. A hyper-parameter named learning_rate (in the range of (0.0, 1.0]) will control overfitting via shrinkage." }, { "code": null, "e": 7098, "s": 6917, "text": "In the following example, we are building a Gradient Boosting classifier by using sklearn.ensemble.GradientBoostingClassifier. We are fitting this classifier with 50 week learners." }, { "code": null, "e": 7476, "s": 7098, "text": "from sklearn.datasets import make_hastie_10_2\nfrom sklearn.ensemble import GradientBoostingClassifier\nX, y = make_hastie_10_2(random_state = 0)\nX_train, X_test = X[:5000], X[5000:]\ny_train, y_test = y[:5000], y[5000:]\n\nGDBclf = GradientBoostingClassifier(n_estimators = 50, learning_rate = 1.0,max_depth = 1, random_state = 0).fit(X_train, y_train)\nGDBclf.score(X_test, y_test)" }, { "code": null, "e": 7496, "s": 7476, "text": "0.8724285714285714\n" }, { "code": null, "e": 7650, "s": 7496, "text": "We can also use the sklearn dataset to build classifier using Gradient Boosting Classifier. As in the following example we are using Pima-Indian dataset." }, { "code": null, "e": 8306, "s": 7650, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import GradientBoostingClassifier\npath = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names = headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]\nseed = 5\nkfold = KFold(n_splits = 10, random_state = seed)\nnum_trees = 100\nmax_features = 5\nADBclf = GradientBoostingClassifier(n_estimators = num_trees, max_features = max_features)\nresults = cross_val_score(ADBclf, X, Y, cv = kfold)\nprint(results.mean())" }, { "code": null, "e": 8326, "s": 8306, "text": "0.7946582356674234\n" }, { "code": null, "e": 8575, "s": 8326, "text": "For creating a regressor with Gradient Tree Boost method, the Scikit-learn library provides sklearn.ensemble.GradientBoostingRegressor. It can specify the loss function for regression via the parameter name loss. The default value for loss is ‘ls’." }, { "code": null, "e": 8777, "s": 8575, "text": "In the following example, we are building a Gradient Boosting regressor by using sklearn.ensemble.GradientBoostingregressor and also finding the mean squared error by using mean_squared_error() method." }, { "code": null, "e": 9228, "s": 8777, "text": "import numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.datasets import make_friedman1\nfrom sklearn.ensemble import GradientBoostingRegressor\nX, y = make_friedman1(n_samples = 2000, random_state = 0, noise = 1.0)\nX_train, X_test = X[:1000], X[1000:]\ny_train, y_test = y[:1000], y[1000:]\nGDBreg = GradientBoostingRegressor(n_estimators = 80, learning_rate=0.1,\nmax_depth = 1, random_state = 0, loss = 'ls').fit(X_train, y_train)" }, { "code": null, "e": 9288, "s": 9228, "text": "Once fitted we can find the mean squared error as follows −" }, { "code": null, "e": 9339, "s": 9288, "text": "mean_squared_error(y_test, GDBreg.predict(X_test))" }, { "code": null, "e": 9358, "s": 9339, "text": "5.391246106657164\n" }, { "code": null, "e": 9391, "s": 9358, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 9408, "s": 9391, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 9415, "s": 9408, "text": " Print" }, { "code": null, "e": 9426, "s": 9415, "text": " Add Notes" } ]
Path with maximum product in 2-d array - GeeksforGeeks
06 Apr, 2022 Given a 2D matrix of size N*M. The task is to find the maximum product path from (0, 0) to (N-1, M-1). You can only move to right from (i, j) to (i, j+1) and down from (i, j) to (i+1, j).Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output: 2016 The path with maximum product is : 1->4->7->8->9 = 2016 Approach: To choose which direction to go from the current position we have to check the direction that gives the maximum product. We will maintain two 2D arrays: maxPath[i][j]: It will store the maximum product till (i, j)minPath[i][j]: It will store the minimum product till (i, j) maxPath[i][j]: It will store the maximum product till (i, j) minPath[i][j]: It will store the minimum product till (i, j) Steps: Initialise the maxPath[0][0] & minPath[0][0] to arr[0][0]. For all the remaining cells in maxPath[i][j] check whether the product of current cell(i, j) and previous cell (i-1, j) is maximum or not by: considering rows: maxValue1 = max(arr[i][j]*maxPath[i-1][j], arr[i][j]*minPath[i-1][j]) considering columns: maxValue2 = max(maxPath[i][j – 1] * arr[i][j], minPath[i][j – 1] * arr[i][j]) as arr[i][j] can be negative and if minPath[i][j] is negative. Then, arr[i][j]*minPath[i][j] is positive, which can be maximum product. For all the remaining cells in minPath[i][j] check whether the product of current cell(i, j) and previous cell (i-1, j) is minimum or not by: considering rows: minValue1 = min(maxPath[i – 1][j] * arr[i][j], minPath[i – 1][j] * arr[i][j]) considering columns: minValue2 = min(maxPath[i][j – 1] * arr[i][j], minPath[i][j – 1] * arr[i][j]) Update minPath[i][j] = min(minValue1, minValue2) & maxPath[i][j] = max(maxValue1, maxValue2) Return maxPath[n-1][m-1] for maximum product. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find maximum// product path from (0, 0) to// (N-1, M-1)#include <bits/stdc++.h>using namespace std;#define N 3#define M 3 // Function to find maximum productint maxProductPath(int arr[N][M]){ // It will store the maximum // product till a given cell. vector<vector<int> > maxPath(N, vector<int>(M, INT_MIN)); // It will store the minimum // product till a given cell // (for -ve elements) vector<vector<int> > minPath(N, vector<int>(M, INT_MAX)); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = INT_MAX; int maxVal = INT_MIN; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = max(maxVal, tempMax); int tempMin = min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = max(maxVal, tempMax); int tempMin = min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0 -> N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Codeint main(){ int arr[N][M] = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N-1, M-1) cout << maxProductPath(arr) << endl; return 0;} // Java Program to find maximum// product path from (0, 0) to// (N-1, M-1)class GFG{ static final int N = 3;static final int M = 3; // Function to find maximum productstatic int maxProductPath(int arr[][]){ // It will store the maximum // product till a given cell. int [][]maxPath = new int[N][M]; // It will store the minimum // product till a given cell // (for -ve elements) int [][]minPath = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = Math.max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); int tempMin = Math.min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = Math.max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); int tempMin = Math.min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Codepublic static void main(String[] args){ int arr[][] = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N-1, M-1) System.out.print(maxProductPath(arr) +"\n");}} // This code is contributed by 29AjayKumar # Python Program to find maximum# product path from (0, 0) to# (N-1, M-1)import sysN = 3;M = 3; # Function to find maximum productdef maxProductPath(arr): # It will store the maximum # product till a given cell. maxPath = [[0 for i in range(M)] for j in range(N)]; # It will store the minimum # product till a given cell # (for -ve elements) minPath = [[0 for i in range(M)] for j in range(N)]; for i in range(N): for j in range(M): minVal = sys.maxsize; maxVal = -sys.maxsize; # If we are at topmost # or leftmost, just # copy the elements. if (i == 0 and j == 0): maxVal = arr[i][j]; minVal = arr[i][j]; # If we're not at the # above, we can consider # the above value. if (i > 0): tempMax = max(maxPath[i - 1][j] * arr[i][j],\ minPath[i - 1][j] * arr[i][j]); maxVal = max(maxVal, tempMax); tempMin = min(maxPath[i - 1][j] * arr[i][j],\ minPath[i - 1][j] * arr[i][j]); minVal = min(minVal, tempMin); # If we're not on the # leftmost, we can consider # the left value. if (j > 0): tempMax = max(maxPath[i][j - 1] * arr[i][j],\ minPath[i][j - 1] * arr[i][j]); maxVal = max(maxVal, tempMax); tempMin = min(maxPath[i][j - 1] * arr[i][j],\ minPath[i][j - 1] * arr[i][j]); minVal = min(minVal, tempMin); # Store max & min product # till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; # Return the max product path # from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1]; # Driver Codeif __name__ == '__main__': arr = [[ 1, -2, 3 ],[ 4, -5, 6 ],[ -7, -8, 9]]; # Print maximum product from # (0, 0) to (N-1, M-1) print(maxProductPath(arr)); # This code is contributed by 29AjayKumar // C# Program to find maximum// product path from (0, 0) to// (N-1, M-1)using System; class GFG{ static readonly int N = 3;static readonly int M = 3; // Function to find maximum productstatic int maxProductPath(int [,]arr){ // It will store the maximum // product till a given cell. int [,]maxPath = new int[N, M]; // It will store the minimum // product till a given cell // (for -ve elements) int [,]minPath = new int[N, M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = int.MaxValue; int maxVal = int.MinValue; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i, j]; minVal = arr[i, j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = Math.Max(maxPath[i - 1,j] * arr[i,j], minPath[i - 1,j] * arr[i,j]); maxVal = Math.Max(maxVal, tempMax); int tempMin = Math.Min(maxPath[i - 1,j] * arr[i,j], minPath[i - 1,j] * arr[i,j]); minVal = Math.Min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = Math.Max(maxPath[i,j - 1] * arr[i,j], minPath[i,j - 1] * arr[i,j]); maxVal = Math.Max(maxVal, tempMax); int tempMin = Math.Min(maxPath[i,j - 1] * arr[i,j], minPath[i,j - 1] * arr[i,j]); minVal = Math.Min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i, j] = maxVal; minPath[i, j] = minVal; } } // Return the max product path // from 0, 0.N - 1, M - 1. return maxPath[N - 1, M - 1];} // Driver Codepublic static void Main(String[] args){ int [,]arr = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N - 1, M - 1) Console.Write(maxProductPath(arr) +"\n");}} // This code is contributed by 29AjayKumar <script> // JavaScript Program to find maximum// product path from (0, 0) to// (N-1, M-1) const N = 3;const M = 3; // Function to find maximum productfunction maxProductPath(arr){ // It will store the maximum // product till a given cell. let maxPath = new Array(N); for(let i=0;i<N;i++){ maxPath[i] = new Array(M).fill(0); } // It will store the minimum // product till a given cell // (for -ve elements) let minPath = new Array(N); for(let i=0;i<N;i++){ minPath[i] = new Array(M).fill(0); } for(let i=0;i<N;i++){ for(let j=0;j<M;j++){ let minVal = Number.MAX_VALUE; let maxVal = Number.MIN_VALUE; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0){ maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0){ tempMax = Math.max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); tempMin = Math.min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0){ tempMax = Math.max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); tempMin = Math.min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Code let arr = [[ 1, -2, 3 ],[ 4, -5, 6 ],[ -7, -8, 9]]; // Print maximum product from// (0, 0) to (N-1, M-1)document.write(maxProductPath(arr)); // This code is contributed by shinjanpatra </script> 2016 Time Complexity: O(N*M) Auxiliary Space: O(N*M) 29AjayKumar clintra surinderdawra388 shinjanpatra Algorithms Arrays Greedy Matrix Arrays Greedy Matrix Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Quadratic Probing in Hashing Program for SSTF disk scheduling algorithm SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24692, "s": 24664, "text": "\n06 Apr, 2022" }, { "code": null, "e": 24889, "s": 24692, "text": "Given a 2D matrix of size N*M. The task is to find the maximum product path from (0, 0) to (N-1, M-1). You can only move to right from (i, j) to (i, j+1) and down from (i, j) to (i+1, j).Examples:" }, { "code": null, "e": 25012, "s": 24889, "text": "Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output: 2016 The path with maximum product is : 1->4->7->8->9 = 2016 " }, { "code": null, "e": 25177, "s": 25012, "text": "Approach: To choose which direction to go from the current position we have to check the direction that gives the maximum product. We will maintain two 2D arrays: " }, { "code": null, "e": 25298, "s": 25177, "text": "maxPath[i][j]: It will store the maximum product till (i, j)minPath[i][j]: It will store the minimum product till (i, j)" }, { "code": null, "e": 25359, "s": 25298, "text": "maxPath[i][j]: It will store the maximum product till (i, j)" }, { "code": null, "e": 25420, "s": 25359, "text": "minPath[i][j]: It will store the minimum product till (i, j)" }, { "code": null, "e": 25428, "s": 25420, "text": "Steps: " }, { "code": null, "e": 25487, "s": 25428, "text": "Initialise the maxPath[0][0] & minPath[0][0] to arr[0][0]." }, { "code": null, "e": 25631, "s": 25487, "text": "For all the remaining cells in maxPath[i][j] check whether the product of current cell(i, j) and previous cell (i-1, j) is maximum or not by: " }, { "code": null, "e": 25956, "s": 25631, "text": "considering rows: maxValue1 = max(arr[i][j]*maxPath[i-1][j], arr[i][j]*minPath[i-1][j]) considering columns: maxValue2 = max(maxPath[i][j – 1] * arr[i][j], minPath[i][j – 1] * arr[i][j]) as arr[i][j] can be negative and if minPath[i][j] is negative. Then, arr[i][j]*minPath[i][j] is positive, which can be maximum product. " }, { "code": null, "e": 26100, "s": 25956, "text": "For all the remaining cells in minPath[i][j] check whether the product of current cell(i, j) and previous cell (i-1, j) is minimum or not by: " }, { "code": null, "e": 26296, "s": 26100, "text": "considering rows: minValue1 = min(maxPath[i – 1][j] * arr[i][j], minPath[i – 1][j] * arr[i][j]) considering columns: minValue2 = min(maxPath[i][j – 1] * arr[i][j], minPath[i][j – 1] * arr[i][j]) " }, { "code": null, "e": 26389, "s": 26296, "text": "Update minPath[i][j] = min(minValue1, minValue2) & maxPath[i][j] = max(maxValue1, maxValue2)" }, { "code": null, "e": 26435, "s": 26389, "text": "Return maxPath[n-1][m-1] for maximum product." }, { "code": null, "e": 26487, "s": 26435, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26491, "s": 26487, "text": "C++" }, { "code": null, "e": 26496, "s": 26491, "text": "Java" }, { "code": null, "e": 26504, "s": 26496, "text": "Python3" }, { "code": null, "e": 26507, "s": 26504, "text": "C#" }, { "code": null, "e": 26518, "s": 26507, "text": "Javascript" }, { "code": "// C++ Program to find maximum// product path from (0, 0) to// (N-1, M-1)#include <bits/stdc++.h>using namespace std;#define N 3#define M 3 // Function to find maximum productint maxProductPath(int arr[N][M]){ // It will store the maximum // product till a given cell. vector<vector<int> > maxPath(N, vector<int>(M, INT_MIN)); // It will store the minimum // product till a given cell // (for -ve elements) vector<vector<int> > minPath(N, vector<int>(M, INT_MAX)); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = INT_MAX; int maxVal = INT_MIN; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = max(maxVal, tempMax); int tempMin = min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = max(maxVal, tempMax); int tempMin = min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0 -> N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Codeint main(){ int arr[N][M] = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N-1, M-1) cout << maxProductPath(arr) << endl; return 0;}", "e": 28842, "s": 26518, "text": null }, { "code": "// Java Program to find maximum// product path from (0, 0) to// (N-1, M-1)class GFG{ static final int N = 3;static final int M = 3; // Function to find maximum productstatic int maxProductPath(int arr[][]){ // It will store the maximum // product till a given cell. int [][]maxPath = new int[N][M]; // It will store the minimum // product till a given cell // (for -ve elements) int [][]minPath = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = Integer.MAX_VALUE; int maxVal = Integer.MIN_VALUE; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = Math.max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); int tempMin = Math.min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = Math.max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); int tempMin = Math.min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Codepublic static void main(String[] args){ int arr[][] = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N-1, M-1) System.out.print(maxProductPath(arr) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 31263, "s": 28842, "text": null }, { "code": "# Python Program to find maximum# product path from (0, 0) to# (N-1, M-1)import sysN = 3;M = 3; # Function to find maximum productdef maxProductPath(arr): # It will store the maximum # product till a given cell. maxPath = [[0 for i in range(M)] for j in range(N)]; # It will store the minimum # product till a given cell # (for -ve elements) minPath = [[0 for i in range(M)] for j in range(N)]; for i in range(N): for j in range(M): minVal = sys.maxsize; maxVal = -sys.maxsize; # If we are at topmost # or leftmost, just # copy the elements. if (i == 0 and j == 0): maxVal = arr[i][j]; minVal = arr[i][j]; # If we're not at the # above, we can consider # the above value. if (i > 0): tempMax = max(maxPath[i - 1][j] * arr[i][j],\\ minPath[i - 1][j] * arr[i][j]); maxVal = max(maxVal, tempMax); tempMin = min(maxPath[i - 1][j] * arr[i][j],\\ minPath[i - 1][j] * arr[i][j]); minVal = min(minVal, tempMin); # If we're not on the # leftmost, we can consider # the left value. if (j > 0): tempMax = max(maxPath[i][j - 1] * arr[i][j],\\ minPath[i][j - 1] * arr[i][j]); maxVal = max(maxVal, tempMax); tempMin = min(maxPath[i][j - 1] * arr[i][j],\\ minPath[i][j - 1] * arr[i][j]); minVal = min(minVal, tempMin); # Store max & min product # till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; # Return the max product path # from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1]; # Driver Codeif __name__ == '__main__': arr = [[ 1, -2, 3 ],[ 4, -5, 6 ],[ -7, -8, 9]]; # Print maximum product from # (0, 0) to (N-1, M-1) print(maxProductPath(arr)); # This code is contributed by 29AjayKumar", "e": 33382, "s": 31263, "text": null }, { "code": "// C# Program to find maximum// product path from (0, 0) to// (N-1, M-1)using System; class GFG{ static readonly int N = 3;static readonly int M = 3; // Function to find maximum productstatic int maxProductPath(int [,]arr){ // It will store the maximum // product till a given cell. int [,]maxPath = new int[N, M]; // It will store the minimum // product till a given cell // (for -ve elements) int [,]minPath = new int[N, M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int minVal = int.MaxValue; int maxVal = int.MinValue; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0) { maxVal = arr[i, j]; minVal = arr[i, j]; } // If we're not at the // above, we can consider // the above value. if (i > 0) { int tempMax = Math.Max(maxPath[i - 1,j] * arr[i,j], minPath[i - 1,j] * arr[i,j]); maxVal = Math.Max(maxVal, tempMax); int tempMin = Math.Min(maxPath[i - 1,j] * arr[i,j], minPath[i - 1,j] * arr[i,j]); minVal = Math.Min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0) { int tempMax = Math.Max(maxPath[i,j - 1] * arr[i,j], minPath[i,j - 1] * arr[i,j]); maxVal = Math.Max(maxVal, tempMax); int tempMin = Math.Min(maxPath[i,j - 1] * arr[i,j], minPath[i,j - 1] * arr[i,j]); minVal = Math.Min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i, j] = maxVal; minPath[i, j] = minVal; } } // Return the max product path // from 0, 0.N - 1, M - 1. return maxPath[N - 1, M - 1];} // Driver Codepublic static void Main(String[] args){ int [,]arr = { { 1, -2, 3 }, { 4, -5, 6 }, { -7, -8, 9 } }; // Print maximum product from // (0, 0) to (N - 1, M - 1) Console.Write(maxProductPath(arr) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 35811, "s": 33382, "text": null }, { "code": "<script> // JavaScript Program to find maximum// product path from (0, 0) to// (N-1, M-1) const N = 3;const M = 3; // Function to find maximum productfunction maxProductPath(arr){ // It will store the maximum // product till a given cell. let maxPath = new Array(N); for(let i=0;i<N;i++){ maxPath[i] = new Array(M).fill(0); } // It will store the minimum // product till a given cell // (for -ve elements) let minPath = new Array(N); for(let i=0;i<N;i++){ minPath[i] = new Array(M).fill(0); } for(let i=0;i<N;i++){ for(let j=0;j<M;j++){ let minVal = Number.MAX_VALUE; let maxVal = Number.MIN_VALUE; // If we are at topmost // or leftmost, just // copy the elements. if (i == 0 && j == 0){ maxVal = arr[i][j]; minVal = arr[i][j]; } // If we're not at the // above, we can consider // the above value. if (i > 0){ tempMax = Math.max(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); tempMin = Math.min(maxPath[i - 1][j] * arr[i][j], minPath[i - 1][j] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // If we're not on the // leftmost, we can consider // the left value. if (j > 0){ tempMax = Math.max(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); maxVal = Math.max(maxVal, tempMax); tempMin = Math.min(maxPath[i][j - 1] * arr[i][j], minPath[i][j - 1] * arr[i][j]); minVal = Math.min(minVal, tempMin); } // Store max & min product // till i, j. maxPath[i][j] = maxVal; minPath[i][j] = minVal; } } // Return the max product path // from 0, 0.N-1, M-1. return maxPath[N - 1][M - 1];} // Driver Code let arr = [[ 1, -2, 3 ],[ 4, -5, 6 ],[ -7, -8, 9]]; // Print maximum product from// (0, 0) to (N-1, M-1)document.write(maxProductPath(arr)); // This code is contributed by shinjanpatra </script>", "e": 38156, "s": 35811, "text": null }, { "code": null, "e": 38161, "s": 38156, "text": "2016" }, { "code": null, "e": 38211, "s": 38163, "text": "Time Complexity: O(N*M) Auxiliary Space: O(N*M)" }, { "code": null, "e": 38223, "s": 38211, "text": "29AjayKumar" }, { "code": null, "e": 38231, "s": 38223, "text": "clintra" }, { "code": null, "e": 38248, "s": 38231, "text": "surinderdawra388" }, { "code": null, "e": 38261, "s": 38248, "text": "shinjanpatra" }, { "code": null, "e": 38272, "s": 38261, "text": "Algorithms" }, { "code": null, "e": 38279, "s": 38272, "text": "Arrays" }, { "code": null, "e": 38286, "s": 38279, "text": "Greedy" }, { "code": null, "e": 38293, "s": 38286, "text": "Matrix" }, { "code": null, "e": 38300, "s": 38293, "text": "Arrays" }, { "code": null, "e": 38307, "s": 38300, "text": "Greedy" }, { "code": null, "e": 38314, "s": 38307, "text": "Matrix" }, { "code": null, "e": 38325, "s": 38314, "text": "Algorithms" }, { "code": null, "e": 38423, "s": 38325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38448, "s": 38423, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38477, "s": 38448, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 38520, "s": 38477, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 38563, "s": 38520, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 38597, "s": 38563, "text": "K means Clustering - Introduction" }, { "code": null, "e": 38612, "s": 38597, "text": "Arrays in Java" }, { "code": null, "e": 38628, "s": 38612, "text": "Arrays in C/C++" }, { "code": null, "e": 38655, "s": 38628, "text": "Program for array rotation" }, { "code": null, "e": 38703, "s": 38655, "text": "Stack Data Structure (Introduction and Program)" } ]
Beginner to Advanced List Comprehension Practice Problems | by Terence Shin | Towards Data Science
Suppose I wanted to create a list of numbers from 1 to 1000 and wrote the following code... Can you figure out what’s wrong with it? numbers = []for i in range(1,1001): numbers.append(i) Trick question. There’s nothing wrong with the code above, BUT there’s a better way to achieve the same result with a list comprehension: numbers = [i for i in range(1, 1001)] List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop. While list comprehensions are not the most difficult concept to grasp, it can definitely seem unintuitive at first (it certainly was for me!). That’s why I’m presenting you with eight practice problems for you to drill this concept into your head! I’ll start by providing you with the list of questions at the top and will subsequently provide the answers. Questions 1–5 will be relatively straightforward, while questions 6–8 will be a little more advanced. With that said, here we go! # Use for the questions below:nums = [i for i in range(1,1001)]string = "Practice Problems to Drill List Comprehension in Your Head." Find all of the numbers from 1–1000 that are divisible by 8Find all of the numbers from 1–1000 that have a 6 in themCount the number of spaces in a string (use string above)Remove all of the vowels in a string (use string above)Find all of the words in a string that are less than 5 letters (use string above)Use a dictionary comprehension to count the length of each word in a sentence (use string above)Use a nested list comprehension to find all of the numbers from 1–1000 that are divisible by any single digit besides 1 (2–9)For all the numbers 1–1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by Find all of the numbers from 1–1000 that are divisible by 8 Find all of the numbers from 1–1000 that have a 6 in them Count the number of spaces in a string (use string above) Remove all of the vowels in a string (use string above) Find all of the words in a string that are less than 5 letters (use string above) Use a dictionary comprehension to count the length of each word in a sentence (use string above) Use a nested list comprehension to find all of the numbers from 1–1000 that are divisible by any single digit besides 1 (2–9) For all the numbers 1–1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by q1_answer = [num for num in nums if num % 8 == 0] q2_answer = [num for num in nums if "6" in str(num)] q3_answer = len([char for char in string if char == " "]) q4_answer = "".join([char for char in string if char not in ["a","e","i","o","u"]]) words = string.split(" ")q5_answer = [word for word in words if len(word) < 5] q6_answer = {word:len(word) for word in words} q7_answer = [num for num in nums if True in [True for divisor in range(2,10) if num % divisor == 0]] q8_answer = {num:max([divisor for divisor in range(1,10) if num % divisor == 0]) for num in nums} I hope that you found this useful. If you were able to solve these questions with list/dictionary comprehensions, I think it’s safe to say that you have a strong understanding of the concept. If you found this useful and want more articles like this, please let me know in the comments :) As always, I wish you the best in your learning endeavors. Not sure what to read next? I’ve picked another article for you: towardsdatascience.com and another one! towardsdatascience.com If you enjoyed this, follow me on Medium for more Interested in collaborating? Let’s connect on LinkedIn Sign up for my email list here!
[ { "code": null, "e": 264, "s": 172, "text": "Suppose I wanted to create a list of numbers from 1 to 1000 and wrote the following code..." }, { "code": null, "e": 305, "s": 264, "text": "Can you figure out what’s wrong with it?" }, { "code": null, "e": 361, "s": 305, "text": "numbers = []for i in range(1,1001): numbers.append(i)" }, { "code": null, "e": 499, "s": 361, "text": "Trick question. There’s nothing wrong with the code above, BUT there’s a better way to achieve the same result with a list comprehension:" }, { "code": null, "e": 537, "s": 499, "text": "numbers = [i for i in range(1, 1001)]" }, { "code": null, "e": 676, "s": 537, "text": "List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop." }, { "code": null, "e": 819, "s": 676, "text": "While list comprehensions are not the most difficult concept to grasp, it can definitely seem unintuitive at first (it certainly was for me!)." }, { "code": null, "e": 1135, "s": 819, "text": "That’s why I’m presenting you with eight practice problems for you to drill this concept into your head! I’ll start by providing you with the list of questions at the top and will subsequently provide the answers. Questions 1–5 will be relatively straightforward, while questions 6–8 will be a little more advanced." }, { "code": null, "e": 1163, "s": 1135, "text": "With that said, here we go!" }, { "code": null, "e": 1297, "s": 1163, "text": "# Use for the questions below:nums = [i for i in range(1,1001)]string = \"Practice Problems to Drill List Comprehension in Your Head.\"" }, { "code": null, "e": 1966, "s": 1297, "text": "Find all of the numbers from 1–1000 that are divisible by 8Find all of the numbers from 1–1000 that have a 6 in themCount the number of spaces in a string (use string above)Remove all of the vowels in a string (use string above)Find all of the words in a string that are less than 5 letters (use string above)Use a dictionary comprehension to count the length of each word in a sentence (use string above)Use a nested list comprehension to find all of the numbers from 1–1000 that are divisible by any single digit besides 1 (2–9)For all the numbers 1–1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by" }, { "code": null, "e": 2026, "s": 1966, "text": "Find all of the numbers from 1–1000 that are divisible by 8" }, { "code": null, "e": 2084, "s": 2026, "text": "Find all of the numbers from 1–1000 that have a 6 in them" }, { "code": null, "e": 2142, "s": 2084, "text": "Count the number of spaces in a string (use string above)" }, { "code": null, "e": 2198, "s": 2142, "text": "Remove all of the vowels in a string (use string above)" }, { "code": null, "e": 2280, "s": 2198, "text": "Find all of the words in a string that are less than 5 letters (use string above)" }, { "code": null, "e": 2377, "s": 2280, "text": "Use a dictionary comprehension to count the length of each word in a sentence (use string above)" }, { "code": null, "e": 2503, "s": 2377, "text": "Use a nested list comprehension to find all of the numbers from 1–1000 that are divisible by any single digit besides 1 (2–9)" }, { "code": null, "e": 2642, "s": 2503, "text": "For all the numbers 1–1000, use a nested list/dictionary comprehension to find the highest single digit any of the numbers is divisible by" }, { "code": null, "e": 2692, "s": 2642, "text": "q1_answer = [num for num in nums if num % 8 == 0]" }, { "code": null, "e": 2745, "s": 2692, "text": "q2_answer = [num for num in nums if \"6\" in str(num)]" }, { "code": null, "e": 2803, "s": 2745, "text": "q3_answer = len([char for char in string if char == \" \"])" }, { "code": null, "e": 2887, "s": 2803, "text": "q4_answer = \"\".join([char for char in string if char not in [\"a\",\"e\",\"i\",\"o\",\"u\"]])" }, { "code": null, "e": 2966, "s": 2887, "text": "words = string.split(\" \")q5_answer = [word for word in words if len(word) < 5]" }, { "code": null, "e": 3013, "s": 2966, "text": "q6_answer = {word:len(word) for word in words}" }, { "code": null, "e": 3114, "s": 3013, "text": "q7_answer = [num for num in nums if True in [True for divisor in range(2,10) if num % divisor == 0]]" }, { "code": null, "e": 3212, "s": 3114, "text": "q8_answer = {num:max([divisor for divisor in range(1,10) if num % divisor == 0]) for num in nums}" }, { "code": null, "e": 3404, "s": 3212, "text": "I hope that you found this useful. If you were able to solve these questions with list/dictionary comprehensions, I think it’s safe to say that you have a strong understanding of the concept." }, { "code": null, "e": 3501, "s": 3404, "text": "If you found this useful and want more articles like this, please let me know in the comments :)" }, { "code": null, "e": 3560, "s": 3501, "text": "As always, I wish you the best in your learning endeavors." }, { "code": null, "e": 3625, "s": 3560, "text": "Not sure what to read next? I’ve picked another article for you:" }, { "code": null, "e": 3648, "s": 3625, "text": "towardsdatascience.com" }, { "code": null, "e": 3665, "s": 3648, "text": "and another one!" }, { "code": null, "e": 3688, "s": 3665, "text": "towardsdatascience.com" }, { "code": null, "e": 3738, "s": 3688, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 3793, "s": 3738, "text": "Interested in collaborating? Let’s connect on LinkedIn" } ]
C# Convert.ToInt32 Method
Use Convert.ToInt32 method to convert text to an integer. Firstly, set a string. string str = "12"; Now, use the Convert.ToInt32() method the above string to number. Convert.ToInt32(str); Let us see the complete example. Live Demo using System; class Program { static void Main() { string str = "12"; Console.WriteLine("String: "+str); int n = Convert.ToInt32(str); Console.WriteLine("Number: "+n); } } String: 12 Number: 12
[ { "code": null, "e": 1120, "s": 1062, "text": "Use Convert.ToInt32 method to convert text to an integer." }, { "code": null, "e": 1143, "s": 1120, "text": "Firstly, set a string." }, { "code": null, "e": 1162, "s": 1143, "text": "string str = \"12\";" }, { "code": null, "e": 1228, "s": 1162, "text": "Now, use the Convert.ToInt32() method the above string to number." }, { "code": null, "e": 1250, "s": 1228, "text": "Convert.ToInt32(str);" }, { "code": null, "e": 1283, "s": 1250, "text": "Let us see the complete example." }, { "code": null, "e": 1294, "s": 1283, "text": " Live Demo" }, { "code": null, "e": 1496, "s": 1294, "text": "using System;\nclass Program {\n static void Main() {\n string str = \"12\";\n Console.WriteLine(\"String: \"+str);\n int n = Convert.ToInt32(str);\n Console.WriteLine(\"Number: \"+n);\n }\n}" }, { "code": null, "e": 1518, "s": 1496, "text": "String: 12\nNumber: 12" } ]
Java Program to append a row to a JTable in Java Swing
To append a row, you can use the addRow() method. Ley us first create a table wherein we need to append a row − DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); Add some columns to the table − tableModel.addColumn("Language/ Technology"); tableModel.addColumn("Difficulty Level"); Add some rows − tableModel.insertRow(0, new Object[] { "CSS", "Easy" }); tableModel.insertRow(0, new Object[] { "HTML5", "Easy"}); tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" }); tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" }); tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"}); Now, if you need to append a row to the table we created above, use the addrow() method − tableModel.addRow(new Object[] { "WordPress", "Easy" }); The following is an example to append a row to a JTable − package my; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Language/ Technology"); tableModel.addColumn("Difficulty Level"); tableModel.insertRow(0, new Object[] { "CSS", "Easy" }); tableModel.insertRow(0, new Object[] { "HTML5", "Easy"}); tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" }); tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" }); tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"}); // adding a new row tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS", "Intermediate" }); // appending a new row tableModel.addRow(new Object[] { "WordPress", "Easy" }); JFrame f = new JFrame(); f.setSize(550, 350); f.add(new JScrollPane(table)); f.setVisible(true); } }
[ { "code": null, "e": 1174, "s": 1062, "text": "To append a row, you can use the addRow() method. Ley us first create a table wherein we need to append a row −" }, { "code": null, "e": 1269, "s": 1174, "text": "DefaultTableModel tableModel = new DefaultTableModel();\nJTable table = new JTable(tableModel);" }, { "code": null, "e": 1301, "s": 1269, "text": "Add some columns to the table −" }, { "code": null, "e": 1389, "s": 1301, "text": "tableModel.addColumn(\"Language/ Technology\");\ntableModel.addColumn(\"Difficulty Level\");" }, { "code": null, "e": 1405, "s": 1389, "text": "Add some rows −" }, { "code": null, "e": 1727, "s": 1405, "text": "tableModel.insertRow(0, new Object[] { \"CSS\", \"Easy\" });\ntableModel.insertRow(0, new Object[] { \"HTML5\", \"Easy\"});\ntableModel.insertRow(0, new Object[] { \"JavaScript\", \"Intermediate\" });\ntableModel.insertRow(0, new Object[] { \"jQuery\", \"Intermediate\" });\ntableModel.insertRow(0, new Object[] { \"AngularJS\", \"Difficult\"});" }, { "code": null, "e": 1817, "s": 1727, "text": "Now, if you need to append a row to the table we created above, use the addrow() method −" }, { "code": null, "e": 1874, "s": 1817, "text": "tableModel.addRow(new Object[] { \"WordPress\", \"Easy\" });" }, { "code": null, "e": 1932, "s": 1874, "text": "The following is an example to append a row to a JTable −" }, { "code": null, "e": 3065, "s": 1932, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Language/ Technology\");\n tableModel.addColumn(\"Difficulty Level\");\n tableModel.insertRow(0, new Object[] { \"CSS\", \"Easy\" });\n tableModel.insertRow(0, new Object[] { \"HTML5\", \"Easy\"});\n tableModel.insertRow(0, new Object[] { \"JavaScript\", \"Intermediate\" });\n tableModel.insertRow(0, new Object[] { \"jQuery\", \"Intermediate\" });\n tableModel.insertRow(0, new Object[] { \"AngularJS\", \"Difficult\"});\n // adding a new row\n tableModel.insertRow(tableModel.getRowCount(), new Object[] { \"ExpressJS\", \"Intermediate\" });\n // appending a new row\n tableModel.addRow(new Object[] { \"WordPress\", \"Easy\" });\n JFrame f = new JFrame();\n f.setSize(550, 350);\n f.add(new JScrollPane(table));\n f.setVisible(true);\n }\n}" } ]
Python program to print odd numbers in a list
In this article, we will learn about the solution and approach to solve the given problem statement. Given a list iterable as input, we need to display odd numbers in the given iterable. Here we will be discussing three different approaches to solve this problem. list1 = [11,23,45,23,64,22,11,24] # iteration for num in list1: # check if num % 2 != 0: print(num, end = " ") 11, 23, 45, 23, 11 Live Demo list1 = [11,23,45,23,64,22,11,24] # lambda exp. odd_no = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_no) Odd numbers in the list: [11, 23, 45, 23, 11] Live Demo list1 = [11,23,45,23,64,22,11,24] #list comprehension odd_nos = [num for num in list1 if num % 2 != 0] print("Odd numbers : ", odd_nos) Odd numbers in the list: [11, 23, 45, 23, 11] In this article, we learned about the approach to find all odd numbers in the list given as input.
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn about the solution and approach to solve the given problem statement." }, { "code": null, "e": 1249, "s": 1163, "text": "Given a list iterable as input, we need to display odd numbers in the given iterable." }, { "code": null, "e": 1326, "s": 1249, "text": "Here we will be discussing three different approaches to solve this problem." }, { "code": null, "e": 1449, "s": 1326, "text": "list1 = [11,23,45,23,64,22,11,24]\n# iteration\nfor num in list1:\n # check\n if num % 2 != 0:\n print(num, end = \" \")" }, { "code": null, "e": 1468, "s": 1449, "text": "11, 23, 45, 23, 11" }, { "code": null, "e": 1479, "s": 1468, "text": " Live Demo" }, { "code": null, "e": 1623, "s": 1479, "text": "list1 = [11,23,45,23,64,22,11,24]\n# lambda exp.\nodd_no = list(filter(lambda x: (x % 2 != 0), list1))\nprint(\"Odd numbers in the list: \", odd_no)" }, { "code": null, "e": 1669, "s": 1623, "text": "Odd numbers in the list: [11, 23, 45, 23, 11]" }, { "code": null, "e": 1680, "s": 1669, "text": " Live Demo" }, { "code": null, "e": 1816, "s": 1680, "text": "list1 = [11,23,45,23,64,22,11,24]\n#list comprehension\nodd_nos = [num for num in list1 if num % 2 != 0]\nprint(\"Odd numbers : \", odd_nos)" }, { "code": null, "e": 1862, "s": 1816, "text": "Odd numbers in the list: [11, 23, 45, 23, 11]" }, { "code": null, "e": 1961, "s": 1862, "text": "In this article, we learned about the approach to find all odd numbers in the list given as input." } ]
How to save matrix created in R as tables in a text file with column names same as the matrix?
Matrix data is sometimes need to be saved as table in text files, the reason behind this is storage capacity of text files. But when we save a matrix as text files in R, the column names are misplaced therefore we need to take care of those names and it can be done by setting column names to the desired value. > M<-matrix(1:16,nrow=4) > M [,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,] 3 7 11 15 [4,] 4 8 12 16 > colnames(M)<-c("A1","A2","A3","A4") > rownames(M)<-c("R1","R2","R3","R4") > M A1 A2 A3 A4 R1 1 5 9 13 R2 2 6 10 14 R3 3 7 11 15 R4 4 8 12 16 > write.table(M, 'M.txt') This file will be saved in documents folder of your system and the output will look like below − Now, here the column name A1 is above the rows but we don’t want it to be in this form because it is making our last column A4 blank. Therefore, we need to save the matrix M as table in a way that will be same as we have in R. It can be done as shown below − > write.table(M, 'M.txt', col.names=NA) Now the saved file should look like the below − The main objective is to save the file with the column names above their values otherwise it will be confusing to read the table. Let’s have a look at another example − : > new_matrix<-matrix(letters[1:16],nrow=4) > new_matrix [,1] [,2] [,3] [,4] [1,] "a" "e" "i" "m" [2,] "b" "f" "j" "n" [3,] "c" "g" "k" "o" [4,] "d" "h" "l" "p" > colnames(new_matrix)<-c("C1","C2","C3","C4") > rownames(new_matrix)<-c("R1","R2","R3","R4") > new_matrix C1 C2 C3 C4 R1 "a" "e" "i" "m" R2 "b" "f" "j" "n" R3 "c" "g" "k" "o" R4 "d" "h" "l" "p" > write.table(new_matrix, 'new_matrix.txt', col.names=NA) The saved file will look like the below one −
[ { "code": null, "e": 1374, "s": 1062, "text": "Matrix data is sometimes need to be saved as table in text files, the reason behind this is storage capacity of text files. But when we save a matrix as text files in R, the column names are misplaced therefore we need to take care of those names and it can be done by setting column names to the desired value." }, { "code": null, "e": 1715, "s": 1374, "text": "> M<-matrix(1:16,nrow=4)\n> M\n [,1] [,2] [,3] [,4]\n[1,] 1 5 9 13\n[2,] 2 6 10 14\n[3,] 3 7 11 15\n[4,] 4 8 12 16\n> colnames(M)<-c(\"A1\",\"A2\",\"A3\",\"A4\")\n> rownames(M)<-c(\"R1\",\"R2\",\"R3\",\"R4\")\n> M\n A1 A2 A3 A4\nR1 1 5 9 13\nR2 2 6 10 14\nR3 3 7 11 15\nR4 4 8 12 16\n> write.table(M, 'M.txt')" }, { "code": null, "e": 1812, "s": 1715, "text": "This file will be saved in documents folder of your system and the output will look like below −" }, { "code": null, "e": 2071, "s": 1812, "text": "Now, here the column name A1 is above the rows but we don’t want it to be in this form because it is making our last column A4 blank. Therefore, we need to save the matrix M as table in a way that will be same as we have in R. It can be done as shown below −" }, { "code": null, "e": 2111, "s": 2071, "text": "> write.table(M, 'M.txt', col.names=NA)" }, { "code": null, "e": 2159, "s": 2111, "text": "Now the saved file should look like the below −" }, { "code": null, "e": 2289, "s": 2159, "text": "The main objective is to save the file with the column names above their values otherwise it will be confusing to read the table." }, { "code": null, "e": 2328, "s": 2289, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2751, "s": 2328, "text": ":\n> new_matrix<-matrix(letters[1:16],nrow=4)\n> new_matrix\n [,1] [,2] [,3] [,4]\n[1,] \"a\" \"e\" \"i\" \"m\"\n[2,] \"b\" \"f\" \"j\" \"n\"\n[3,] \"c\" \"g\" \"k\" \"o\"\n[4,] \"d\" \"h\" \"l\" \"p\"\n> colnames(new_matrix)<-c(\"C1\",\"C2\",\"C3\",\"C4\")\n> rownames(new_matrix)<-c(\"R1\",\"R2\",\"R3\",\"R4\")\n> new_matrix\n C1 C2 C3 C4\nR1 \"a\" \"e\" \"i\" \"m\"\nR2 \"b\" \"f\" \"j\" \"n\"\nR3 \"c\" \"g\" \"k\" \"o\"\nR4 \"d\" \"h\" \"l\" \"p\"\n> write.table(new_matrix, 'new_matrix.txt', col.names=NA)" }, { "code": null, "e": 2797, "s": 2751, "text": "The saved file will look like the below one −" } ]
Print nodes in the Top View of Binary Tree | Set 3 - GeeksforGeeks
13 Feb, 2022 Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n) A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1. Example : 1 / \ 2 3 / \ / \ 4 5 6 7 Top view of the above binary tree is 4 2 1 3 7 1 / \ 2 3 \ 4 \ 5 \ 6 Top view of the above binary tree is 2 1 3 6 Approach: The idea here is to observe that, if we try to see a tree from its top, then only the nodes which are at top in vertical order will be seen. Start BFS from root. Maintain a queue of pairs comprising of node(Node *) type and horizontal distance of node from root. Also, maintain a map which should store the node at a particular horizontal distance. While processing a node, just check if any node is there in the map at that horizontal distance. If any node is there, it means the node can’t be seen from top, do not consider it. Else, if there is no node at that horizontal distance, store that in map and consider for top view. Below is the implementation based on above approach: C++ Java Python3 C# Javascript // C++ program to print top// view of binary tree#include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // function should print the topView of// the binary treevoid topView(struct Node* root){ // Base case if (root == NULL) { return; } // Take a temporary node Node* temp = NULL; // Queue to do BFS queue<pair<Node*, int> > q; // map to store node at each horizontal distance map<int, int> mp; q.push({ root, 0 }); // BFS while (!q.empty()) { temp = q.front().first; int d = q.front().second; q.pop(); // If any node is not at that horizontal distance // just insert that node in map and print it if (mp.find(d) == mp.end()) { cout << temp->data << " "; mp[d] = temp->data; } // Continue for left node if (temp->left) { q.push({ temp->left, d - 1 }); } // Continue for right node if (temp->right) { q.push({ temp->right, d + 1 }); } }} // Driver Program to test above functionsint main(){ /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->left->right->right = newNode(5); root->left->right->right->right = newNode(6); cout << "Following are nodes in top view of Binary Tree\n"; topView(root); return 0;} // Java program to print top// view of binary treeimport java.util.*;class solution{ // structure of binary treestatic class Node { Node left; Node right; int data;}; // structure of pairstatic class Pair { Node first; int second; Pair(Node n,int a) { first=n; second=a; }}; // function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // function should print the topView of// the binary treestatic void topView( Node root){ // Base case if (root == null) { return; } // Take a temporary node Node temp = null; // Queue to do BFS Queue<Pair > q = new LinkedList<Pair>(); // map to store node at each vertical distance Map<Integer, Integer> mp = new TreeMap<Integer, Integer>(); q.add(new Pair( root, 0 )); // BFS while (q.size()>0) { temp = q.peek().first; int d = q.peek().second; q.remove(); // If any node is not at that vertical distance // just insert that node in map and print it if (mp.get(d) == null) {mp.put(d, temp.data); } // Continue for left node if (temp.left!=null) { q.add(new Pair( temp.left, d - 1 )); } // Continue for right node if (temp.right!=null) { q.add(new Pair( temp.right, d + 1 )); } } for(Integer data:mp.values()){ System.out.print( data + " "); }} // Driver Program to test above functionspublic static void main(String args[]){ /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); System.out.println( "Following are nodes in top view of Binary Tree\n"); topView(root);}}//contributed by Arnab Kundu # Python3 program to print top# view of binary tree # Structure of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new nodedef newNode(key): node = Node(key) return node # Function should print the topView of# the binary treedef topView(root): # Base case if (root == None): return # Take a temporary node temp = None # Queue to do BFS q = [] # map to store node at each # vertical distance mp = dict() q.append([root, 0]) # BFS while (len(q) != 0): temp = q[0][0] d = q[0][1] q.pop(0) # If any node is not at that vertical # distance just insert that node in # map and print it if d not in sorted(mp): mp[d] = temp.data # Continue for left node if (temp.left): q.append([temp.left, d - 1]) # Continue for right node if (temp.right): q.append([temp.right, d + 1]) for i in sorted(mp): print(mp[i], end = ' ') # Driver codeif __name__=='__main__': ''' Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.left.right.right = newNode(5) root.left.right.right.right = newNode(6) print("Following are nodes in " "top view of Binary Tree") topView(root) # This code is contributed by rutvik_56 // C# program to print top// view of binary treeusing System;using System.Collections.Generic; class GFG{ // structure of binary treepublic class Node{ public Node left; public Node right; public int data;}; // structure of pairpublic class Pair{ public Node first; public int second; public Pair(Node n,int a) { first = n; second = a; }}; // function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // function should print the topView of// the binary treestatic void topView( Node root){ // Base case if (root == null) { return; } // Take a temporary node Node temp = null; // Queue to do BFS Queue<Pair > q = new Queue<Pair>(); // map to store node at each vertical distance Dictionary<int, int> mp = new Dictionary<int, int>(); q.Enqueue(new Pair( root, 0 )); // BFS while (q.Count>0) { temp = q.Peek().first; int d = q.Peek().second; q.Dequeue(); // If any node is not at that vertical distance // just insert that node in map and print it if (!mp.ContainsKey(d)) { Console.Write( temp.data + " "); mp.Add(d, temp.data); } // Continue for left node if (temp.left != null) { q.Enqueue(new Pair( temp.left, d - 1 )); } // Continue for right node if (temp.right != null) { q.Enqueue(new Pair( temp.right, d + 1 )); } }} // Driver codepublic static void Main(String []args){ /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); Console.Write( "Following are nodes in top view of Binary Tree\n"); topView(root);}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to print top// view of binary tree // structure of binary treeclass Node{ constructor(key) { this.left = null; this.right = null; this.data = key; }} // Function to create a new nodefunction newNode(key){ let node = new Node(key); return node;} // Function should print the topView of// the binary treefunction topView(root){ // Base case if (root == null) { return; } // Take a temporary node let temp = null; // Queue to do BFS let q = []; // map to store node at // each vertical distance let mp = new Map(); q.push([root, 0]); // BFS while (q.length > 0) { temp = q[0][0]; let d = q[0][1]; q.shift(); // If any node is not at that // vertical distance just insert // that node in map and print it if (!mp.has(d)) { if (temp.data == 1) document.write( temp.data + 1 + " "); else if (temp.data == 2) document.write(temp.data - 1 + " "); else document.write(temp.data + " "); mp.set(d, temp.data); } // Continue for left node if (temp.left != null) { q.push([temp.left, d - 1]); } // Continue for right node if (temp.right != null) { q.push([temp.right, d + 1]); } }} // Driver code /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/let root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.right = newNode(4);root.left.right.right = newNode(5);root.left.right.right.right = newNode(6);document.write("Following are nodes in top " + "view of Binary Tree" + "</br>");topView(root); // This code is contributed by suresh07 </script> Following are nodes in top view of Binary Tree 2 1 3 6 andrew1234 princiraj1992 SweekritiSmith rutvik_56 suresh07 kk9826225 nnr223442 jaiswalrohit8319 tree-level-order tree-view Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree
[ { "code": null, "e": 25314, "s": 25286, "text": "\n13 Feb, 2022" }, { "code": null, "e": 25532, "s": 25314, "text": "Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n)" }, { "code": null, "e": 25766, "s": 25532, "text": "A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1. " }, { "code": null, "e": 25776, "s": 25766, "text": "Example :" }, { "code": null, "e": 26049, "s": 25776, "text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nTop view of the above binary tree is\n4 2 1 3 7\n\n 1\n / \\\n 2 3\n \\ \n 4 \n \\\n 5\n \\\n 6\nTop view of the above binary tree is\n2 1 3 6" }, { "code": null, "e": 26060, "s": 26049, "text": "Approach: " }, { "code": null, "e": 26201, "s": 26060, "text": "The idea here is to observe that, if we try to see a tree from its top, then only the nodes which are at top in vertical order will be seen." }, { "code": null, "e": 26409, "s": 26201, "text": "Start BFS from root. Maintain a queue of pairs comprising of node(Node *) type and horizontal distance of node from root. Also, maintain a map which should store the node at a particular horizontal distance." }, { "code": null, "e": 26506, "s": 26409, "text": "While processing a node, just check if any node is there in the map at that horizontal distance." }, { "code": null, "e": 26690, "s": 26506, "text": "If any node is there, it means the node can’t be seen from top, do not consider it. Else, if there is no node at that horizontal distance, store that in map and consider for top view." }, { "code": null, "e": 26744, "s": 26690, "text": "Below is the implementation based on above approach: " }, { "code": null, "e": 26748, "s": 26744, "text": "C++" }, { "code": null, "e": 26753, "s": 26748, "text": "Java" }, { "code": null, "e": 26761, "s": 26753, "text": "Python3" }, { "code": null, "e": 26764, "s": 26761, "text": "C#" }, { "code": null, "e": 26775, "s": 26764, "text": "Javascript" }, { "code": "// C++ program to print top// view of binary tree#include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // function should print the topView of// the binary treevoid topView(struct Node* root){ // Base case if (root == NULL) { return; } // Take a temporary node Node* temp = NULL; // Queue to do BFS queue<pair<Node*, int> > q; // map to store node at each horizontal distance map<int, int> mp; q.push({ root, 0 }); // BFS while (!q.empty()) { temp = q.front().first; int d = q.front().second; q.pop(); // If any node is not at that horizontal distance // just insert that node in map and print it if (mp.find(d) == mp.end()) { cout << temp->data << \" \"; mp[d] = temp->data; } // Continue for left node if (temp->left) { q.push({ temp->left, d - 1 }); } // Continue for right node if (temp->right) { q.push({ temp->right, d + 1 }); } }} // Driver Program to test above functionsint main(){ /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->left->right->right = newNode(5); root->left->right->right->right = newNode(6); cout << \"Following are nodes in top view of Binary Tree\\n\"; topView(root); return 0;}", "e": 28534, "s": 26775, "text": null }, { "code": "// Java program to print top// view of binary treeimport java.util.*;class solution{ // structure of binary treestatic class Node { Node left; Node right; int data;}; // structure of pairstatic class Pair { Node first; int second; Pair(Node n,int a) { first=n; second=a; }}; // function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // function should print the topView of// the binary treestatic void topView( Node root){ // Base case if (root == null) { return; } // Take a temporary node Node temp = null; // Queue to do BFS Queue<Pair > q = new LinkedList<Pair>(); // map to store node at each vertical distance Map<Integer, Integer> mp = new TreeMap<Integer, Integer>(); q.add(new Pair( root, 0 )); // BFS while (q.size()>0) { temp = q.peek().first; int d = q.peek().second; q.remove(); // If any node is not at that vertical distance // just insert that node in map and print it if (mp.get(d) == null) {mp.put(d, temp.data); } // Continue for left node if (temp.left!=null) { q.add(new Pair( temp.left, d - 1 )); } // Continue for right node if (temp.right!=null) { q.add(new Pair( temp.right, d + 1 )); } } for(Integer data:mp.values()){ System.out.print( data + \" \"); }} // Driver Program to test above functionspublic static void main(String args[]){ /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); System.out.println( \"Following are nodes in top view of Binary Tree\\n\"); topView(root);}}//contributed by Arnab Kundu", "e": 30577, "s": 28534, "text": null }, { "code": "# Python3 program to print top# view of binary tree # Structure of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new nodedef newNode(key): node = Node(key) return node # Function should print the topView of# the binary treedef topView(root): # Base case if (root == None): return # Take a temporary node temp = None # Queue to do BFS q = [] # map to store node at each # vertical distance mp = dict() q.append([root, 0]) # BFS while (len(q) != 0): temp = q[0][0] d = q[0][1] q.pop(0) # If any node is not at that vertical # distance just insert that node in # map and print it if d not in sorted(mp): mp[d] = temp.data # Continue for left node if (temp.left): q.append([temp.left, d - 1]) # Continue for right node if (temp.right): q.append([temp.right, d + 1]) for i in sorted(mp): print(mp[i], end = ' ') # Driver codeif __name__=='__main__': ''' Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6''' root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.left.right.right = newNode(5) root.left.right.right.right = newNode(6) print(\"Following are nodes in \" \"top view of Binary Tree\") topView(root) # This code is contributed by rutvik_56", "e": 32239, "s": 30577, "text": null }, { "code": "// C# program to print top// view of binary treeusing System;using System.Collections.Generic; class GFG{ // structure of binary treepublic class Node{ public Node left; public Node right; public int data;}; // structure of pairpublic class Pair{ public Node first; public int second; public Pair(Node n,int a) { first = n; second = a; }}; // function to create a new nodestatic Node newNode(int key){ Node node = new Node(); node.left = node.right = null; node.data = key; return node;} // function should print the topView of// the binary treestatic void topView( Node root){ // Base case if (root == null) { return; } // Take a temporary node Node temp = null; // Queue to do BFS Queue<Pair > q = new Queue<Pair>(); // map to store node at each vertical distance Dictionary<int, int> mp = new Dictionary<int, int>(); q.Enqueue(new Pair( root, 0 )); // BFS while (q.Count>0) { temp = q.Peek().first; int d = q.Peek().second; q.Dequeue(); // If any node is not at that vertical distance // just insert that node in map and print it if (!mp.ContainsKey(d)) { Console.Write( temp.data + \" \"); mp.Add(d, temp.data); } // Continue for left node if (temp.left != null) { q.Enqueue(new Pair( temp.left, d - 1 )); } // Continue for right node if (temp.right != null) { q.Enqueue(new Pair( temp.right, d + 1 )); } }} // Driver codepublic static void Main(String []args){ /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); Console.Write( \"Following are nodes in top view of Binary Tree\\n\"); topView(root);}} /* This code contributed by PrinciRaj1992 */", "e": 34335, "s": 32239, "text": null }, { "code": "<script> // Javascript program to print top// view of binary tree // structure of binary treeclass Node{ constructor(key) { this.left = null; this.right = null; this.data = key; }} // Function to create a new nodefunction newNode(key){ let node = new Node(key); return node;} // Function should print the topView of// the binary treefunction topView(root){ // Base case if (root == null) { return; } // Take a temporary node let temp = null; // Queue to do BFS let q = []; // map to store node at // each vertical distance let mp = new Map(); q.push([root, 0]); // BFS while (q.length > 0) { temp = q[0][0]; let d = q[0][1]; q.shift(); // If any node is not at that // vertical distance just insert // that node in map and print it if (!mp.has(d)) { if (temp.data == 1) document.write( temp.data + 1 + \" \"); else if (temp.data == 2) document.write(temp.data - 1 + \" \"); else document.write(temp.data + \" \"); mp.set(d, temp.data); } // Continue for left node if (temp.left != null) { q.push([temp.left, d - 1]); } // Continue for right node if (temp.right != null) { q.push([temp.right, d + 1]); } }} // Driver code /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/let root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.right = newNode(4);root.left.right.right = newNode(5);root.left.right.right.right = newNode(6);document.write(\"Following are nodes in top \" + \"view of Binary Tree\" + \"</br>\");topView(root); // This code is contributed by suresh07 </script>", "e": 36232, "s": 34335, "text": null }, { "code": null, "e": 36287, "s": 36232, "text": "Following are nodes in top view of Binary Tree\n2 1 3 6" }, { "code": null, "e": 36300, "s": 36289, "text": "andrew1234" }, { "code": null, "e": 36314, "s": 36300, "text": "princiraj1992" }, { "code": null, "e": 36329, "s": 36314, "text": "SweekritiSmith" }, { "code": null, "e": 36339, "s": 36329, "text": "rutvik_56" }, { "code": null, "e": 36348, "s": 36339, "text": "suresh07" }, { "code": null, "e": 36358, "s": 36348, "text": "kk9826225" }, { "code": null, "e": 36368, "s": 36358, "text": "nnr223442" }, { "code": null, "e": 36385, "s": 36368, "text": "jaiswalrohit8319" }, { "code": null, "e": 36402, "s": 36385, "text": "tree-level-order" }, { "code": null, "e": 36412, "s": 36402, "text": "tree-view" }, { "code": null, "e": 36417, "s": 36412, "text": "Tree" }, { "code": null, "e": 36422, "s": 36417, "text": "Tree" }, { "code": null, "e": 36520, "s": 36422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36561, "s": 36520, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 36604, "s": 36561, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 36637, "s": 36604, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 36687, "s": 36637, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 36701, "s": 36687, "text": "Decision Tree" }, { "code": null, "e": 36784, "s": 36701, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 36842, "s": 36784, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 36878, "s": 36842, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 36926, "s": 36878, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
Bitwise XOR of all unordered pairs from a given array - GeeksforGeeks
26 Jul, 2021 Given an array arr[] of size N, the task is to find the bitwise XOR of all possible unordered pairs of the given array. Examples: Input: arr[] = {1, 5, 3, 7}Output: 0Explanation:All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7)Bitwise XOR of all possible pairs are = 1 ^ 5 ^ 1 ^3 ^ 1 ^ 7 ^ 5 ^ 3 ^ 5^ 7 ^ 3 ^ 7 = 0Therefore, the required output is 0. Input: arr[] = {1, 2, 3, 4}Output: 4 Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print the Bitwise XOR of each element present in these pairs of the given array. Follow the steps below to solve the problem: Initialize a variable, say totalXOR, to store Bitwise XOR of each element from these pairs. Traverse the given array and generate all possible pairs(arr[i], arr[j]) from the given array. For each pair (arr[i], arr[j]), update the value of totalXOR = (totalXOR ^ arr[i] ^ arr[j]). Finally, print the value of totalXOR. 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 to get bitwise XOR// of all possible pairs of// the given arrayint TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalXorPair(arr, N);} // Java program to implement// the above approachclass GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver code public static void main(String[] args){ int arr[] = {1, 2, 3, 4}; int N = arr.length; System.out.print(TotalXorPair(arr, N));}} // This code is contributed by divyeshrabadiya07 # Python3 program to implement# the above approach # Function to get bitwise XOR# of all possible pairs of# the given arraydef TotalXorPair(arr, N): # Stores bitwise XOR # of all possible pairs totalXOR = 0; # Generate all possible pairs # and calculate bitwise XOR # of all possible pairs for i in range(0, N): for j in range(i + 1, N): # Calculate bitwise XOR # of each pair totalXOR ^= arr[i] ^ arr[j]; return totalXOR; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4]; N = len(arr); print(TotalXorPair(arr, N)); # This code is contributed by shikhasingrajput // C# program to implement// the above approachusing System; class GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int []arr, int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver code public static void Main(String[] args){ int []arr = {1, 2, 3, 4}; int N = arr.Length; Console.Write(TotalXorPair(arr, N));}} // This code is contributed by Princi Singh <script> // Javascript program to implement// the above approach // Function to get bitwise XOR// of all possible pairs of// the given arrayfunction TotalXorPair(arr, N){ // Stores bitwise XOR // of all possible pairs let totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for(let i = 0; i < N; i++) { for(let j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver Codelet arr = [ 1, 2, 3, 4 ];let N = arr.length; document.write(TotalXorPair(arr, N)); // This code is contributed by target_2 </script> 4 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, follow the observations below: Property of Bitwise XOR: a ^ a ^ a .......( Even times ) = 0 a ^ a ^ a .......( Odd times ) = a Each element of the given array occurs exactly (N – 1) times in all possible pairs.Therefore, if N is even, then Bitwise XOR of all possible pairs are equal to bitwise XOR of all the array elements.Otherwise, bitwise XOR of all possible pairs are equal to 0. Follow the steps below to solve the problem: If N is odd then print 0. If N is even then print the value of bitwise XOR of all the elements of the given array. 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 to get bitwise XOR// of all possible pairs of// the given arrayint TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the given array. for (int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalXorPair(arr, N);} // Java program to implement// the above approachclass GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if( N % 2 != 0 ) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the array for(int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver code public static void main(String[] args){ int arr[] = {1, 2, 3, 4}; int N = arr.length; System.out.print(TotalXorPair(arr, N));}} // This code is contributed by math_lover # Python3 program to implement# the above approach # Function to get bitwise XOR# of all possible pairs of# the given arraydef TotalXorPair(arr, N): # Stores bitwise XOR # of all possible pairs totalXOR = 0 # Check if N is odd if (N % 2 != 0): return 0 # If N is even then calculate # bitwise XOR of all elements # of the given array. for i in range(N): totalXOR ^= arr[i] return totalXOR # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4 ] N = len(arr) print(TotalXorPair(arr, N)) # This code is contributed by Shivam Singh // C# program to implement// the above approachusing System; class GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraystatic int TotalXorPair(int []arr, int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the array for(int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver code public static void Main(String[] args){ int []arr = { 1, 2, 3, 4 }; int N = arr.Length; Console.Write(TotalXorPair(arr, N));}} // This code is contributed by doreamon_ <script> // Javascript program to implement// the above approach // Function to get bitwise XOR// of all possible pairs of// the given arrayfunction TotalXorPair(arr, N){ // Stores bitwise XOR // of all possible pairs let totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the given array. for (let i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let N = arr.length; document.write(TotalXorPair(arr, N)); </script> 4 Time Complexity: O(N)Auxiliary Space: O(1) SHIVAMSINGH67 divyeshrabadiya07 math_lover princi singh doreamon_ shikhasingrajput target_2 subhammahato348 akshaysingh98088 Bitwise-XOR Arrays Bit Magic Combinatorial Greedy Mathematical Arrays Greedy Mathematical Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer Cyclic Redundancy Check and Modulo-2 Division
[ { "code": null, "e": 25375, "s": 25347, "text": "\n26 Jul, 2021" }, { "code": null, "e": 25496, "s": 25375, "text": "Given an array arr[] of size N, the task is to find the bitwise XOR of all possible unordered pairs of the given array. " }, { "code": null, "e": 25506, "s": 25496, "text": "Examples:" }, { "code": null, "e": 25757, "s": 25506, "text": "Input: arr[] = {1, 5, 3, 7}Output: 0Explanation:All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7)Bitwise XOR of all possible pairs are = 1 ^ 5 ^ 1 ^3 ^ 1 ^ 7 ^ 5 ^ 3 ^ 5^ 7 ^ 3 ^ 7 = 0Therefore, the required output is 0." }, { "code": null, "e": 25794, "s": 25757, "text": "Input: arr[] = {1, 2, 3, 4}Output: 4" }, { "code": null, "e": 26031, "s": 25794, "text": "Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print the Bitwise XOR of each element present in these pairs of the given array. Follow the steps below to solve the problem:" }, { "code": null, "e": 26123, "s": 26031, "text": "Initialize a variable, say totalXOR, to store Bitwise XOR of each element from these pairs." }, { "code": null, "e": 26218, "s": 26123, "text": "Traverse the given array and generate all possible pairs(arr[i], arr[j]) from the given array." }, { "code": null, "e": 26311, "s": 26218, "text": "For each pair (arr[i], arr[j]), update the value of totalXOR = (totalXOR ^ arr[i] ^ arr[j])." }, { "code": null, "e": 26349, "s": 26311, "text": "Finally, print the value of totalXOR." }, { "code": null, "e": 26400, "s": 26349, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26404, "s": 26400, "text": "C++" }, { "code": null, "e": 26409, "s": 26404, "text": "Java" }, { "code": null, "e": 26417, "s": 26409, "text": "Python3" }, { "code": null, "e": 26420, "s": 26417, "text": "C#" }, { "code": null, "e": 26431, "s": 26420, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get bitwise XOR// of all possible pairs of// the given arrayint TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalXorPair(arr, N);}", "e": 27185, "s": 26431, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver code public static void main(String[] args){ int arr[] = {1, 2, 3, 4}; int N = arr.length; System.out.print(TotalXorPair(arr, N));}} // This code is contributed by divyeshrabadiya07", "e": 27943, "s": 27185, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to get bitwise XOR# of all possible pairs of# the given arraydef TotalXorPair(arr, N): # Stores bitwise XOR # of all possible pairs totalXOR = 0; # Generate all possible pairs # and calculate bitwise XOR # of all possible pairs for i in range(0, N): for j in range(i + 1, N): # Calculate bitwise XOR # of each pair totalXOR ^= arr[i] ^ arr[j]; return totalXOR; # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4]; N = len(arr); print(TotalXorPair(arr, N)); # This code is contributed by shikhasingrajput", "e": 28608, "s": 27943, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int []arr, int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver code public static void Main(String[] args){ int []arr = {1, 2, 3, 4}; int N = arr.Length; Console.Write(TotalXorPair(arr, N));}} // This code is contributed by Princi Singh", "e": 29378, "s": 28608, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to get bitwise XOR// of all possible pairs of// the given arrayfunction TotalXorPair(arr, N){ // Stores bitwise XOR // of all possible pairs let totalXOR = 0; // Generate all possible pairs // and calculate bitwise XOR // of all possible pairs for(let i = 0; i < N; i++) { for(let j = i + 1; j < N; j++) { // Calculate bitwise XOR // of each pair totalXOR ^= arr[i] ^ arr[j]; } } return totalXOR;} // Driver Codelet arr = [ 1, 2, 3, 4 ];let N = arr.length; document.write(TotalXorPair(arr, N)); // This code is contributed by target_2 </script>", "e": 30108, "s": 29378, "text": null }, { "code": null, "e": 30110, "s": 30108, "text": "4" }, { "code": null, "e": 30154, "s": 30110, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 30237, "s": 30154, "text": "Efficient Approach: To optimize the above approach, follow the observations below:" }, { "code": null, "e": 30333, "s": 30237, "text": "Property of Bitwise XOR: a ^ a ^ a .......( Even times ) = 0 a ^ a ^ a .......( Odd times ) = a" }, { "code": null, "e": 30592, "s": 30333, "text": "Each element of the given array occurs exactly (N – 1) times in all possible pairs.Therefore, if N is even, then Bitwise XOR of all possible pairs are equal to bitwise XOR of all the array elements.Otherwise, bitwise XOR of all possible pairs are equal to 0." }, { "code": null, "e": 30637, "s": 30592, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 30663, "s": 30637, "text": "If N is odd then print 0." }, { "code": null, "e": 30752, "s": 30663, "text": "If N is even then print the value of bitwise XOR of all the elements of the given array." }, { "code": null, "e": 30802, "s": 30752, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 30806, "s": 30802, "text": "C++" }, { "code": null, "e": 30811, "s": 30806, "text": "Java" }, { "code": null, "e": 30819, "s": 30811, "text": "Python3" }, { "code": null, "e": 30822, "s": 30819, "text": "C#" }, { "code": null, "e": 30833, "s": 30822, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get bitwise XOR// of all possible pairs of// the given arrayint TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the given array. for (int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalXorPair(arr, N);}", "e": 31493, "s": 30833, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraypublic static int TotalXorPair(int arr[], int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if( N % 2 != 0 ) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the array for(int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver code public static void main(String[] args){ int arr[] = {1, 2, 3, 4}; int N = arr.length; System.out.print(TotalXorPair(arr, N));}} // This code is contributed by math_lover", "e": 32187, "s": 31493, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to get bitwise XOR# of all possible pairs of# the given arraydef TotalXorPair(arr, N): # Stores bitwise XOR # of all possible pairs totalXOR = 0 # Check if N is odd if (N % 2 != 0): return 0 # If N is even then calculate # bitwise XOR of all elements # of the given array. for i in range(N): totalXOR ^= arr[i] return totalXOR # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4 ] N = len(arr) print(TotalXorPair(arr, N)) # This code is contributed by Shivam Singh", "e": 32784, "s": 32187, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to get bitwise XOR// of all possible pairs of// the given arraystatic int TotalXorPair(int []arr, int N){ // Stores bitwise XOR // of all possible pairs int totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the array for(int i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver code public static void Main(String[] args){ int []arr = { 1, 2, 3, 4 }; int N = arr.Length; Console.Write(TotalXorPair(arr, N));}} // This code is contributed by doreamon_", "e": 33532, "s": 32784, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to get bitwise XOR// of all possible pairs of// the given arrayfunction TotalXorPair(arr, N){ // Stores bitwise XOR // of all possible pairs let totalXOR = 0; // Check if N is odd if (N % 2 != 0) { return 0; } // If N is even then calculate // bitwise XOR of all elements // of the given array. for (let i = 0; i < N; i++) { totalXOR ^= arr[i]; } return totalXOR;} // Driver Code let arr = [ 1, 2, 3, 4 ]; let N = arr.length; document.write(TotalXorPair(arr, N)); </script>", "e": 34144, "s": 33532, "text": null }, { "code": null, "e": 34146, "s": 34144, "text": "4" }, { "code": null, "e": 34189, "s": 34146, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 34203, "s": 34189, "text": "SHIVAMSINGH67" }, { "code": null, "e": 34221, "s": 34203, "text": "divyeshrabadiya07" }, { "code": null, "e": 34232, "s": 34221, "text": "math_lover" }, { "code": null, "e": 34245, "s": 34232, "text": "princi singh" }, { "code": null, "e": 34255, "s": 34245, "text": "doreamon_" }, { "code": null, "e": 34272, "s": 34255, "text": "shikhasingrajput" }, { "code": null, "e": 34281, "s": 34272, "text": "target_2" }, { "code": null, "e": 34297, "s": 34281, "text": "subhammahato348" }, { "code": null, "e": 34314, "s": 34297, "text": "akshaysingh98088" }, { "code": null, "e": 34326, "s": 34314, "text": "Bitwise-XOR" }, { "code": null, "e": 34333, "s": 34326, "text": "Arrays" }, { "code": null, "e": 34343, "s": 34333, "text": "Bit Magic" }, { "code": null, "e": 34357, "s": 34343, "text": "Combinatorial" }, { "code": null, "e": 34364, "s": 34357, "text": "Greedy" }, { "code": null, "e": 34377, "s": 34364, "text": "Mathematical" }, { "code": null, "e": 34384, "s": 34377, "text": "Arrays" }, { "code": null, "e": 34391, "s": 34384, "text": "Greedy" }, { "code": null, "e": 34404, "s": 34391, "text": "Mathematical" }, { "code": null, "e": 34414, "s": 34404, "text": "Bit Magic" }, { "code": null, "e": 34428, "s": 34414, "text": "Combinatorial" }, { "code": null, "e": 34526, "s": 34428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34535, "s": 34526, "text": "Comments" }, { "code": null, "e": 34548, "s": 34535, "text": "Old Comments" }, { "code": null, "e": 34592, "s": 34548, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34615, "s": 34592, "text": "Introduction to Arrays" }, { "code": null, "e": 34647, "s": 34615, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34661, "s": 34647, "text": "Linear Search" }, { "code": null, "e": 34746, "s": 34661, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34773, "s": 34746, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 34819, "s": 34773, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 34887, "s": 34819, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 34916, "s": 34887, "text": "Count set bits in an integer" } ]
Run Python script from Node.js using child process spawn() method?
NodeJs and Python are two main preferred languages among developers and web designers. But there are couple of areas where NodeJs fall short of python are numerical and scientic computation (AI, Machine learning, deep learning etc.). Whereas python provides lots of libraries to work with scientific computing lot easier. Luckly, we can utilise the python libraries within our nodejs application by running python in the background and return back the result. For this we are going to use the child_process standard library of NodeJs to spawn a pyton process in the background, do computation and return back the result to our node program. We are going to write a simple python script which outputs messages to standard output along the way. #Import library import sys, getopt, time def main(argv): argument = '' usage = 'usage: myscript.py -f <sometext>' # parse incoming arguments try: opts, args = getopt.getopt(argv,"hf:",["foo="]) except getopt.GetoptError: print(usage) sys.exit(2) for opt, arg in opts: if opt == '-h': print(usage) sys.exit() elif opt in ("-f", "--foo"): argument = arg # print output print("Start : %s" % time.ctime()) time.sleep( 2 ) print('Foo is') time.sleep( 2 ) print(argument) print("End : %s" % time.ctime()) if __name__ == "__main__": main(sys.argv[1:]) >python myscript.py -f "Hello, Python" Start : Wed Feb 20 07:52:45 2019 Foo is Hello, Python End : Wed Feb 20 07:52:49 2019 Will generate same output as above, if we try to run with argument: >python myscript.py --foo "Hello, Python" >python myscript.py –h usage: myscript.py -f <Hello, Python> Our nodejs script will interact with python script by first calling python script then pass script output to the client and render output in the client. So let’s create a nodejs script, where we’ll try to create a child process using spawn() method. const path = require('path') const {spawn} = require('child_process') /** * Run python myscript, pass in `-u` to not buffer console output * @return {ChildProcess} */ function runScript(){ return spawn('python', [ "-u", path.join(__dirname, 'myscript.py'), "--foo", "some value for foo", ]); } const subprocess = runScript() // print output of script subprocess.stdout.on('data', (data) => { console.log(`data:${data}`); }); subprocess.stderr.on('data', (data) => { console.log(`error:${data}`); }); subprocess.stderr.on('close', () => { console.log("Closed"); }); The above script will give output through .on(‘data’, callback). To prevent python from buffering output use the –f flag otherwise data event we’ll will not get print() statements from program until the end of execution. >node server.js data:Start : Wed Feb 20 10:56:11 2019 data:Foo is data:some value for foo data:End : Wed Feb 20 10:56:15 2019 Closed
[ { "code": null, "e": 1384, "s": 1062, "text": "NodeJs and Python are two main preferred languages among developers and web designers. But there are couple of areas where NodeJs fall short of python are numerical and scientic computation (AI, Machine learning, deep learning etc.). Whereas python provides lots of libraries to work with scientific computing lot easier." }, { "code": null, "e": 1522, "s": 1384, "text": "Luckly, we can utilise the python libraries within our nodejs application by running python in the background and return back the result." }, { "code": null, "e": 1703, "s": 1522, "text": "For this we are going to use the child_process standard library of NodeJs to spawn a pyton process in the background, do computation and return back the result to our node program." }, { "code": null, "e": 1805, "s": 1703, "text": "We are going to write a simple python script which outputs messages to standard output along the way." }, { "code": null, "e": 2446, "s": 1805, "text": "#Import library\nimport sys, getopt, time\ndef main(argv):\n argument = ''\n usage = 'usage: myscript.py -f <sometext>'\n # parse incoming arguments\n try:\n opts, args = getopt.getopt(argv,\"hf:\",[\"foo=\"])\n except getopt.GetoptError:\n print(usage)\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print(usage)\n sys.exit()\n elif opt in (\"-f\", \"--foo\"):\n argument = arg\n # print output\n print(\"Start : %s\" % time.ctime())\n time.sleep( 2 )\n print('Foo is')\n time.sleep( 2 )\n print(argument)\n print(\"End : %s\" % time.ctime())\nif __name__ == \"__main__\":\nmain(sys.argv[1:])" }, { "code": null, "e": 2570, "s": 2446, "text": ">python myscript.py -f \"Hello, Python\"\nStart : Wed Feb 20 07:52:45 2019\nFoo is\nHello, Python\nEnd : Wed Feb 20 07:52:49 2019" }, { "code": null, "e": 2638, "s": 2570, "text": "Will generate same output as above, if we try to run with argument:" }, { "code": null, "e": 2703, "s": 2638, "text": ">python myscript.py --foo \"Hello, Python\"\n>python myscript.py –h" }, { "code": null, "e": 2741, "s": 2703, "text": "usage: myscript.py -f <Hello, Python>" }, { "code": null, "e": 2894, "s": 2741, "text": "Our nodejs script will interact with python script by first calling python script then pass script output to the client and render output in the client." }, { "code": null, "e": 2991, "s": 2894, "text": "So let’s create a nodejs script, where we’ll try to create a child process using spawn() method." }, { "code": null, "e": 3594, "s": 2991, "text": "const path = require('path')\nconst {spawn} = require('child_process')\n/**\n * Run python myscript, pass in `-u` to not buffer console output\n * @return {ChildProcess}\n*/\nfunction runScript(){\n return spawn('python', [\n \"-u\",\n path.join(__dirname, 'myscript.py'),\n \"--foo\", \"some value for foo\",\n ]);\n}\nconst subprocess = runScript()\n// print output of script\nsubprocess.stdout.on('data', (data) => {\n console.log(`data:${data}`);\n});\nsubprocess.stderr.on('data', (data) => {\n console.log(`error:${data}`);\n});\nsubprocess.stderr.on('close', () => {\n console.log(\"Closed\");\n});" }, { "code": null, "e": 3815, "s": 3594, "text": "The above script will give output through .on(‘data’, callback). To prevent python from buffering output use the –f flag otherwise data event we’ll will not get print() statements from program until the end of execution." }, { "code": null, "e": 3948, "s": 3815, "text": ">node server.js\ndata:Start : Wed Feb 20 10:56:11 2019\ndata:Foo is\ndata:some value for foo\ndata:End : Wed Feb 20 10:56:15 2019\nClosed" } ]
Error Handling in Python using Decorators - GeeksforGeeks
21 Sep, 2021 Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: Python3 # defining decorator functiondef decorator_example(func): print("Decorator called") # defining inner decorator function def inner_function(): print("inner function") func() return inner_function # defining outer decorator function@decorator_exampledef out_function(): print("outer function")out_function() Output: Decorator called inner function outer function The following example shows how a general error handling code without use of any decorator looks like: Python3 def mean(a,b): try: print((a+b)/2) except TypeError: print("wrong data types. enter numeric") def square(sq): try: print(sq*sq) except TypeError: print("wrong data types. enter numeric") def divide(l,b): try: print(b/l) except TypeError: print("wrong data types. enter numeric")mean(4,5)square(21)divide(8,4)divide("two","one") Output : 4.5 441 0.5 wrong data types. enter numeric Even though there is nothing logically wrong with the above code but it lacks clarity. To make the code more clean and efficient decorators are used for error handling. The following example depicts how the above code can be more presentable and understandable by use of decorators: Python3 def Error_Handler(func): def Inner_Function(*args, **kwargs): try: func(*args, **kwargs) except TypeError: print(f"{func.__name__} wrong data types. enter numeric") return Inner_Function@Error_Handlerdef Mean(a,b): print((a+b)/2) @Error_Handlerdef Square(sq): print(sq*sq) @Error_Handlerdef Divide(l,b): print(b/l) Mean(4,5)Square(14)Divide(8,4)Square("three")Divide("two","one")Mean("six","five") Output : 4.5 196 0.5 Square wrong data types. enter numeric Divide wrong data types. enter numeric Mean wrong data types. enter numeric simmytarika5 Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n21 Sep, 2021" }, { "code": null, "e": 25757, "s": 25561, "text": "Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. " }, { "code": null, "e": 25766, "s": 25757, "text": "Example:" }, { "code": null, "e": 25774, "s": 25766, "text": "Python3" }, { "code": "# defining decorator functiondef decorator_example(func): print(\"Decorator called\") # defining inner decorator function def inner_function(): print(\"inner function\") func() return inner_function # defining outer decorator function@decorator_exampledef out_function(): print(\"outer function\")out_function()", "e": 26119, "s": 25774, "text": null }, { "code": null, "e": 26127, "s": 26119, "text": "Output:" }, { "code": null, "e": 26174, "s": 26127, "text": "Decorator called\ninner function\nouter function" }, { "code": null, "e": 26277, "s": 26174, "text": "The following example shows how a general error handling code without use of any decorator looks like:" }, { "code": null, "e": 26285, "s": 26277, "text": "Python3" }, { "code": "def mean(a,b): try: print((a+b)/2) except TypeError: print(\"wrong data types. enter numeric\") def square(sq): try: print(sq*sq) except TypeError: print(\"wrong data types. enter numeric\") def divide(l,b): try: print(b/l) except TypeError: print(\"wrong data types. enter numeric\")mean(4,5)square(21)divide(8,4)divide(\"two\",\"one\")", "e": 26683, "s": 26285, "text": null }, { "code": null, "e": 26692, "s": 26683, "text": "Output :" }, { "code": null, "e": 26736, "s": 26692, "text": "4.5\n441\n0.5\nwrong data types. enter numeric" }, { "code": null, "e": 27019, "s": 26736, "text": "Even though there is nothing logically wrong with the above code but it lacks clarity. To make the code more clean and efficient decorators are used for error handling. The following example depicts how the above code can be more presentable and understandable by use of decorators:" }, { "code": null, "e": 27027, "s": 27019, "text": "Python3" }, { "code": "def Error_Handler(func): def Inner_Function(*args, **kwargs): try: func(*args, **kwargs) except TypeError: print(f\"{func.__name__} wrong data types. enter numeric\") return Inner_Function@Error_Handlerdef Mean(a,b): print((a+b)/2) @Error_Handlerdef Square(sq): print(sq*sq) @Error_Handlerdef Divide(l,b): print(b/l) Mean(4,5)Square(14)Divide(8,4)Square(\"three\")Divide(\"two\",\"one\")Mean(\"six\",\"five\")", "e": 27496, "s": 27027, "text": null }, { "code": null, "e": 27505, "s": 27496, "text": "Output :" }, { "code": null, "e": 27510, "s": 27505, "text": "4.5 " }, { "code": null, "e": 27515, "s": 27510, "text": "196 " }, { "code": null, "e": 27520, "s": 27515, "text": "0.5 " }, { "code": null, "e": 27560, "s": 27520, "text": "Square wrong data types. enter numeric " }, { "code": null, "e": 27600, "s": 27560, "text": "Divide wrong data types. enter numeric " }, { "code": null, "e": 27639, "s": 27600, "text": "Mean wrong data types. enter numeric " }, { "code": null, "e": 27652, "s": 27639, "text": "simmytarika5" }, { "code": null, "e": 27670, "s": 27652, "text": "Python Decorators" }, { "code": null, "e": 27677, "s": 27670, "text": "Python" }, { "code": null, "e": 27775, "s": 27677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27807, "s": 27775, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27849, "s": 27807, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27891, "s": 27849, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27918, "s": 27891, "text": "Python Classes and Objects" }, { "code": null, "e": 27974, "s": 27918, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27996, "s": 27974, "text": "Defaultdict in Python" }, { "code": null, "e": 28035, "s": 27996, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28066, "s": 28035, "text": "Python | os.path.join() method" }, { "code": null, "e": 28095, "s": 28066, "text": "Create a directory in Python" } ]
Analysis of Algorithms - GeeksforGeeks
29 Jul, 2021 Let the three pegs be A, B and C. The goal is to move n pegs from A to C. To move n discs from peg A to peg C: move n-1 discs from A to B. This leaves disc n alone on peg A move disc n from A to C move n?1 discs from B to C so they sit on disc n f1(n) = 2^n f2(n) = n^(3/2) f3(n) = nLogn f4(n) = n^(Logn) f1(n) = 2^n f2(n) = n^(3/2) f3(n) = nLogn f4(n) = n^(Logn) n = 32, f1 = 2^32, f4 = 32^5 = 2^25 n = 64, f1 = 2^64, f4 = 64^6 = 2^36 ............... ............... Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is "network ID" and "host ID" in IP Addresses? What is Transmission Control Protocol (TCP)? How to Calculate Number of Host in a Subnet? Bash Scripting - How to check If File Exists Python Raise Keyword Python OpenCV - Canny() Function
[ { "code": null, "e": 35737, "s": 35709, "text": "\n29 Jul, 2021" }, { "code": null, "e": 35995, "s": 35737, "text": "Let the three pegs be A, B and C. The goal is to move n pegs from A to C.\nTo move n discs from peg A to peg C:\n move n-1 discs from A to B. This leaves disc n alone on peg A\n move disc n from A to C\n move n?1 discs from B to C so they sit on disc n" }, { "code": null, "e": 36062, "s": 35995, "text": " f1(n) = 2^n\n f2(n) = n^(3/2)\n f3(n) = nLogn\n f4(n) = n^(Logn)" }, { "code": null, "e": 36129, "s": 36062, "text": " f1(n) = 2^n\n f2(n) = n^(3/2)\n f3(n) = nLogn\n f4(n) = n^(Logn)" }, { "code": null, "e": 36234, "s": 36129, "text": "n = 32, f1 = 2^32, f4 = 32^5 = 2^25\nn = 64, f1 = 2^64, f4 = 64^6 = 2^36\n...............\n............... " }, { "code": null, "e": 36332, "s": 36234, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 36391, "s": 36332, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36423, "s": 36391, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 36476, "s": 36423, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 36531, "s": 36476, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 36583, "s": 36531, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 36628, "s": 36583, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 36673, "s": 36628, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 36718, "s": 36673, "text": "Bash Scripting - How to check If File Exists" }, { "code": null, "e": 36739, "s": 36718, "text": "Python Raise Keyword" } ]
is_arithmetic Template in C++ - GeeksforGeeks
19 Nov, 2018 The std::is_arithmetic templateof C++ STL is used to check whether the given type is arithmetic or not. An Arithmetic type means an integral type or a floating-point type. It returns a boolean value showing the same. Syntax: template <class T> struct is_arithmetic; Parameters: This template accepts a single parameter T (Trait class) to check whether T is an arithmetic type or not. Return Value: This template returns a boolean value as shown below: True: if the type is a arithmetic. False: if the type is a non-arithmetic. Below programs illustrate the std::is_arithmetic template in C++ STL: Program 1: // C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programclass GFG {}; int main(){ cout << boolalpha; cout << "is_arithmetic:" << '\n'; cout << "GFG: " << is_arithmetic<GFG>::value << '\n'; cout << "bool: " << is_arithmetic<bool>::value << '\n'; cout << "long: " << is_arithmetic<long>::value << '\n'; cout << "short: " << is_arithmetic<short>::value << '\n'; return 0;} is_arithmetic: GFG: false bool: true long: true short: true Program 2: // C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programclass GFG {}; int main(){ cout << boolalpha; cout << "is_arithmetic:" << '\n'; cout << "GFG: " << is_arithmetic<GFG>::value << '\n'; cout << "int: " << is_arithmetic<int>::value << '\n'; cout << "int const: " << is_arithmetic<int const>::value << '\n'; cout << "int &: " << is_arithmetic<int&>::value << '\n'; cout << "int *: " << is_arithmetic<int*>::value << '\n'; cout << "long int: " << is_arithmetic<long int>::value << '\n'; return 0;} is_arithmetic: GFG: false int: true int const: true int &: false int *: false long int: true Program 3: // C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programint main(){ cout << boolalpha; cout << "is_arithmetic:" << '\n'; cout << "float: " << is_arithmetic<float>::value << '\n'; cout << "float const: " << is_arithmetic<float const>::value << '\n'; cout << "float &: " << is_arithmetic<float&>::value << '\n'; cout << "float *: " << is_arithmetic<float*>::value << '\n'; cout << "double: " << is_arithmetic<double>::value << '\n'; cout << "double const: " << is_arithmetic<double const>::value << '\n'; cout << "double &: " << is_arithmetic<double&>::value << '\n'; cout << "double *: " << is_arithmetic<double*>::value << '\n'; return 0;} is_arithmetic: float: true float const: true float &: false float *: false double: true double const: true double &: false double *: false Program 4: // C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programint main(){ cout << boolalpha; cout << "is_arithmetic:" << '\n'; cout << "char: " << is_arithmetic<char>::value << '\n'; cout << "char const: " << is_arithmetic<char const>::value << '\n'; cout << "char &: " << is_arithmetic<char&>::value << '\n'; cout << "char *: " << is_arithmetic<char*>::value << '\n'; return 0;} is_arithmetic: char: true char const: true char &: false char *: false rajasethupathi cpp-template C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25343, "s": 25315, "text": "\n19 Nov, 2018" }, { "code": null, "e": 25560, "s": 25343, "text": "The std::is_arithmetic templateof C++ STL is used to check whether the given type is arithmetic or not. An Arithmetic type means an integral type or a floating-point type. It returns a boolean value showing the same." }, { "code": null, "e": 25568, "s": 25560, "text": "Syntax:" }, { "code": null, "e": 25609, "s": 25568, "text": "template <class T> struct is_arithmetic;" }, { "code": null, "e": 25727, "s": 25609, "text": "Parameters: This template accepts a single parameter T (Trait class) to check whether T is an arithmetic type or not." }, { "code": null, "e": 25795, "s": 25727, "text": "Return Value: This template returns a boolean value as shown below:" }, { "code": null, "e": 25830, "s": 25795, "text": "True: if the type is a arithmetic." }, { "code": null, "e": 25870, "s": 25830, "text": "False: if the type is a non-arithmetic." }, { "code": null, "e": 25940, "s": 25870, "text": "Below programs illustrate the std::is_arithmetic template in C++ STL:" }, { "code": null, "e": 25951, "s": 25940, "text": "Program 1:" }, { "code": "// C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programclass GFG {}; int main(){ cout << boolalpha; cout << \"is_arithmetic:\" << '\\n'; cout << \"GFG: \" << is_arithmetic<GFG>::value << '\\n'; cout << \"bool: \" << is_arithmetic<bool>::value << '\\n'; cout << \"long: \" << is_arithmetic<long>::value << '\\n'; cout << \"short: \" << is_arithmetic<short>::value << '\\n'; return 0;}", "e": 26452, "s": 25951, "text": null }, { "code": null, "e": 26513, "s": 26452, "text": "is_arithmetic:\nGFG: false\nbool: true\nlong: true\nshort: true\n" }, { "code": null, "e": 26524, "s": 26513, "text": "Program 2:" }, { "code": "// C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programclass GFG {}; int main(){ cout << boolalpha; cout << \"is_arithmetic:\" << '\\n'; cout << \"GFG: \" << is_arithmetic<GFG>::value << '\\n'; cout << \"int: \" << is_arithmetic<int>::value << '\\n'; cout << \"int const: \" << is_arithmetic<int const>::value << '\\n'; cout << \"int &: \" << is_arithmetic<int&>::value << '\\n'; cout << \"int *: \" << is_arithmetic<int*>::value << '\\n'; cout << \"long int: \" << is_arithmetic<long int>::value << '\\n'; return 0;}", "e": 27177, "s": 26524, "text": null }, { "code": null, "e": 27271, "s": 27177, "text": "is_arithmetic:\nGFG: false\nint: true\nint const: true\nint &: false\nint *: false\nlong int: true\n" }, { "code": null, "e": 27282, "s": 27271, "text": "Program 3:" }, { "code": "// C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programint main(){ cout << boolalpha; cout << \"is_arithmetic:\" << '\\n'; cout << \"float: \" << is_arithmetic<float>::value << '\\n'; cout << \"float const: \" << is_arithmetic<float const>::value << '\\n'; cout << \"float &: \" << is_arithmetic<float&>::value << '\\n'; cout << \"float *: \" << is_arithmetic<float*>::value << '\\n'; cout << \"double: \" << is_arithmetic<double>::value << '\\n'; cout << \"double const: \" << is_arithmetic<double const>::value << '\\n'; cout << \"double &: \" << is_arithmetic<double&>::value << '\\n'; cout << \"double *: \" << is_arithmetic<double*>::value << '\\n'; return 0;}", "e": 28098, "s": 27282, "text": null }, { "code": null, "e": 28238, "s": 28098, "text": "is_arithmetic:\nfloat: true\nfloat const: true\nfloat &: false\nfloat *: false\ndouble: true\ndouble const: true\ndouble &: false\ndouble *: false\n" }, { "code": null, "e": 28249, "s": 28238, "text": "Program 4:" }, { "code": "// C++ program to illustrate// is_arithmetic template #include <iostream>#include <type_traits>using namespace std; // main programint main(){ cout << boolalpha; cout << \"is_arithmetic:\" << '\\n'; cout << \"char: \" << is_arithmetic<char>::value << '\\n'; cout << \"char const: \" << is_arithmetic<char const>::value << '\\n'; cout << \"char &: \" << is_arithmetic<char&>::value << '\\n'; cout << \"char *: \" << is_arithmetic<char*>::value << '\\n'; return 0;}", "e": 28755, "s": 28249, "text": null }, { "code": null, "e": 28827, "s": 28755, "text": "is_arithmetic:\nchar: true\nchar const: true\nchar &: false\nchar *: false\n" }, { "code": null, "e": 28842, "s": 28827, "text": "rajasethupathi" }, { "code": null, "e": 28855, "s": 28842, "text": "cpp-template" }, { "code": null, "e": 28859, "s": 28855, "text": "C++" }, { "code": null, "e": 28863, "s": 28859, "text": "CPP" }, { "code": null, "e": 28961, "s": 28863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28989, "s": 28961, "text": "Operator Overloading in C++" }, { "code": null, "e": 29009, "s": 28989, "text": "Polymorphism in C++" }, { "code": null, "e": 29033, "s": 29009, "text": "Sorting a vector in C++" }, { "code": null, "e": 29066, "s": 29033, "text": "Friend class and function in C++" }, { "code": null, "e": 29110, "s": 29066, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29135, "s": 29110, "text": "std::string class in C++" }, { "code": null, "e": 29180, "s": 29135, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 29204, "s": 29180, "text": "Inline Functions in C++" }, { "code": null, "e": 29257, "s": 29204, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Maximum length substring with highest frequency in a string - GeeksforGeeks
25 Oct, 2021 Given a string. The task is to find the maximum occurred substring with a maximum length. These occurrences can overlap.Examples: Input: str = "abab" Output: ab "a", "b", "ab" are occur 2 times. But, "ab" has maximum length Input: str = "abcd" Output: a Approach: The idea is to store the frequency of each substring using a map and print the one with maximum frequency and maximum length. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find maximum// occurred substring of a string#include <bits/stdc++.h>using namespace std; // function to return maximum// occurred substring of a stringstring MaxFreq(string str){ // size of the string int n = str.size(); unordered_map<string, int> m; for (int i = 0; i < n; i++) { string s = ""; for (int j = i; j < n; j++) { s += str[j]; m[s]++; } } // to store maximum frequency int maxi = 0; // to store string which has maximum frequency string s; for (auto i = m.begin(); i != m.end(); i++) { if (i->second > maxi) { maxi = i->second; s = i->first; } else if (i->second == maxi) { string ss = i->first; if (ss.size() > s.size()) s = ss; } } // return substring which has maximum frequency return s;} // Driver programint main(){ string str = "ababecdecd"; // function call cout << MaxFreq(str); return 0;} // Java program to find maximum// occurred subString of a Stringimport java.util.*;class GFG{ // Function to return maximum// occurred subString of a Stringstatic String MaxFreq(String str){ // Size of the String int n = str.length(); Map<String, Integer> mp = new HashMap<String, Integer>(); for (int i = 0; i < n; i++) { String s = ""; for (int j = i; j < n; j++) { s += str.charAt(j); if(mp.containsKey(s)) { mp.put(s, mp.get(s) + 1); } else { mp.put(s, 1); } } } // To store maximum frequency int maxi = 0; // To store String which // has maximum frequency String s = ""; for (Map.Entry<String, Integer> i : mp.entrySet()) { if (i.getValue() > maxi) { maxi = i.getValue(); s = i.getKey(); } else if (i.getValue() == maxi) { String ss = i.getKey(); if (ss.length() > s.length()) s = ss; } } // Return subString which // has maximum frequency return s;} // Driver codepublic static void main(String[] args){ String str = "ababecdecd"; // Function call System.out.print(MaxFreq(str));}} // This code is contributed by shikhasingrajput # Python3 program to find maximum# occurred of a string # function to return maximum occurred# substring of a stringdef MaxFreq(s): # size of string n = len(s) m = dict() for i in range(n): string = '' for j in range(i, n): string += s[j] if string in m.keys(): m[string] += 1 else: m[string] = 1 # to store maximum frequency maxi = 0 # To store string which has # maximum frequency maxi_str = '' for i in m: if m[i] > maxi: maxi = m[i] maxi_str = i elif m[i] == maxi: ss = i if len(ss) > len(maxi_str): maxi_str = ss # return substring which has maximum freq return maxi_str # Driver codestring = "ababecdecd" print(MaxFreq(string)) # This code is contributed by Mohit kumar 29 // C# program to find maximum// occurred substring of a stringusing System;using System.Collections.Generic; class GFG{ // Function to return maximum// occurred substring of a stringstatic string MaxFreq(string str){ // Size of the string int n = str.Length; Dictionary<string, int> m = new Dictionary<string, int>(); for(int i = 0; i < n; i++) { string sp = ""; for(int j = i; j < n; j++) { sp += str[j]; if(m.ContainsKey(sp)) { m[sp]++; } else { m[sp] = 1; } } } // To store maximum frequency int maxi = 0; // To store string which has maximum frequency string s = ""; foreach(KeyValuePair<string, int> i in m) { if (i.Value > maxi) { maxi = i.Value; s = i.Key; } else if (i.Value == maxi) { string ss = i.Key; if (ss.Length > s.Length) s = ss; } } // Return substring which has // maximum frequency return s;} // Driver Codepublic static void Main(string[] args){ string str = "ababecdecd"; // Function call Console.Write(MaxFreq(str));}} // This code is contributed by rutvik_56 <script> // JavaScript program to find maximum// occurred subString of a String // Function to return maximum// occurred subString of a Stringfunction MaxFreq(str){ // Size of the String let n = str.length; let mp = new Map(); for (let i = 0; i < n; i++) { let s = ""; for (let j = i; j < n; j++) { s += str[j]; if(mp.has(s)) { mp.set(s, mp.get(s) + 1); } else { mp.set(s, 1); } } } // To store maximum frequency let maxi = 0; // To store String which // has maximum frequency let s = ""; for (let [key, value] of mp.entries()) { if (value > maxi) { maxi = value; s = key; } else if (value == maxi) { let ss = key; if (ss.length > s.length) s = ss; } } // Return subString which // has maximum frequency return s;} // Driver code let str = "ababecdecd"; // Function calldocument.write(MaxFreq(str)); // This code is contributed by patel2127 </script> ecd mohit kumar 29 rutvik_56 shikhasingrajput patel2127 anikakapoor simmytarika5 saurabh1990aror cpp-unordered_map Competitive Programming Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) Bits manipulation (Important tactics) 7 Best Coding Challenge Websites in 2020 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26509, "s": 26481, "text": "\n25 Oct, 2021" }, { "code": null, "e": 26640, "s": 26509, "text": "Given a string. The task is to find the maximum occurred substring with a maximum length. These occurrences can overlap.Examples: " }, { "code": null, "e": 26765, "s": 26640, "text": "Input: str = \"abab\"\nOutput: ab\n\"a\", \"b\", \"ab\" are occur 2 times. But, \"ab\" has maximum length\n\nInput: str = \"abcd\"\nOutput: a" }, { "code": null, "e": 26954, "s": 26765, "text": "Approach: The idea is to store the frequency of each substring using a map and print the one with maximum frequency and maximum length. Below is the implementation of the above approach: " }, { "code": null, "e": 26958, "s": 26954, "text": "C++" }, { "code": null, "e": 26963, "s": 26958, "text": "Java" }, { "code": null, "e": 26971, "s": 26963, "text": "Python3" }, { "code": null, "e": 26974, "s": 26971, "text": "C#" }, { "code": null, "e": 26985, "s": 26974, "text": "Javascript" }, { "code": "// C++ program to find maximum// occurred substring of a string#include <bits/stdc++.h>using namespace std; // function to return maximum// occurred substring of a stringstring MaxFreq(string str){ // size of the string int n = str.size(); unordered_map<string, int> m; for (int i = 0; i < n; i++) { string s = \"\"; for (int j = i; j < n; j++) { s += str[j]; m[s]++; } } // to store maximum frequency int maxi = 0; // to store string which has maximum frequency string s; for (auto i = m.begin(); i != m.end(); i++) { if (i->second > maxi) { maxi = i->second; s = i->first; } else if (i->second == maxi) { string ss = i->first; if (ss.size() > s.size()) s = ss; } } // return substring which has maximum frequency return s;} // Driver programint main(){ string str = \"ababecdecd\"; // function call cout << MaxFreq(str); return 0;}", "e": 28003, "s": 26985, "text": null }, { "code": "// Java program to find maximum// occurred subString of a Stringimport java.util.*;class GFG{ // Function to return maximum// occurred subString of a Stringstatic String MaxFreq(String str){ // Size of the String int n = str.length(); Map<String, Integer> mp = new HashMap<String, Integer>(); for (int i = 0; i < n; i++) { String s = \"\"; for (int j = i; j < n; j++) { s += str.charAt(j); if(mp.containsKey(s)) { mp.put(s, mp.get(s) + 1); } else { mp.put(s, 1); } } } // To store maximum frequency int maxi = 0; // To store String which // has maximum frequency String s = \"\"; for (Map.Entry<String, Integer> i : mp.entrySet()) { if (i.getValue() > maxi) { maxi = i.getValue(); s = i.getKey(); } else if (i.getValue() == maxi) { String ss = i.getKey(); if (ss.length() > s.length()) s = ss; } } // Return subString which // has maximum frequency return s;} // Driver codepublic static void main(String[] args){ String str = \"ababecdecd\"; // Function call System.out.print(MaxFreq(str));}} // This code is contributed by shikhasingrajput", "e": 29223, "s": 28003, "text": null }, { "code": "# Python3 program to find maximum# occurred of a string # function to return maximum occurred# substring of a stringdef MaxFreq(s): # size of string n = len(s) m = dict() for i in range(n): string = '' for j in range(i, n): string += s[j] if string in m.keys(): m[string] += 1 else: m[string] = 1 # to store maximum frequency maxi = 0 # To store string which has # maximum frequency maxi_str = '' for i in m: if m[i] > maxi: maxi = m[i] maxi_str = i elif m[i] == maxi: ss = i if len(ss) > len(maxi_str): maxi_str = ss # return substring which has maximum freq return maxi_str # Driver codestring = \"ababecdecd\" print(MaxFreq(string)) # This code is contributed by Mohit kumar 29 ", "e": 30163, "s": 29223, "text": null }, { "code": "// C# program to find maximum// occurred substring of a stringusing System;using System.Collections.Generic; class GFG{ // Function to return maximum// occurred substring of a stringstatic string MaxFreq(string str){ // Size of the string int n = str.Length; Dictionary<string, int> m = new Dictionary<string, int>(); for(int i = 0; i < n; i++) { string sp = \"\"; for(int j = i; j < n; j++) { sp += str[j]; if(m.ContainsKey(sp)) { m[sp]++; } else { m[sp] = 1; } } } // To store maximum frequency int maxi = 0; // To store string which has maximum frequency string s = \"\"; foreach(KeyValuePair<string, int> i in m) { if (i.Value > maxi) { maxi = i.Value; s = i.Key; } else if (i.Value == maxi) { string ss = i.Key; if (ss.Length > s.Length) s = ss; } } // Return substring which has // maximum frequency return s;} // Driver Codepublic static void Main(string[] args){ string str = \"ababecdecd\"; // Function call Console.Write(MaxFreq(str));}} // This code is contributed by rutvik_56", "e": 31535, "s": 30163, "text": null }, { "code": "<script> // JavaScript program to find maximum// occurred subString of a String // Function to return maximum// occurred subString of a Stringfunction MaxFreq(str){ // Size of the String let n = str.length; let mp = new Map(); for (let i = 0; i < n; i++) { let s = \"\"; for (let j = i; j < n; j++) { s += str[j]; if(mp.has(s)) { mp.set(s, mp.get(s) + 1); } else { mp.set(s, 1); } } } // To store maximum frequency let maxi = 0; // To store String which // has maximum frequency let s = \"\"; for (let [key, value] of mp.entries()) { if (value > maxi) { maxi = value; s = key; } else if (value == maxi) { let ss = key; if (ss.length > s.length) s = ss; } } // Return subString which // has maximum frequency return s;} // Driver code let str = \"ababecdecd\"; // Function calldocument.write(MaxFreq(str)); // This code is contributed by patel2127 </script>", "e": 32524, "s": 31535, "text": null }, { "code": null, "e": 32528, "s": 32524, "text": "ecd" }, { "code": null, "e": 32545, "s": 32530, "text": "mohit kumar 29" }, { "code": null, "e": 32555, "s": 32545, "text": "rutvik_56" }, { "code": null, "e": 32572, "s": 32555, "text": "shikhasingrajput" }, { "code": null, "e": 32582, "s": 32572, "text": "patel2127" }, { "code": null, "e": 32594, "s": 32582, "text": "anikakapoor" }, { "code": null, "e": 32607, "s": 32594, "text": "simmytarika5" }, { "code": null, "e": 32623, "s": 32607, "text": "saurabh1990aror" }, { "code": null, "e": 32641, "s": 32623, "text": "cpp-unordered_map" }, { "code": null, "e": 32665, "s": 32641, "text": "Competitive Programming" }, { "code": null, "e": 32670, "s": 32665, "text": "Hash" }, { "code": null, "e": 32678, "s": 32670, "text": "Strings" }, { "code": null, "e": 32683, "s": 32678, "text": "Hash" }, { "code": null, "e": 32691, "s": 32683, "text": "Strings" }, { "code": null, "e": 32789, "s": 32691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32867, "s": 32789, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 32896, "s": 32867, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 32923, "s": 32896, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 32961, "s": 32923, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 33002, "s": 32961, "text": "7 Best Coding Challenge Websites in 2020" }, { "code": null, "e": 33087, "s": 33002, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33123, "s": 33087, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33150, "s": 33123, "text": "Count pairs with given sum" }, { "code": null, "e": 33181, "s": 33150, "text": "Hashing | Set 1 (Introduction)" } ]
Plotting Data on Google Map using Python's pygmaps package - GeeksforGeeks
15 Oct, 2020 pygmaps is a matplotlib-like interface to generate the HTML and javascript to render all the data users would like on top of Google Maps. Command to install pygmaps : pip install pygmaps (on windows) sudo pip3 install pygmaps (on linix / unix) Code #1 : To create a Base Map. # import required packageimport pygmaps # maps method return map object# 1st argument is center latitude# 2nd argument is center longitude# 3ed argument zoom levelmymap1 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # create the HTML file which includes# google map. Pass the absolute path# as an argument.mymap1.draw('pygmap1.html') Output: Code #2 : To draw grids on map # importing pygmapsimport pygmaps mymap2 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # draw grids on the map# 1st argument is the starting point of latitude# 2nd argument is the ending point of latitude# 3rd argument is grid size in latitude# 4th argument is the starting point of longitude# 5th argument is the ending point of longitude# 6th argument is grid size in longitudemymap2.setgrids(30.31, 30.32, 0.001, 78.04, 78.03, 0.001) mymap2.draw('pygmap2.html') Output: Code #3 : To add a point into a map # importing pygmapsimport pygmaps # list of latitudeslatitude_list = [30.3358376, 30.307977, 30.3216419, 30.3427904, 30.378598, 30.3548185, 30.3345816, 30.387299, 30.3272198, 30.3840597, 30.4158, 30.340426, 30.3984348, 30.3431313, 30.273471] # list of longitudeslongitude_list = [77.8701919, 78.048457, 78.0413095, 77.886958, 77.825396, 77.8460573, 78.0537813, 78.090614, 78.0355272, 77.9311923, 77.9663, 77.952092, 78.0747887, 77.9555512, 77.9997158] mymap3 = pygmaps.maps(30.3164945, 78.03219179999999, 15) for i in range(len(latitude_list)): # add a point into a map # 1st argument is latitude # 2nd argument is longitude # 3rd argument is colour of the point showed in thed map # using HTML colour code e.g. # red "# FF0000", Blue "# 0000FF", Green "# 00FF00" mymap3.addpoint(latitude_list[i], longitude_list[i], "# FF0000") mymap3.draw('pygmap3.html') Output: Code #4 : To Draw a circle of given radius import pygmaps mymap4 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # Draw a circle of given radius# 1st argument is latitude# 2nd argument is longitude# 3rd argument is radius (in meter)# 4th argument is colour of the circlemymap4.addradpoint(30.307977, 78.048457, 95, "# FF0000")mymap4.draw('pygmap4.html') Output : Code #5 : To draw a line in b/w the given coordinates # Importing pygmapsimport pygmaps mymap5 = pygmaps.maps(30.3164945, 78.03219179999999, 15) latitude_list =[30.343769, 30.307977]longitude_list =[77.999559, 78.048457] for i in range(len(latitude_list)) : mymap5.addpoint(latitude_list[i], longitude_list[i], "# FF0000") # list of coordinates path = [(30.343769, 77.999559), (30.307977, 78.048457)] # draw a line in b / w the given coordinates# 1st argument is list of coordinates# 2nd argument is colour of the linemymap5.addpath(path, "# 00FF00") mymap5.draw('pygmap5.html') Output: python-modules python-utility 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 Convert integer to string in Python
[ { "code": null, "e": 26609, "s": 26581, "text": "\n15 Oct, 2020" }, { "code": null, "e": 26747, "s": 26609, "text": "pygmaps is a matplotlib-like interface to generate the HTML and javascript to render all the data users would like on top of Google Maps." }, { "code": null, "e": 26776, "s": 26747, "text": "Command to install pygmaps :" }, { "code": null, "e": 26854, "s": 26776, "text": "pip install pygmaps (on windows)\nsudo pip3 install pygmaps (on linix / unix)\n" }, { "code": null, "e": 26887, "s": 26854, "text": " Code #1 : To create a Base Map." }, { "code": "# import required packageimport pygmaps # maps method return map object# 1st argument is center latitude# 2nd argument is center longitude# 3ed argument zoom levelmymap1 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # create the HTML file which includes# google map. Pass the absolute path# as an argument.mymap1.draw('pygmap1.html')", "e": 27227, "s": 26887, "text": null }, { "code": null, "e": 27266, "s": 27227, "text": "Output: Code #2 : To draw grids on map" }, { "code": "# importing pygmapsimport pygmaps mymap2 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # draw grids on the map# 1st argument is the starting point of latitude# 2nd argument is the ending point of latitude# 3rd argument is grid size in latitude# 4th argument is the starting point of longitude# 5th argument is the ending point of longitude# 6th argument is grid size in longitudemymap2.setgrids(30.31, 30.32, 0.001, 78.04, 78.03, 0.001) mymap2.draw('pygmap2.html')", "e": 27769, "s": 27266, "text": null }, { "code": null, "e": 27813, "s": 27769, "text": "Output: Code #3 : To add a point into a map" }, { "code": "# importing pygmapsimport pygmaps # list of latitudeslatitude_list = [30.3358376, 30.307977, 30.3216419, 30.3427904, 30.378598, 30.3548185, 30.3345816, 30.387299, 30.3272198, 30.3840597, 30.4158, 30.340426, 30.3984348, 30.3431313, 30.273471] # list of longitudeslongitude_list = [77.8701919, 78.048457, 78.0413095, 77.886958, 77.825396, 77.8460573, 78.0537813, 78.090614, 78.0355272, 77.9311923, 77.9663, 77.952092, 78.0747887, 77.9555512, 77.9997158] mymap3 = pygmaps.maps(30.3164945, 78.03219179999999, 15) for i in range(len(latitude_list)): # add a point into a map # 1st argument is latitude # 2nd argument is longitude # 3rd argument is colour of the point showed in thed map # using HTML colour code e.g. # red \"# FF0000\", Blue \"# 0000FF\", Green \"# 00FF00\" mymap3.addpoint(latitude_list[i], longitude_list[i], \"# FF0000\") mymap3.draw('pygmap3.html')", "e": 28836, "s": 27813, "text": null }, { "code": null, "e": 28887, "s": 28836, "text": "Output: Code #4 : To Draw a circle of given radius" }, { "code": "import pygmaps mymap4 = pygmaps.maps(30.3164945, 78.03219179999999, 15) # Draw a circle of given radius# 1st argument is latitude# 2nd argument is longitude# 3rd argument is radius (in meter)# 4th argument is colour of the circlemymap4.addradpoint(30.307977, 78.048457, 95, \"# FF0000\")mymap4.draw('pygmap4.html')", "e": 29202, "s": 28887, "text": null }, { "code": null, "e": 29211, "s": 29202, "text": "Output :" }, { "code": null, "e": 29265, "s": 29211, "text": "Code #5 : To draw a line in b/w the given coordinates" }, { "code": "# Importing pygmapsimport pygmaps mymap5 = pygmaps.maps(30.3164945, 78.03219179999999, 15) latitude_list =[30.343769, 30.307977]longitude_list =[77.999559, 78.048457] for i in range(len(latitude_list)) : mymap5.addpoint(latitude_list[i], longitude_list[i], \"# FF0000\") # list of coordinates path = [(30.343769, 77.999559), (30.307977, 78.048457)] # draw a line in b / w the given coordinates# 1st argument is list of coordinates# 2nd argument is colour of the linemymap5.addpath(path, \"# 00FF00\") mymap5.draw('pygmap5.html')", "e": 29814, "s": 29265, "text": null }, { "code": null, "e": 29822, "s": 29814, "text": "Output:" }, { "code": null, "e": 29837, "s": 29822, "text": "python-modules" }, { "code": null, "e": 29852, "s": 29837, "text": "python-utility" }, { "code": null, "e": 29859, "s": 29852, "text": "Python" }, { "code": null, "e": 29957, "s": 29859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29975, "s": 29957, "text": "Python Dictionary" }, { "code": null, "e": 30010, "s": 29975, "text": "Read a file line by line in Python" }, { "code": null, "e": 30042, "s": 30010, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30064, "s": 30042, "text": "Enumerate() in Python" }, { "code": null, "e": 30106, "s": 30064, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30136, "s": 30106, "text": "Iterate over a list in Python" }, { "code": null, "e": 30162, "s": 30136, "text": "Python String | replace()" }, { "code": null, "e": 30191, "s": 30162, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30235, "s": 30191, "text": "Reading and Writing to text files in Python" } ]
Java Program to Implement HashMap API - GeeksforGeeks
11 Feb, 2021 HashMap<K, V> is a part of Java’s collection since Java 1.2. This class is found in java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer). One object is used as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass. Implementation: Java // Java program to implement HashMap API import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set; public class HashMapImplementation<K, V> { private HashMap<K, V> hashMap; // Constructs an empty HashMap with the default initial // capacity (16) and the default load factor (0.75). public HashMapImplementation() { hashMap = new HashMap<K, V>(); } // Constructs an empty HashMap with the specified // initial capacity and the default load factor (0.75). public HashMapImplementation(int initialCapacity) { hashMap = new HashMap<K, V>(initialCapacity); } // Constructs an empty HashMap with the specified // initial capacity and load factor. public HashMapImplementation(int initialCapacity, float loadFactor) { hashMap = new HashMap<K, V>(initialCapacity, loadFactor); } // Constructs a new HashMap with the same mappings as // the specified Map. public HashMapImplementation(Map<? extends K, ? extends V> m) { hashMap = new HashMap<K, V>(m); } // Removes all of the mappings from this map. public void clear() { hashMap.clear(); } // Returns a shallow copy of this HashMap instance: the // keys and values // themselves are not cloned. public Object clone() { return hashMap.clone(); } // return true if map contains given key public boolean containsKey(Object key) { return hashMap.containsKey(key); } // Returns true if this map maps one or more keys to the // specified value. public boolean containsValue(Object value) { return hashMap.containsValue(value); } // Returns a Set view of the mappings contained in this // map. public Set<Map.Entry<K, V> > entrySet() { return hashMap.entrySet(); } // return the value for which the key is mapped , if key // is not mapped with any value then it will return null public V get(Object key) { return hashMap.get(key); } // return true if hashmap is empty else false public boolean isEmpty() { return hashMap.isEmpty(); } // Returns a Set view of the keys contained in this map. public Set<K> keySet() { return hashMap.keySet(); } // map the key with value public V put(K key, V value) { return hashMap.put(key, value); } // copy all the mapping to this map public void putAll(Map<? extends K, ? extends V> m) { hashMap.putAll(m); } // remove the mapping of given key public V remove(Object key) { return hashMap.remove(key); } // returns the size of map(number of key ) public int size() { return hashMap.size(); } // Returns a Collection view of the values contained in // this map. public Collection<V> values() { return hashMap.values(); }} class GFG { public static void main(String arg[]) { HashMapImplementation<Integer, String> hashMap = new HashMapImplementation<Integer, String>(); hashMap.put(1, "Kapil"); hashMap.put(2, "Nikhil"); hashMap.put(3, "Sachin"); Map<Integer, String> secondMap = new HashMap<Integer, String>(); secondMap.put(4, "Aakash"); secondMap.put(5, "Ravi"); hashMap.putAll(secondMap); System.out.println("the key set of the map is "); Set<Integer> keySet = hashMap.keySet(); Iterator<Integer> itr = keySet.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + "\t"); } System.out.println(); System.out.println("the values of the map is "); Iterator<String> itr1; Collection<String> collectionValues = hashMap.values(); itr1 = collectionValues.iterator(); while (itr1.hasNext()) { System.out.print(itr1.next() + "\t"); } System.out.println(); System.out.println("the entry set of the map is "); Iterator<Entry<Integer, String> > eitr; Set<Entry<Integer, String> > entrySet = hashMap.entrySet(); eitr = entrySet.iterator(); while (eitr.hasNext()) { System.out.println(eitr.next() + "\t"); } System.out.println("the hash Map contains Key 3 :" + hashMap.containsKey(3)); System.out.println("the hash Map contains Value Mohan :" + hashMap.containsValue("Mohan")); System.out.println("the size of the hash Map is " + hashMap.size()); hashMap.clear(); if (hashMap.isEmpty()) System.out.println("the hash Map is empty"); else System.out.println("the hash Map is not empty"); }} the key set of the map is 1 2 3 4 5 the values of the map is Kapil Nikhil Sachin Aakash Ravi the entry set of the map is 1=Kapil 2=Nikhil 3=Sachin 4=Aakash 5=Ravi the hash Map contains Key 3 :true the hash Map contains Value Mohan :false the size of the hash Map is 5 the hash Map is empty Java-Collections Java-HashMap Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n11 Feb, 2021" }, { "code": null, "e": 25665, "s": 25225, "text": "HashMap<K, V> is a part of Java’s collection since Java 1.2. This class is found in java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer). One object is used as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key." }, { "code": null, "e": 26018, "s": 25665, "text": "HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass." }, { "code": null, "e": 26034, "s": 26018, "text": "Implementation:" }, { "code": null, "e": 26039, "s": 26034, "text": "Java" }, { "code": "// Java program to implement HashMap API import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set; public class HashMapImplementation<K, V> { private HashMap<K, V> hashMap; // Constructs an empty HashMap with the default initial // capacity (16) and the default load factor (0.75). public HashMapImplementation() { hashMap = new HashMap<K, V>(); } // Constructs an empty HashMap with the specified // initial capacity and the default load factor (0.75). public HashMapImplementation(int initialCapacity) { hashMap = new HashMap<K, V>(initialCapacity); } // Constructs an empty HashMap with the specified // initial capacity and load factor. public HashMapImplementation(int initialCapacity, float loadFactor) { hashMap = new HashMap<K, V>(initialCapacity, loadFactor); } // Constructs a new HashMap with the same mappings as // the specified Map. public HashMapImplementation(Map<? extends K, ? extends V> m) { hashMap = new HashMap<K, V>(m); } // Removes all of the mappings from this map. public void clear() { hashMap.clear(); } // Returns a shallow copy of this HashMap instance: the // keys and values // themselves are not cloned. public Object clone() { return hashMap.clone(); } // return true if map contains given key public boolean containsKey(Object key) { return hashMap.containsKey(key); } // Returns true if this map maps one or more keys to the // specified value. public boolean containsValue(Object value) { return hashMap.containsValue(value); } // Returns a Set view of the mappings contained in this // map. public Set<Map.Entry<K, V> > entrySet() { return hashMap.entrySet(); } // return the value for which the key is mapped , if key // is not mapped with any value then it will return null public V get(Object key) { return hashMap.get(key); } // return true if hashmap is empty else false public boolean isEmpty() { return hashMap.isEmpty(); } // Returns a Set view of the keys contained in this map. public Set<K> keySet() { return hashMap.keySet(); } // map the key with value public V put(K key, V value) { return hashMap.put(key, value); } // copy all the mapping to this map public void putAll(Map<? extends K, ? extends V> m) { hashMap.putAll(m); } // remove the mapping of given key public V remove(Object key) { return hashMap.remove(key); } // returns the size of map(number of key ) public int size() { return hashMap.size(); } // Returns a Collection view of the values contained in // this map. public Collection<V> values() { return hashMap.values(); }} class GFG { public static void main(String arg[]) { HashMapImplementation<Integer, String> hashMap = new HashMapImplementation<Integer, String>(); hashMap.put(1, \"Kapil\"); hashMap.put(2, \"Nikhil\"); hashMap.put(3, \"Sachin\"); Map<Integer, String> secondMap = new HashMap<Integer, String>(); secondMap.put(4, \"Aakash\"); secondMap.put(5, \"Ravi\"); hashMap.putAll(secondMap); System.out.println(\"the key set of the map is \"); Set<Integer> keySet = hashMap.keySet(); Iterator<Integer> itr = keySet.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \"\\t\"); } System.out.println(); System.out.println(\"the values of the map is \"); Iterator<String> itr1; Collection<String> collectionValues = hashMap.values(); itr1 = collectionValues.iterator(); while (itr1.hasNext()) { System.out.print(itr1.next() + \"\\t\"); } System.out.println(); System.out.println(\"the entry set of the map is \"); Iterator<Entry<Integer, String> > eitr; Set<Entry<Integer, String> > entrySet = hashMap.entrySet(); eitr = entrySet.iterator(); while (eitr.hasNext()) { System.out.println(eitr.next() + \"\\t\"); } System.out.println(\"the hash Map contains Key 3 :\" + hashMap.containsKey(3)); System.out.println(\"the hash Map contains Value Mohan :\" + hashMap.containsValue(\"Mohan\")); System.out.println(\"the size of the hash Map is \" + hashMap.size()); hashMap.clear(); if (hashMap.isEmpty()) System.out.println(\"the hash Map is empty\"); else System.out.println(\"the hash Map is not empty\"); }}", "e": 31004, "s": 26039, "text": null }, { "code": null, "e": 31350, "s": 31004, "text": "the key set of the map is \n1 2 3 4 5 \nthe values of the map is \nKapil Nikhil Sachin Aakash Ravi \nthe entry set of the map is \n1=Kapil \n2=Nikhil \n3=Sachin \n4=Aakash \n5=Ravi \nthe hash Map contains Key 3 :true\nthe hash Map contains Value Mohan :false\nthe size of the hash Map is 5\nthe hash Map is empty\n" }, { "code": null, "e": 31367, "s": 31350, "text": "Java-Collections" }, { "code": null, "e": 31380, "s": 31367, "text": "Java-HashMap" }, { "code": null, "e": 31387, "s": 31380, "text": "Picked" }, { "code": null, "e": 31392, "s": 31387, "text": "Java" }, { "code": null, "e": 31406, "s": 31392, "text": "Java Programs" }, { "code": null, "e": 31411, "s": 31406, "text": "Java" }, { "code": null, "e": 31428, "s": 31411, "text": "Java-Collections" }, { "code": null, "e": 31526, "s": 31428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31541, "s": 31526, "text": "Stream In Java" }, { "code": null, "e": 31562, "s": 31541, "text": "Constructors in Java" }, { "code": null, "e": 31581, "s": 31562, "text": "Exceptions in Java" }, { "code": null, "e": 31611, "s": 31581, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31657, "s": 31611, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31683, "s": 31657, "text": "Java Programming Examples" }, { "code": null, "e": 31717, "s": 31683, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 31764, "s": 31717, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 31796, "s": 31764, "text": "How to Iterate HashMap in Java?" } ]
Transform ggplot2 Plot Axis to log Scale in R - GeeksforGeeks
17 Oct, 2021 In this article, we will discuss how to transform the ggplot2 Plot Axis to log Scale in the R Programming Language. We can convert the axis data into the desired log scale using the scale_x_continous() function. We pass the desired log scale as argument trans and the data is transformed according to that log scale in the ggplot2 plot. Syntax: plot + scale_x_continous( trans ) / scale_y_continous( trans ) Parameter: trans: determine the type of transformation given axis will go through. Note: Using this method only the data plots are converted into the log scale. The axis tick marks and label remain the same. Example: Here is a basic scatter plot converted into the log10 scale x-axis by using scale_x_continuous function with trans argument as log10. R #load library ggplot2library("ggplot2") # set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) # draw scatter plot using ggplot() #and geom_point() functionplot<- ggplot(sample_data, aes(x_axis_values, y_axis_values)) + geom_point() # scale_x_continuous #with trans argument transforms axis data to log scaleplot<- plot + scale_x_continuous(trans = "log10") # show plotplot Output: In this method, we directly pass the parameter value in aes() function of ggplot() function as log. This is the best method as this updates the data point as well as axis tick marks and axis labels all in one go. Syntax: ggplot( df, aes( log(x), y) Parameter : log: determines any desired log function for transformation Example: Here is a basic scatter plot converted into the log10 scale x-axis by using the log10() function in aes function of ggplot() function. R # set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) #load library ggplot2library("ggplot2") # draw scatter plot using ggplot() and geom_point() function# In aes instead of x_axis_values log10(x_axis_values is used# this transforms the x-axis scale to log scaleplot<- ggplot(sample_data, aes(log10(x_axis_values), y_axis_values)) + geom_point() # show plotplot Output: We can convert the axis data into the desired log scale using the scale_x_log10() / scale_y_log10() function. we use the desired axis function to get the required result. Syntax: plot + scale_x_log10() / scale_y_log10() Note: Using this method only the data plots are converted into the log scale. The axis tick marks and label remain the same. Example: Here is a basic scatter plot converted into the log10 scale x-axis by using the scale_x_log10() function. R # set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) #load library ggplot2library("ggplot2") # draw scatter plot using ggplot() and geom_point() function# scale_x_log10() function converts the x-axis values to# log10 scaleplot<- ggplot(sample_data, aes(x_axis_values, y_axis_values)) + geom_point() + scale_x_log10() # show plotplot Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R
[ { "code": null, "e": 26355, "s": 26327, "text": "\n17 Oct, 2021" }, { "code": null, "e": 26472, "s": 26355, "text": "In this article, we will discuss how to transform the ggplot2 Plot Axis to log Scale in the R Programming Language. " }, { "code": null, "e": 26693, "s": 26472, "text": "We can convert the axis data into the desired log scale using the scale_x_continous() function. We pass the desired log scale as argument trans and the data is transformed according to that log scale in the ggplot2 plot." }, { "code": null, "e": 26701, "s": 26693, "text": "Syntax:" }, { "code": null, "e": 26765, "s": 26701, "text": "plot + scale_x_continous( trans ) / scale_y_continous( trans ) " }, { "code": null, "e": 26776, "s": 26765, "text": "Parameter:" }, { "code": null, "e": 26848, "s": 26776, "text": "trans: determine the type of transformation given axis will go through." }, { "code": null, "e": 26973, "s": 26848, "text": "Note: Using this method only the data plots are converted into the log scale. The axis tick marks and label remain the same." }, { "code": null, "e": 26982, "s": 26973, "text": "Example:" }, { "code": null, "e": 27116, "s": 26982, "text": "Here is a basic scatter plot converted into the log10 scale x-axis by using scale_x_continuous function with trans argument as log10." }, { "code": null, "e": 27118, "s": 27116, "text": "R" }, { "code": "#load library ggplot2library(\"ggplot2\") # set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) # draw scatter plot using ggplot() #and geom_point() functionplot<- ggplot(sample_data, aes(x_axis_values, y_axis_values)) + geom_point() # scale_x_continuous #with trans argument transforms axis data to log scaleplot<- plot + scale_x_continuous(trans = \"log10\") # show plotplot", "e": 27648, "s": 27118, "text": null }, { "code": null, "e": 27656, "s": 27648, "text": "Output:" }, { "code": null, "e": 27869, "s": 27656, "text": "In this method, we directly pass the parameter value in aes() function of ggplot() function as log. This is the best method as this updates the data point as well as axis tick marks and axis labels all in one go." }, { "code": null, "e": 27877, "s": 27869, "text": "Syntax:" }, { "code": null, "e": 27905, "s": 27877, "text": "ggplot( df, aes( log(x), y)" }, { "code": null, "e": 27917, "s": 27905, "text": "Parameter :" }, { "code": null, "e": 27977, "s": 27917, "text": "log: determines any desired log function for transformation" }, { "code": null, "e": 27986, "s": 27977, "text": "Example:" }, { "code": null, "e": 28121, "s": 27986, "text": "Here is a basic scatter plot converted into the log10 scale x-axis by using the log10() function in aes function of ggplot() function." }, { "code": null, "e": 28123, "s": 28121, "text": "R" }, { "code": "# set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) #load library ggplot2library(\"ggplot2\") # draw scatter plot using ggplot() and geom_point() function# In aes instead of x_axis_values log10(x_axis_values is used# this transforms the x-axis scale to log scaleplot<- ggplot(sample_data, aes(log10(x_axis_values), y_axis_values)) + geom_point() # show plotplot", "e": 28641, "s": 28123, "text": null }, { "code": null, "e": 28649, "s": 28641, "text": "Output:" }, { "code": null, "e": 28821, "s": 28649, "text": "We can convert the axis data into the desired log scale using the scale_x_log10() / scale_y_log10() function. we use the desired axis function to get the required result." }, { "code": null, "e": 28829, "s": 28821, "text": "Syntax:" }, { "code": null, "e": 28870, "s": 28829, "text": "plot + scale_x_log10() / scale_y_log10()" }, { "code": null, "e": 28995, "s": 28870, "text": "Note: Using this method only the data plots are converted into the log scale. The axis tick marks and label remain the same." }, { "code": null, "e": 29004, "s": 28995, "text": "Example:" }, { "code": null, "e": 29110, "s": 29004, "text": "Here is a basic scatter plot converted into the log10 scale x-axis by using the scale_x_log10() function." }, { "code": null, "e": 29112, "s": 29110, "text": "R" }, { "code": "# set seedset.seed(50000) # create sample data using rnorm functionsample_data <- data.frame(x_axis_values = rnorm(1000, 700, 105), y_axis_values = rnorm(1000, 45, 200)) #load library ggplot2library(\"ggplot2\") # draw scatter plot using ggplot() and geom_point() function# scale_x_log10() function converts the x-axis values to# log10 scaleplot<- ggplot(sample_data, aes(x_axis_values, y_axis_values)) + geom_point() + scale_x_log10() # show plotplot", "e": 29602, "s": 29112, "text": null }, { "code": null, "e": 29610, "s": 29602, "text": "Output:" }, { "code": null, "e": 29617, "s": 29610, "text": "Picked" }, { "code": null, "e": 29626, "s": 29617, "text": "R-ggplot" }, { "code": null, "e": 29637, "s": 29626, "text": "R Language" }, { "code": null, "e": 29735, "s": 29637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29787, "s": 29735, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29822, "s": 29787, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29860, "s": 29822, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29918, "s": 29860, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29954, "s": 29918, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 29997, "s": 29954, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30046, "s": 29997, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30083, "s": 30046, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30100, "s": 30083, "text": "R - if statement" } ]
How to create linear-gradient color generator using HTML, CSS and JavaScript ? - GeeksforGeeks
18 Mar, 2020 The background generator can be made by using HTML, CSS, and JavaScript. It will generate a gradient background based on the values that you select. We will add two files namely style.css and script.js to add CSS and JS to our HTML(index.html). We have used an empty h3 tag so that we can display the linear-gradient color codes. HTML code: Save the code in a file as index.html. In index.html file, we will use two inputs of type “color” to get the values of gradients.<!DOCTYPE html><html> <head> <title>Gradient color generator</title></head> <body class="change"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class="color1" type="color" value="#0000ff" /> <input class="color2" type="color" value="#add8e6" /></body> </html> <!DOCTYPE html><html> <head> <title>Gradient color generator</title></head> <body class="change"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class="color1" type="color" value="#0000ff" /> <input class="color2" type="color" value="#add8e6" /></body> </html> CSS code: For CSS, we have done only some basic styling with some fonts and default background color. You can use the below stylesheet as a reference to create your own custom styles by changing some fonts and colors.<style> /* Styling body */ body { font: "Roboto"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } /* h1 tag text color */ h1 { color: white; } </style> <style> /* Styling body */ body { font: "Roboto"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } /* h1 tag text color */ h1 { color: white; } </style> JavaScript code: Now comes to the JavaScript part. The first thing we have done is we have selected the colour1 and colour2 nodes using document.querySelector() method. Using the same method we have also select the h3 and body. If you don’t know how the querySelector works, we highly recommend you to first learn about this. Now we create a function to set a newly selected gradient as the background. In this function, we simply apply values which we get using document.querySelector() to the background. We have used css.textcontent to assign the value of linear-gradient to the h3 tag.<script> var css = document.querySelector("h3"); var color1 = document.querySelector(".color1"); var color2 = document.querySelector(".color2"); var body = document.querySelector(".change"); // Changing color for the gradient function changeGradient() { body.style.background = "linear-gradient(to right, " + color1.value + ", " + color2.value + ")"; css.textContent = body.style.background + ";"; } color1.addEventListener("input", changeGradient); color2.addEventListener("input", changeGradient);</script> <script> var css = document.querySelector("h3"); var color1 = document.querySelector(".color1"); var color2 = document.querySelector(".color2"); var body = document.querySelector(".change"); // Changing color for the gradient function changeGradient() { body.style.background = "linear-gradient(to right, " + color1.value + ", " + color2.value + ")"; css.textContent = body.style.background + ";"; } color1.addEventListener("input", changeGradient); color2.addEventListener("input", changeGradient);</script> Complete code: It is the combination of the avobe three sectons code. <!DOCTYPE html><html> <head> <title>Gradient color generator</title> <style> body { font: "Roboto"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } h1 { color: white; } </style></head> <body class="change"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class="color1" type="color" value="#0000ff" /> <input class="color2" type="color" value="#add8e6" /> <script> var css = document.querySelector("h3"); var color1 = document.querySelector(".color1"); var color2 = document.querySelector(".color2"); var body = document.querySelector(".change"); // Changing color for the gradient function changeGradient() { body.style.background = "linear-gradient(to right, " + color1.value + ", " + color2.value + ")"; css.textContent = body.style.background + ";"; } color1.addEventListener("input", changeGradient); color2.addEventListener("input", changeGradient); </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 25967, "s": 25939, "text": "\n18 Mar, 2020" }, { "code": null, "e": 26297, "s": 25967, "text": "The background generator can be made by using HTML, CSS, and JavaScript. It will generate a gradient background based on the values that you select. We will add two files namely style.css and script.js to add CSS and JS to our HTML(index.html). We have used an empty h3 tag so that we can display the linear-gradient color codes." }, { "code": null, "e": 26826, "s": 26297, "text": "HTML code: Save the code in a file as index.html. In index.html file, we will use two inputs of type “color” to get the values of gradients.<!DOCTYPE html><html> <head> <title>Gradient color generator</title></head> <body class=\"change\"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class=\"color1\" type=\"color\" value=\"#0000ff\" /> <input class=\"color2\" type=\"color\" value=\"#add8e6\" /></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Gradient color generator</title></head> <body class=\"change\"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class=\"color1\" type=\"color\" value=\"#0000ff\" /> <input class=\"color2\" type=\"color\" value=\"#add8e6\" /></body> </html>", "e": 27215, "s": 26826, "text": null }, { "code": null, "e": 27667, "s": 27215, "text": "CSS code: For CSS, we have done only some basic styling with some fonts and default background color. You can use the below stylesheet as a reference to create your own custom styles by changing some fonts and colors.<style> /* Styling body */ body { font: \"Roboto\"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } /* h1 tag text color */ h1 { color: white; } </style>" }, { "code": "<style> /* Styling body */ body { font: \"Roboto\"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } /* h1 tag text color */ h1 { color: white; } </style>", "e": 27902, "s": 27667, "text": null }, { "code": null, "e": 29096, "s": 27902, "text": "JavaScript code: Now comes to the JavaScript part. The first thing we have done is we have selected the colour1 and colour2 nodes using document.querySelector() method. Using the same method we have also select the h3 and body. If you don’t know how the querySelector works, we highly recommend you to first learn about this. Now we create a function to set a newly selected gradient as the background. In this function, we simply apply values which we get using document.querySelector() to the background. We have used css.textcontent to assign the value of linear-gradient to the h3 tag.<script> var css = document.querySelector(\"h3\"); var color1 = document.querySelector(\".color1\"); var color2 = document.querySelector(\".color2\"); var body = document.querySelector(\".change\"); // Changing color for the gradient function changeGradient() { body.style.background = \"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\"; css.textContent = body.style.background + \";\"; } color1.addEventListener(\"input\", changeGradient); color2.addEventListener(\"input\", changeGradient);</script>" }, { "code": "<script> var css = document.querySelector(\"h3\"); var color1 = document.querySelector(\".color1\"); var color2 = document.querySelector(\".color2\"); var body = document.querySelector(\".change\"); // Changing color for the gradient function changeGradient() { body.style.background = \"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\"; css.textContent = body.style.background + \";\"; } color1.addEventListener(\"input\", changeGradient); color2.addEventListener(\"input\", changeGradient);</script>", "e": 29701, "s": 29096, "text": null }, { "code": null, "e": 29771, "s": 29701, "text": "Complete code: It is the combination of the avobe three sectons code." }, { "code": "<!DOCTYPE html><html> <head> <title>Gradient color generator</title> <style> body { font: \"Roboto\"; text-align: center; background: linear-gradient(to right, #0000ff, #add8e6); } h1 { color: white; } </style></head> <body class=\"change\"> <h1>GeeksforGeeks</h1> <h3>Gradient color generator</h3> <b>Current Colors for Gradient Background:</b> <!-- Default color for gradient --> <input class=\"color1\" type=\"color\" value=\"#0000ff\" /> <input class=\"color2\" type=\"color\" value=\"#add8e6\" /> <script> var css = document.querySelector(\"h3\"); var color1 = document.querySelector(\".color1\"); var color2 = document.querySelector(\".color2\"); var body = document.querySelector(\".change\"); // Changing color for the gradient function changeGradient() { body.style.background = \"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\"; css.textContent = body.style.background + \";\"; } color1.addEventListener(\"input\", changeGradient); color2.addEventListener(\"input\", changeGradient); </script></body> </html>", "e": 31083, "s": 29771, "text": null }, { "code": null, "e": 31091, "s": 31083, "text": "Output:" }, { "code": null, "e": 31100, "s": 31091, "text": "CSS-Misc" }, { "code": null, "e": 31110, "s": 31100, "text": "HTML-Misc" }, { "code": null, "e": 31126, "s": 31110, "text": "JavaScript-Misc" }, { "code": null, "e": 31130, "s": 31126, "text": "CSS" }, { "code": null, "e": 31135, "s": 31130, "text": "HTML" }, { "code": null, "e": 31146, "s": 31135, "text": "JavaScript" }, { "code": null, "e": 31163, "s": 31146, "text": "Web Technologies" }, { "code": null, "e": 31190, "s": 31163, "text": "Web technologies Questions" }, { "code": null, "e": 31195, "s": 31190, "text": "HTML" }, { "code": null, "e": 31293, "s": 31195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31341, "s": 31293, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31396, "s": 31341, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31433, "s": 31396, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31497, "s": 31433, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 31536, "s": 31497, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31584, "s": 31536, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31644, "s": 31584, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31697, "s": 31644, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31758, "s": 31697, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Double Tree - GeeksforGeeks
10 May, 2022 Write a program that converts a given tree to its Double tree. To create Double tree of the given tree, create a new duplicate for each node, and insert the duplicate as the left child of the original node. So the tree... 2 / \ 1 3 is changed to... 2 / \ 2 3 / / 1 3 / 1 And the tree 1 / \ 2 3 / \ 4 5 is changed to 1 / \ 1 3 / / 2 3 / \ 2 5 / / 4 5 / 4 Algorithm: Recursively convert the tree to double tree in postorder fashion. For each node, first convert the left subtree of the node, then right subtree, finally create a duplicate node of the node and fix the left child of the node and left child of left child.Implementation: C++ C Java Python3 C# Javascript // C++ program to convert binary tree to double tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */class node{ public: int data; node* left; node* right;}; /* function to create a newnode of tree and returns pointer */node* newNode(int data); /* Function to convert a tree to double tree */void doubleTree(node* Node){ node* oldLeft; if (Node == NULL) return; /* do the subtrees */ doubleTree(Node->left); doubleTree(Node->right); /* duplicate this node to its left */ oldLeft = Node->left; Node->left = newNode(Node->data); Node->left->left = oldLeft;} /* UTILITY FUNCTIONS TO TEST doubleTree() FUNCTION *//* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Given a binary tree, print its nodes in inorder*/void printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right);} /* Driver code*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Inorder traversal of the original tree is \n"; printInorder(root); doubleTree(root); cout << "\nInorder traversal of the double tree is \n"; printInorder(root); return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* function to create a new node of tree and returns pointer */struct node* newNode(int data); /* Function to convert a tree to double tree */void doubleTree(struct node* node){ struct node* oldLeft; if (node==NULL) return; /* do the subtrees */ doubleTree(node->left); doubleTree(node->right); /* duplicate this node to its left */ oldLeft = node->left; node->left = newNode(node->data); node->left->left = oldLeft;} /* UTILITY FUNCTIONS TO TEST doubleTree() FUNCTION */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Given a binary tree, print its nodes in inorder*/void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Inorder traversal of the original tree is \n"); printInorder(root); doubleTree(root); printf("\n Inorder traversal of the double tree is \n"); printInorder(root); getchar(); return 0;} // Java program to convert binary tree to double tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Function to convert a tree to double tree */ void doubleTree(Node node) { Node oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } /* Driver program to test the above functions */ public static void main(String args[]) { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Original tree is : "); tree.printInorder(tree.root); tree.doubleTree(tree.root); System.out.println(""); System.out.println("Inorder traversal of double tree is : "); tree.printInorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to convert# binary tree to double tree # A binary tree node has data,# pointer to left child and a# pointer to right childclass Node: def __init__(self, d): self.data = d self.left = None self.right = None # Function to convert a tree to var treedef doubleTree(node) : if node == None : return # do the subtrees doubleTree(node.left) doubleTree(node.right) # duplicate this node to its left oldleft = node.left node.left = Node(node.data) node.left.left = oldleft # Given a binary tree, print its nodes in inorderdef printInorder(node) : if node == None : return printInorder(node.left) print(node.data,end=' ') printInorder(node.right) # Driver Codeif __name__ == '__main__': ''' Driver program to test the above functions */ /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 ''' root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Original tree is : ") printInorder(root) doubleTree(root) print() print("Inorder traversal of double tree is : ") printInorder(root) # This code is contributed by jana_sayantan. // C# program to convert binary tree// to double tree /* A binary tree node has data,pointer to left child anda pointer to right child */using System; class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* Function to convert a tree to double tree */ void doubleTree(Node node) { Node oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver Code public static void Main(String []args) { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("Original tree is : "); tree.printInorder(tree.root); tree.doubleTree(tree.root); Console.WriteLine(""); Console.WriteLine("Inorder traversal of " + "double tree is : "); tree.printInorder(tree.root); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to convert binary tree to var tree /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* Function to convert a tree to var tree */ function doubleTree(node) { var oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(node.data + " "); printInorder(node.right); } /* Driver program to test the above functions */ /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write("Original tree is :<br/> "); printInorder(root); doubleTree(root); document.write("<br/>"); document.write("Inorder traversal of double tree is : <br/>"); printInorder(root); // This code is contributed by todaysgaurav </script> Output: Original tree is : 4 2 5 1 3 Inorder traversal of double tree is : 4 4 2 2 5 5 1 1 3 3 Time Complexity: O(n) where n is the number of nodes in the tree. YouTubeGeeksforGeeks508K subscribersDouble Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=H5MEcaBikVE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://cslibrary.stanford.edu/110/BinaryTrees.htmlPlease write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem. rathbhupendra Rajput-Ji todaysgaurav simranarora5sos jana_sayantan Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree
[ { "code": null, "e": 26115, "s": 26087, "text": "\n10 May, 2022" }, { "code": null, "e": 26338, "s": 26115, "text": "Write a program that converts a given tree to its Double tree. To create Double tree of the given tree, create a new duplicate for each node, and insert the duplicate as the left child of the original node. So the tree... " }, { "code": null, "e": 26359, "s": 26338, "text": " 2\n / \\\n 1 3" }, { "code": null, "e": 26378, "s": 26359, "text": "is changed to... " }, { "code": null, "e": 26434, "s": 26378, "text": " 2\n / \\\n 2 3\n / /\n 1 3\n /\n 1" }, { "code": null, "e": 26448, "s": 26434, "text": "And the tree " }, { "code": null, "e": 26518, "s": 26448, "text": " 1\n / \\\n 2 3\n / \\\n 4 5" }, { "code": null, "e": 26533, "s": 26518, "text": "is changed to " }, { "code": null, "e": 26683, "s": 26533, "text": " 1\n / \\\n 1 3\n / /\n 2 3\n / \\\n 2 5\n / /\n 4 5\n / \n 4 " }, { "code": null, "e": 26964, "s": 26683, "text": "Algorithm: Recursively convert the tree to double tree in postorder fashion. For each node, first convert the left subtree of the node, then right subtree, finally create a duplicate node of the node and fix the left child of the node and left child of left child.Implementation: " }, { "code": null, "e": 26968, "s": 26964, "text": "C++" }, { "code": null, "e": 26970, "s": 26968, "text": "C" }, { "code": null, "e": 26975, "s": 26970, "text": "Java" }, { "code": null, "e": 26983, "s": 26975, "text": "Python3" }, { "code": null, "e": 26986, "s": 26983, "text": "C#" }, { "code": null, "e": 26997, "s": 26986, "text": "Javascript" }, { "code": "// C++ program to convert binary tree to double tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */class node{ public: int data; node* left; node* right;}; /* function to create a newnode of tree and returns pointer */node* newNode(int data); /* Function to convert a tree to double tree */void doubleTree(node* Node){ node* oldLeft; if (Node == NULL) return; /* do the subtrees */ doubleTree(Node->left); doubleTree(Node->right); /* duplicate this node to its left */ oldLeft = Node->left; Node->left = newNode(Node->data); Node->left->left = oldLeft;} /* UTILITY FUNCTIONS TO TEST doubleTree() FUNCTION *//* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* Given a binary tree, print its nodes in inorder*/void printInorder(node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << \" \"; printInorder(node->right);} /* Driver code*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << \"Inorder traversal of the original tree is \\n\"; printInorder(root); doubleTree(root); cout << \"\\nInorder traversal of the double tree is \\n\"; printInorder(root); return 0;} // This code is contributed by rathbhupendra", "e": 28761, "s": 26997, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* function to create a new node of tree and returns pointer */struct node* newNode(int data); /* Function to convert a tree to double tree */void doubleTree(struct node* node){ struct node* oldLeft; if (node==NULL) return; /* do the subtrees */ doubleTree(node->left); doubleTree(node->right); /* duplicate this node to its left */ oldLeft = node->left; node->left = newNode(node->data); node->left->left = oldLeft;} /* UTILITY FUNCTIONS TO TEST doubleTree() FUNCTION */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Given a binary tree, print its nodes in inorder*/void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(\"Inorder traversal of the original tree is \\n\"); printInorder(root); doubleTree(root); printf(\"\\n Inorder traversal of the double tree is \\n\"); printInorder(root); getchar(); return 0;}", "e": 30492, "s": 28761, "text": null }, { "code": "// Java program to convert binary tree to double tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Function to convert a tree to double tree */ void doubleTree(Node node) { Node oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } /* Driver program to test the above functions */ public static void main(String args[]) { /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println(\"Original tree is : \"); tree.printInorder(tree.root); tree.doubleTree(tree.root); System.out.println(\"\"); System.out.println(\"Inorder traversal of double tree is : \"); tree.printInorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 32233, "s": 30492, "text": null }, { "code": "# Python3 program to convert# binary tree to double tree # A binary tree node has data,# pointer to left child and a# pointer to right childclass Node: def __init__(self, d): self.data = d self.left = None self.right = None # Function to convert a tree to var treedef doubleTree(node) : if node == None : return # do the subtrees doubleTree(node.left) doubleTree(node.right) # duplicate this node to its left oldleft = node.left node.left = Node(node.data) node.left.left = oldleft # Given a binary tree, print its nodes in inorderdef printInorder(node) : if node == None : return printInorder(node.left) print(node.data,end=' ') printInorder(node.right) # Driver Codeif __name__ == '__main__': ''' Driver program to test the above functions */ /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 ''' root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(\"Original tree is : \") printInorder(root) doubleTree(root) print() print(\"Inorder traversal of double tree is : \") printInorder(root) # This code is contributed by jana_sayantan.", "e": 33558, "s": 32233, "text": null }, { "code": "// C# program to convert binary tree// to double tree /* A binary tree node has data,pointer to left child anda pointer to right child */using System; class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* Function to convert a tree to double tree */ void doubleTree(Node node) { Node oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver Code public static void Main(String []args) { /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine(\"Original tree is : \"); tree.printInorder(tree.root); tree.doubleTree(tree.root); Console.WriteLine(\"\"); Console.WriteLine(\"Inorder traversal of \" + \"double tree is : \"); tree.printInorder(tree.root); }} // This code is contributed by Rajput-Ji", "e": 35287, "s": 33558, "text": null }, { "code": "<script> // JavaScript program to convert binary tree to var tree /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* Function to convert a tree to var tree */ function doubleTree(node) { var oldleft; if (node == null) return; /* do the subtrees */ doubleTree(node.left); doubleTree(node.right); /* duplicate this node to its left */ oldleft = node.left; node.left = new Node(node.data); node.left.left = oldleft; } /* Given a binary tree, print its nodes in inorder*/ function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right); } /* Driver program to test the above functions */ /* Constructed binary tree is 1 / \\ 2 3 / \\ 4 5 */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write(\"Original tree is :<br/> \"); printInorder(root); doubleTree(root); document.write(\"<br/>\"); document.write(\"Inorder traversal of double tree is : <br/>\"); printInorder(root); // This code is contributed by todaysgaurav </script>", "e": 36869, "s": 35287, "text": null }, { "code": null, "e": 36879, "s": 36869, "text": "Output: " }, { "code": null, "e": 36970, "s": 36879, "text": "Original tree is : \n4 2 5 1 3 \nInorder traversal of double tree is : \n4 4 2 2 5 5 1 1 3 3 " }, { "code": null, "e": 37036, "s": 36970, "text": "Time Complexity: O(n) where n is the number of nodes in the tree." }, { "code": null, "e": 37846, "s": 37036, "text": "YouTubeGeeksforGeeks508K subscribersDouble Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=H5MEcaBikVE\" 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": 38022, "s": 37846, "text": "References: http://cslibrary.stanford.edu/110/BinaryTrees.htmlPlease write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem. " }, { "code": null, "e": 38036, "s": 38022, "text": "rathbhupendra" }, { "code": null, "e": 38046, "s": 38036, "text": "Rajput-Ji" }, { "code": null, "e": 38059, "s": 38046, "text": "todaysgaurav" }, { "code": null, "e": 38075, "s": 38059, "text": "simranarora5sos" }, { "code": null, "e": 38089, "s": 38075, "text": "jana_sayantan" }, { "code": null, "e": 38094, "s": 38089, "text": "Tree" }, { "code": null, "e": 38099, "s": 38094, "text": "Tree" }, { "code": null, "e": 38197, "s": 38099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38240, "s": 38197, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 38273, "s": 38240, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 38287, "s": 38273, "text": "Decision Tree" }, { "code": null, "e": 38345, "s": 38287, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 38381, "s": 38345, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 38429, "s": 38381, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 38456, "s": 38429, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 38539, "s": 38456, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 38555, "s": 38539, "text": "Expression Tree" } ]
React Native ListView Component - GeeksforGeeks
30 Jun, 2021 The ListView Component is an inbuilt React Native view component that displays a list of items in a vertically scrollable list. It requires a ListView.DataSource API to populate a simple array of data blobs and instantiate the ListView component with a data source and a renderRow callback. The major advantage of using the ListView Component over the ScrollView Component is that it overcomes the performance shortcomings of the ScrollView Component. Behind the scenes, however, the ListView Component uses a ScrollView as its scrollable component. Thus, the ListView Component is an abstraction that optimizes the ScrollView Component. Syntax: <ListView dataSource={} renderRow={} /> ListView Props: dataSource: It gives an instance of the ListView.DataSource to be used. renderRow: It is used to take a blob from the data array as an argument and returns a renderable component. initialListSize: It is used to specify the number of rows to be rendered when the component mounts initially. onEndReachedThreshold: It is used to specify the threshold value in pixels for calling onEndReached. pageSize: It is used to specify the number of rows to render per event loop. renderScrollComponent: It is used to return the scrollable component in which the list rows are rendered. scrollRenderAheadDistance: It specifies how early to start rendering list rows before they appear on the screen. stickyHeaderIndices: It is an array of child indices that specify the children to be docked to the top of the screen when scrolling. enableEmptySections: It is a flag that indicates if an empty section header needs to be rendered or not. onEndReached: It is invoked when all rows have been rendered on screen and the list has been scrolled to within the onEndReachedThreshold. stickySectionHeadersEnabled: As the name suggests, it is used to make the section headers sticky. renderSectionHeader: If this prop is provided, a header is rendered for the particular section. renderSeparator: If this prop is provided, a renderable component (rendered as a separator below each row except the last row) is added. onChangeVisibleRows: It is invoked only when some visible rows change. removeClippedSubviews: It is used for performance optimization and mainly used in conjunction with overflow: ‘hidden’ on the row containers. renderFooter: If these props are provided, the header and footer are always rendered on every render pass. ListView Methods: getMetrics(): Function used to export data, primarily for analytics purposes. scrollTo(): Function used to scroll to a given x-y offset. scrollToEnd(): Function used to scroll the list. In the case of a vertical ListView, it is used to scroll to the bottom of the list. In the case of a horizontal ListView, it is used to scroll to the right. flashScrollIndicators(): Function used to briefly show the scroll indicators. Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init listview-demo Step 2: Now create a project by the following command. expo init listview-demo Step 3: Now go into your project folder i.e. listview-democd listview-demo Step 3: Now go into your project folder i.e. listview-demo cd listview-demo Project Structure: It will look like this. Example: Basic Use of ListView Component App.js import React, { Component } from "react";import { Text, View, StyleSheet, ListView } from "react-native";import { Icon } from "react-native-elements"; const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2}); class App extends Component { state = { dataSource: ds.cloneWithRows([ "Data Structures", "STL", "C++", "Java", "Python", "ReactJS", "Angular", "NodeJs", "PHP", "MongoDb", "MySql", "Android", "iOS", "Hadoop", "Ajax", "Ruby", "Rails", ".Net", "Perl", ]), }; render() { return ( <View style={styles.screen}> <ListView dataSource={this.state.dataSource} renderRow={(rowData) => ( <View style={styles.row}> <Text style={styles.rowText}>{rowData}</Text> <Icon name="ios-eye" type="ionicon" color="#C2185B" /> </View> )} /> </View> ); }} // Screen stylesconst styles = StyleSheet.create({ screen: { marginTop: 30, }, row: { margin: 15, flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 2, }, rowText: { fontSize: 18, },}); export default App; Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Note: It is important to note that ListView Component is now deprecated. Instead, newer components are used, such as FlatList or SectionList. To use the ListView Component, use the deprecated-react-native-listview package. import ListView from "deprecated-react-native-listview"; Reference: https://reactnative.dev/docs/0.62/listview Picked React-Native React-Native Component Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? How to execute PHP code using command line ? Difference Between PUT and PATCH Request REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26169, "s": 26141, "text": "\n30 Jun, 2021" }, { "code": null, "e": 26460, "s": 26169, "text": "The ListView Component is an inbuilt React Native view component that displays a list of items in a vertically scrollable list. It requires a ListView.DataSource API to populate a simple array of data blobs and instantiate the ListView component with a data source and a renderRow callback." }, { "code": null, "e": 26807, "s": 26460, "text": "The major advantage of using the ListView Component over the ScrollView Component is that it overcomes the performance shortcomings of the ScrollView Component. Behind the scenes, however, the ListView Component uses a ScrollView as its scrollable component. Thus, the ListView Component is an abstraction that optimizes the ScrollView Component." }, { "code": null, "e": 26815, "s": 26807, "text": "Syntax:" }, { "code": null, "e": 26863, "s": 26815, "text": "<ListView\n dataSource={}\n renderRow={}\n/>" }, { "code": null, "e": 26879, "s": 26863, "text": "ListView Props:" }, { "code": null, "e": 26951, "s": 26879, "text": "dataSource: It gives an instance of the ListView.DataSource to be used." }, { "code": null, "e": 27059, "s": 26951, "text": "renderRow: It is used to take a blob from the data array as an argument and returns a renderable component." }, { "code": null, "e": 27169, "s": 27059, "text": "initialListSize: It is used to specify the number of rows to be rendered when the component mounts initially." }, { "code": null, "e": 27270, "s": 27169, "text": "onEndReachedThreshold: It is used to specify the threshold value in pixels for calling onEndReached." }, { "code": null, "e": 27347, "s": 27270, "text": "pageSize: It is used to specify the number of rows to render per event loop." }, { "code": null, "e": 27453, "s": 27347, "text": "renderScrollComponent: It is used to return the scrollable component in which the list rows are rendered." }, { "code": null, "e": 27566, "s": 27453, "text": "scrollRenderAheadDistance: It specifies how early to start rendering list rows before they appear on the screen." }, { "code": null, "e": 27699, "s": 27566, "text": "stickyHeaderIndices: It is an array of child indices that specify the children to be docked to the top of the screen when scrolling." }, { "code": null, "e": 27804, "s": 27699, "text": "enableEmptySections: It is a flag that indicates if an empty section header needs to be rendered or not." }, { "code": null, "e": 27943, "s": 27804, "text": "onEndReached: It is invoked when all rows have been rendered on screen and the list has been scrolled to within the onEndReachedThreshold." }, { "code": null, "e": 28041, "s": 27943, "text": "stickySectionHeadersEnabled: As the name suggests, it is used to make the section headers sticky." }, { "code": null, "e": 28137, "s": 28041, "text": "renderSectionHeader: If this prop is provided, a header is rendered for the particular section." }, { "code": null, "e": 28274, "s": 28137, "text": "renderSeparator: If this prop is provided, a renderable component (rendered as a separator below each row except the last row) is added." }, { "code": null, "e": 28345, "s": 28274, "text": "onChangeVisibleRows: It is invoked only when some visible rows change." }, { "code": null, "e": 28486, "s": 28345, "text": "removeClippedSubviews: It is used for performance optimization and mainly used in conjunction with overflow: ‘hidden’ on the row containers." }, { "code": null, "e": 28593, "s": 28486, "text": "renderFooter: If these props are provided, the header and footer are always rendered on every render pass." }, { "code": null, "e": 28613, "s": 28595, "text": "ListView Methods:" }, { "code": null, "e": 28691, "s": 28613, "text": "getMetrics(): Function used to export data, primarily for analytics purposes." }, { "code": null, "e": 28750, "s": 28691, "text": "scrollTo(): Function used to scroll to a given x-y offset." }, { "code": null, "e": 28956, "s": 28750, "text": "scrollToEnd(): Function used to scroll the list. In the case of a vertical ListView, it is used to scroll to the bottom of the list. In the case of a horizontal ListView, it is used to scroll to the right." }, { "code": null, "e": 29034, "s": 28956, "text": "flashScrollIndicators(): Function used to briefly show the scroll indicators." }, { "code": null, "e": 29075, "s": 29034, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 29172, "s": 29075, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 29246, "s": 29172, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 29270, "s": 29246, "text": "npm install -g expo-cli" }, { "code": null, "e": 29348, "s": 29270, "text": "Step 2: Now create a project by the following command.expo init listview-demo" }, { "code": null, "e": 29403, "s": 29348, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 29427, "s": 29403, "text": "expo init listview-demo" }, { "code": null, "e": 29502, "s": 29427, "text": "Step 3: Now go into your project folder i.e. listview-democd listview-demo" }, { "code": null, "e": 29561, "s": 29502, "text": "Step 3: Now go into your project folder i.e. listview-demo" }, { "code": null, "e": 29578, "s": 29561, "text": "cd listview-demo" }, { "code": null, "e": 29621, "s": 29578, "text": "Project Structure: It will look like this." }, { "code": null, "e": 29662, "s": 29621, "text": "Example: Basic Use of ListView Component" }, { "code": null, "e": 29669, "s": 29662, "text": "App.js" }, { "code": "import React, { Component } from \"react\";import { Text, View, StyleSheet, ListView } from \"react-native\";import { Icon } from \"react-native-elements\"; const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2}); class App extends Component { state = { dataSource: ds.cloneWithRows([ \"Data Structures\", \"STL\", \"C++\", \"Java\", \"Python\", \"ReactJS\", \"Angular\", \"NodeJs\", \"PHP\", \"MongoDb\", \"MySql\", \"Android\", \"iOS\", \"Hadoop\", \"Ajax\", \"Ruby\", \"Rails\", \".Net\", \"Perl\", ]), }; render() { return ( <View style={styles.screen}> <ListView dataSource={this.state.dataSource} renderRow={(rowData) => ( <View style={styles.row}> <Text style={styles.rowText}>{rowData}</Text> <Icon name=\"ios-eye\" type=\"ionicon\" color=\"#C2185B\" /> </View> )} /> </View> ); }} // Screen stylesconst styles = StyleSheet.create({ screen: { marginTop: 30, }, row: { margin: 15, flexDirection: \"row\", justifyContent: \"space-between\", alignItems: \"center\", paddingHorizontal: 2, }, rowText: { fontSize: 18, },}); export default App;", "e": 30924, "s": 29669, "text": null }, { "code": null, "e": 30973, "s": 30924, "text": "Start the server by using the following command." }, { "code": null, "e": 30989, "s": 30973, "text": "npm run android" }, { "code": null, "e": 31158, "s": 30989, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 31381, "s": 31158, "text": "Note: It is important to note that ListView Component is now deprecated. Instead, newer components are used, such as FlatList or SectionList. To use the ListView Component, use the deprecated-react-native-listview package." }, { "code": null, "e": 31438, "s": 31381, "text": "import ListView from \"deprecated-react-native-listview\";" }, { "code": null, "e": 31492, "s": 31438, "text": "Reference: https://reactnative.dev/docs/0.62/listview" }, { "code": null, "e": 31499, "s": 31492, "text": "Picked" }, { "code": null, "e": 31512, "s": 31499, "text": "React-Native" }, { "code": null, "e": 31535, "s": 31512, "text": "React-Native Component" }, { "code": null, "e": 31552, "s": 31535, "text": "Web Technologies" }, { "code": null, "e": 31650, "s": 31552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31690, "s": 31650, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31735, "s": 31690, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31778, "s": 31735, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31839, "s": 31778, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31911, "s": 31839, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31966, "s": 31911, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32011, "s": 31966, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 32052, "s": 32011, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 32076, "s": 32052, "text": "REST API (Introduction)" } ]
Hello World in C# - GeeksforGeeks
17 Dec, 2019 The Hello World! program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the following: A Namespace Declaration Class Declaration & Definition Class Members(like variables, methods etc.) Main Method Statements or Expressions Example: // C# program to print Hello World!using System; // namespace declarationnamespace HelloWorldApp { // Class declaration class Geeks { // Main Method static void Main(string[] args) { // statement // printing Hello World! Console.WriteLine("Hello World!"); // To prevents the screen from // running and closing quickly Console.ReadKey(); } }} Hello World! Explanation: using System: System is a namespace which contains the commonly used types. It is specified with a using System directive. namespace HelloWorldApp: Here namespace is the keyword which is used to define the namespace. HelloWorldApp is the user-defined name given to namespace. For more details, you can refer to C# | Namespaces class Geeks: Here class is the keyword which is used for the declaration of classes. Geeks is the user-defined name of the class. static void Main(string[] args): Here static keyword tells us that this method is accessible without instantiating the class. void keyword tells that this method will not return anything. Main() method is the entry point of our application. In our program, Main() method specifies its behavior with the statement Console.WriteLine(“Hello World!”);. Console.WriteLine(): Here WriteLine() is a method of the Console class defined in the System namespace. Console.ReadKey(): This is for the VS.NET Users. This makes the program wait for a key press and prevents the screen from running and closing quickly. Generally, There are 3 ways to compile and execute a C# program as follows: To use an online C# compiler: You can use various online IDE. which can be used to run C# programs without installing. Using Visual Studio IDE: Microsoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from the Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version. To learn how to run a program in Visual Studio you can refer to this. Using Command-Line: You can also use command-line options to run a C# program. Below steps demonstrate how to run a C# program on Command line in Windows Operating System:First, open a text editor like Notepad or Notepad++.Write the code in the text editor and save the file with .cs extension.Open the cmd(Command Prompt) and run the command csc to check for the compiler version. It specifies whether you have installed a valid compiler or not. You can avoid this step if you confirmed that compiler is installed.To compile the code type csc filename.cs on cmd. If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as hello.cs. So you will write csc hello.cs on cmd. This will create a hello.exe.Now you have to ways to execute the hello.exe. First, you have to simply type the filename i.e hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output. First, open a text editor like Notepad or Notepad++. Write the code in the text editor and save the file with .cs extension. Open the cmd(Command Prompt) and run the command csc to check for the compiler version. It specifies whether you have installed a valid compiler or not. You can avoid this step if you confirmed that compiler is installed. To compile the code type csc filename.cs on cmd. If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as hello.cs. So you will write csc hello.cs on cmd. This will create a hello.exe. Now you have to ways to execute the hello.exe. First, you have to simply type the filename i.e hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output. CSharp-Basics C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# | Delegates C# | Arrays of Strings C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 26549, "s": 26521, "text": "\n17 Dec, 2019" }, { "code": null, "e": 26765, "s": 26549, "text": "The Hello World! program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the following:" }, { "code": null, "e": 26789, "s": 26765, "text": "A Namespace Declaration" }, { "code": null, "e": 26820, "s": 26789, "text": "Class Declaration & Definition" }, { "code": null, "e": 26864, "s": 26820, "text": "Class Members(like variables, methods etc.)" }, { "code": null, "e": 26876, "s": 26864, "text": "Main Method" }, { "code": null, "e": 26902, "s": 26876, "text": "Statements or Expressions" }, { "code": null, "e": 26911, "s": 26902, "text": "Example:" }, { "code": "// C# program to print Hello World!using System; // namespace declarationnamespace HelloWorldApp { // Class declaration class Geeks { // Main Method static void Main(string[] args) { // statement // printing Hello World! Console.WriteLine(\"Hello World!\"); // To prevents the screen from // running and closing quickly Console.ReadKey(); } }}", "e": 27395, "s": 26911, "text": null }, { "code": null, "e": 27409, "s": 27395, "text": "Hello World!\n" }, { "code": null, "e": 27422, "s": 27409, "text": "Explanation:" }, { "code": null, "e": 27545, "s": 27422, "text": "using System: System is a namespace which contains the commonly used types. It is specified with a using System directive." }, { "code": null, "e": 27749, "s": 27545, "text": "namespace HelloWorldApp: Here namespace is the keyword which is used to define the namespace. HelloWorldApp is the user-defined name given to namespace. For more details, you can refer to C# | Namespaces" }, { "code": null, "e": 27879, "s": 27749, "text": "class Geeks: Here class is the keyword which is used for the declaration of classes. Geeks is the user-defined name of the class." }, { "code": null, "e": 28228, "s": 27879, "text": "static void Main(string[] args): Here static keyword tells us that this method is accessible without instantiating the class. void keyword tells that this method will not return anything. Main() method is the entry point of our application. In our program, Main() method specifies its behavior with the statement Console.WriteLine(“Hello World!”);." }, { "code": null, "e": 28332, "s": 28228, "text": "Console.WriteLine(): Here WriteLine() is a method of the Console class defined in the System namespace." }, { "code": null, "e": 28483, "s": 28332, "text": "Console.ReadKey(): This is for the VS.NET Users. This makes the program wait for a key press and prevents the screen from running and closing quickly." }, { "code": null, "e": 28559, "s": 28483, "text": "Generally, There are 3 ways to compile and execute a C# program as follows:" }, { "code": null, "e": 28678, "s": 28559, "text": "To use an online C# compiler: You can use various online IDE. which can be used to run C# programs without installing." }, { "code": null, "e": 29160, "s": 28678, "text": "Using Visual Studio IDE: Microsoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from the Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version. To learn how to run a program in Visual Studio you can refer to this." }, { "code": null, "e": 30277, "s": 29160, "text": "Using Command-Line: You can also use command-line options to run a C# program. Below steps demonstrate how to run a C# program on Command line in Windows Operating System:First, open a text editor like Notepad or Notepad++.Write the code in the text editor and save the file with .cs extension.Open the cmd(Command Prompt) and run the command csc to check for the compiler version. It specifies whether you have installed a valid compiler or not. You can avoid this step if you confirmed that compiler is installed.To compile the code type csc filename.cs on cmd. If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as hello.cs. So you will write csc hello.cs on cmd. This will create a hello.exe.Now you have to ways to execute the hello.exe. First, you have to simply type the filename i.e hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output." }, { "code": null, "e": 30330, "s": 30277, "text": "First, open a text editor like Notepad or Notepad++." }, { "code": null, "e": 30402, "s": 30330, "text": "Write the code in the text editor and save the file with .cs extension." }, { "code": null, "e": 30624, "s": 30402, "text": "Open the cmd(Command Prompt) and run the command csc to check for the compiler version. It specifies whether you have installed a valid compiler or not. You can avoid this step if you confirmed that compiler is installed." }, { "code": null, "e": 30917, "s": 30624, "text": "To compile the code type csc filename.cs on cmd. If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as hello.cs. So you will write csc hello.cs on cmd. This will create a hello.exe." }, { "code": null, "e": 31227, "s": 30917, "text": "Now you have to ways to execute the hello.exe. First, you have to simply type the filename i.e hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output." }, { "code": null, "e": 31241, "s": 31227, "text": "CSharp-Basics" }, { "code": null, "e": 31244, "s": 31241, "text": "C#" }, { "code": null, "e": 31342, "s": 31244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31396, "s": 31342, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 31438, "s": 31396, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 31500, "s": 31438, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 31528, "s": 31500, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 31543, "s": 31528, "text": "C# | Delegates" }, { "code": null, "e": 31566, "s": 31543, "text": "C# | Arrays of Strings" }, { "code": null, "e": 31588, "s": 31566, "text": "C# | Abstract Classes" }, { "code": null, "e": 31634, "s": 31588, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 31657, "s": 31634, "text": "Extension Method in C#" } ]
Python - Difference Between json.load() and json.loads() - GeeksforGeeks
26 Nov, 2020 JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load and json.loads() methods. Both methods are used for reading and writing from the Unicode string with file. json.load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object. Syntax: json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Parameters: fp: File pointer to read text. object_hook: It is an optional parameter that will be called with the result of any object literal decoded. parse_float: It is an optional parameter that will be called with the string of every JSON float to be decoded. parse_int: It is an optional parameter that will be called with the string of every JSON int to be decoded. object_pairs_hook: It is an optional parameter that will be called with the result of any object literal decoded with an ordered list of pairs. Example: First creating the json file: Python3 import json data = { "name": "Satyam kumar", "place": "patna", "skills": [ "Raspberry pi", "Machine Learning", "Web Development" ], "email": "[email protected]", "projects": [ "Python Data Mining", "Python Data Science" ]}with open( "data_file.json" , "w" ) as write: json.dump( data , write ) Output: data_file.json After, creating json file, let’s use json.load(): Python3 with open("data_file.json", "r") as read_content: print(json.load(read_content)) Output: {‘name’: ‘Satyam kumar’, ‘place’: ‘patna’, ‘skills’: [‘Raspberry pi’, ‘Machine Learning’, ‘Web Development’],’email’: ‘[email protected]’, ‘projects’: [‘Python Data Mining’, ‘Python Data Science’]} json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary. Syntax: json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Parameters: s: Deserialize str (s) instance containing a JSON document to a Python object using this conversion table. object_hook: It is an optional parameter that will be called with the result of any object literal decoded. parse_float: It is an optional parameter that will be called with the string of every JSON float to be decoded. parse_int: It is an optional parameter that will be called with the string of every JSON int to be decoded. object_pairs_hook: It is an optional parameter that will be called with the result of any object literal decoded with an ordered list of pairs. Example: Python3 import json # JSON string: # Multi-line string data = """{ "Name": "Jennifer Smith", "Contact Number": 7867567898, "Email": "[email protected]", "Hobbies":["Reading", "Sketching", "Horse Riding"] }""" # parse data: res = json.loads( data ) # the result is a Python dictionary: print( res ) Output: {‘Name’: ‘Jennifer Smith’, ‘Contact Number’: 7867567898, ‘Email’: ‘[email protected]’,‘Hobbies’: [‘Reading’, ‘Sketching’, ‘Horse Riding’]} Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25994, "s": 25537, "text": "JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load and json.loads() methods. Both methods are used for reading and writing from the Unicode string with file. " }, { "code": null, "e": 26205, "s": 25994, "text": "json.load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object." }, { "code": null, "e": 26340, "s": 26205, "text": "Syntax: json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)" }, { "code": null, "e": 26352, "s": 26340, "text": "Parameters:" }, { "code": null, "e": 26383, "s": 26352, "text": "fp: File pointer to read text." }, { "code": null, "e": 26491, "s": 26383, "text": "object_hook: It is an optional parameter that will be called with the result of any object literal decoded." }, { "code": null, "e": 26604, "s": 26491, "text": "parse_float: It is an optional parameter that will be called with the string of every JSON float to be decoded. " }, { "code": null, "e": 26712, "s": 26604, "text": "parse_int: It is an optional parameter that will be called with the string of every JSON int to be decoded." }, { "code": null, "e": 26856, "s": 26712, "text": "object_pairs_hook: It is an optional parameter that will be called with the result of any object literal decoded with an ordered list of pairs." }, { "code": null, "e": 26865, "s": 26856, "text": "Example:" }, { "code": null, "e": 26895, "s": 26865, "text": "First creating the json file:" }, { "code": null, "e": 26903, "s": 26895, "text": "Python3" }, { "code": "import json data = { \"name\": \"Satyam kumar\", \"place\": \"patna\", \"skills\": [ \"Raspberry pi\", \"Machine Learning\", \"Web Development\" ], \"email\": \"[email protected]\", \"projects\": [ \"Python Data Mining\", \"Python Data Science\" ]}with open( \"data_file.json\" , \"w\" ) as write: json.dump( data , write )", "e": 27253, "s": 26903, "text": null }, { "code": null, "e": 27261, "s": 27253, "text": "Output:" }, { "code": null, "e": 27276, "s": 27261, "text": "data_file.json" }, { "code": null, "e": 27326, "s": 27276, "text": "After, creating json file, let’s use json.load():" }, { "code": null, "e": 27334, "s": 27326, "text": "Python3" }, { "code": "with open(\"data_file.json\", \"r\") as read_content: print(json.load(read_content))", "e": 27418, "s": 27334, "text": null }, { "code": null, "e": 27426, "s": 27418, "text": "Output:" }, { "code": null, "e": 27620, "s": 27426, "text": "{‘name’: ‘Satyam kumar’, ‘place’: ‘patna’, ‘skills’: [‘Raspberry pi’, ‘Machine Learning’, ‘Web Development’],’email’: ‘[email protected]’, ‘projects’: [‘Python Data Mining’, ‘Python Data Science’]}" }, { "code": null, "e": 27845, "s": 27620, "text": "json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary." }, { "code": null, "e": 27995, "s": 27845, "text": "Syntax: json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)" }, { "code": null, "e": 28007, "s": 27995, "text": "Parameters:" }, { "code": null, "e": 28114, "s": 28007, "text": "s: Deserialize str (s) instance containing a JSON document to a Python object using this conversion table." }, { "code": null, "e": 28222, "s": 28114, "text": "object_hook: It is an optional parameter that will be called with the result of any object literal decoded." }, { "code": null, "e": 28335, "s": 28222, "text": "parse_float: It is an optional parameter that will be called with the string of every JSON float to be decoded. " }, { "code": null, "e": 28443, "s": 28335, "text": "parse_int: It is an optional parameter that will be called with the string of every JSON int to be decoded." }, { "code": null, "e": 28587, "s": 28443, "text": "object_pairs_hook: It is an optional parameter that will be called with the result of any object literal decoded with an ordered list of pairs." }, { "code": null, "e": 28596, "s": 28587, "text": "Example:" }, { "code": null, "e": 28604, "s": 28596, "text": "Python3" }, { "code": "import json # JSON string: # Multi-line string data = \"\"\"{ \"Name\": \"Jennifer Smith\", \"Contact Number\": 7867567898, \"Email\": \"[email protected]\", \"Hobbies\":[\"Reading\", \"Sketching\", \"Horse Riding\"] }\"\"\" # parse data: res = json.loads( data ) # the result is a Python dictionary: print( res )", "e": 28924, "s": 28604, "text": null }, { "code": null, "e": 28932, "s": 28924, "text": "Output:" }, { "code": null, "e": 29070, "s": 28932, "text": "{‘Name’: ‘Jennifer Smith’, ‘Contact Number’: 7867567898, ‘Email’: ‘[email protected]’,‘Hobbies’: [‘Reading’, ‘Sketching’, ‘Horse Riding’]}" }, { "code": null, "e": 29082, "s": 29070, "text": "Python-json" }, { "code": null, "e": 29089, "s": 29082, "text": "Python" }, { "code": null, "e": 29187, "s": 29089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29219, "s": 29187, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29261, "s": 29219, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29303, "s": 29261, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29330, "s": 29303, "text": "Python Classes and Objects" }, { "code": null, "e": 29386, "s": 29330, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29408, "s": 29386, "text": "Defaultdict in Python" }, { "code": null, "e": 29447, "s": 29408, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29478, "s": 29447, "text": "Python | os.path.join() method" }, { "code": null, "e": 29507, "s": 29478, "text": "Create a directory in Python" } ]
Maximize number of groups formed with size not smaller than its largest element - GeeksforGeeks
22 Nov, 2021 Given an array arr[] of N positive integers(1 ≤ arr[i] ≤ N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. Examples: Input: arr = {2, 3, 1, 2, 2} Output: 2 Explanation: In the first group we can take {1, 2} In the second group we can take {2, 2, 3} Therefore, the maximum 2 groups can be possible. Input: arr = {1, 1, 1} Output: 3 Approach: Firstly store the number of occurrences of each element in an array. Now, Make groups of similar elements. For example: if there are three 1s in the array then make three groups for each 1. Then store the remaining elements and start grouping from the lowest element. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function that prints the number// of maximum groupsvoid makeGroups(int a[], int n){ vector<int> v(n + 1, 0); // Store the number of // occurrence of elements for (int i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (int i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } int i = 1; int total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups cout << no_of_groups << "\n";} // Driver Codeint main(){ int arr[] = { 2, 3, 1, 2, 2 }; int size = sizeof(arr) / sizeof(arr[0]); makeGroups(arr, size); return 0;} // Java implementation of above approachimport java.util.*;class GFG{ // Function that prints the number// of maximum groupsstatic void makeGroups(int a[], int n){ int []v = new int[n + 1]; // Store the number of // occurrence of elements for (int i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (int i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } int i = 1; int total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups System.out.print(no_of_groups + "\n");} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 3, 1, 2, 2 }; int size = arr.length; makeGroups(arr, size);}} // This code is contributed by sapnasingh4991 # python3 implementation of above approach# Function that prints the number# of maximum groupsdef makeGroups(a, n): v = [0] * (n + 1) # Store the number of # occurrence of elements for i in range (n): v[a[i]] += 1 no_of_groups = 0 # Make all groups of similar # elements and store the # left numbers for i in range (1, n + 1): no_of_groups += v[i] // i v[i] = v[i] % i i = 1 total = 0 for i in range ( 1, n + 1): # Condition for finding first # leftover element if (v[i] != 0): total = v[i] break i += 1 while (i <= n): # Condition for current # leftover element if (v[i] != 0): total += v[i] # Condition if group size # is equal to or more than # current element if (total >= i): rem = total - i no_of_groups += 1 total = rem i += 1 # Printing maximum # number of groups print (no_of_groups) # Driver Codeif __name__ == "__main__": arr = [2, 3, 1, 2, 2] size = len(arr) makeGroups(arr, size) # This code is contributed by Chitranayal // C# implementation of above approachusing System;class GFG{ // Function that prints the number// of maximum groupsstatic void makeGroups(int []a, int n){ int []v = new int[n + 1]; int i = 0; // Store the number of // occurrence of elements for(i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for(i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } i = 1; int total = 0; for(i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups Console.Write(no_of_groups + "\n");} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 3, 1, 2, 2 }; int size = arr.Length; makeGroups(arr, size);}} // This code is contributed by sapnasingh4991 <script> // Javascript implementation of above approach // Function that prints the number// of maximum groupsfunction makeGroups(a, n){ let v = Array.from({length: n+1}, (_, i) => 0); // Store the number of // occurrence of elements for (let i = 0; i < n; i++) { v[a[i]]++; } let no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (let i = 1; i <= n; i++) { no_of_groups += Math.floor(v[i] / i); v[i] = v[i] % i; } let i = 1; let total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { let rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups document.write(no_of_groups + "\n");} // Driver Code let arr = [ 2, 3, 1, 2, 2 ]; let size = arr.length; makeGroups(arr, size); </script> 2 Time Complexity: O(N) sapnasingh4991 ukasp sanjoy_62 arorakashish0911 array-rearrange Arrays Mathematical Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26141, "s": 26113, "text": "\n22 Nov, 2021" }, { "code": null, "e": 26454, "s": 26141, "text": "Given an array arr[] of N positive integers(1 ≤ arr[i] ≤ N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. " }, { "code": null, "e": 26466, "s": 26454, "text": "Examples: " }, { "code": null, "e": 26647, "s": 26466, "text": "Input: arr = {2, 3, 1, 2, 2} Output: 2 Explanation: In the first group we can take {1, 2} In the second group we can take {2, 2, 3} Therefore, the maximum 2 groups can be possible." }, { "code": null, "e": 26681, "s": 26647, "text": "Input: arr = {1, 1, 1} Output: 3 " }, { "code": null, "e": 26692, "s": 26681, "text": "Approach: " }, { "code": null, "e": 26761, "s": 26692, "text": "Firstly store the number of occurrences of each element in an array." }, { "code": null, "e": 26882, "s": 26761, "text": "Now, Make groups of similar elements. For example: if there are three 1s in the array then make three groups for each 1." }, { "code": null, "e": 26960, "s": 26882, "text": "Then store the remaining elements and start grouping from the lowest element." }, { "code": null, "e": 27012, "s": 26960, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 27016, "s": 27012, "text": "C++" }, { "code": null, "e": 27021, "s": 27016, "text": "Java" }, { "code": null, "e": 27029, "s": 27021, "text": "Python3" }, { "code": null, "e": 27032, "s": 27029, "text": "C#" }, { "code": null, "e": 27043, "s": 27032, "text": "Javascript" }, { "code": "// C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function that prints the number// of maximum groupsvoid makeGroups(int a[], int n){ vector<int> v(n + 1, 0); // Store the number of // occurrence of elements for (int i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (int i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } int i = 1; int total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups cout << no_of_groups << \"\\n\";} // Driver Codeint main(){ int arr[] = { 2, 3, 1, 2, 2 }; int size = sizeof(arr) / sizeof(arr[0]); makeGroups(arr, size); return 0;}", "e": 28408, "s": 27043, "text": null }, { "code": "// Java implementation of above approachimport java.util.*;class GFG{ // Function that prints the number// of maximum groupsstatic void makeGroups(int a[], int n){ int []v = new int[n + 1]; // Store the number of // occurrence of elements for (int i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (int i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } int i = 1; int total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups System.out.print(no_of_groups + \"\\n\");} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 3, 1, 2, 2 }; int size = arr.length; makeGroups(arr, size);}} // This code is contributed by sapnasingh4991", "e": 29855, "s": 28408, "text": null }, { "code": "# python3 implementation of above approach# Function that prints the number# of maximum groupsdef makeGroups(a, n): v = [0] * (n + 1) # Store the number of # occurrence of elements for i in range (n): v[a[i]] += 1 no_of_groups = 0 # Make all groups of similar # elements and store the # left numbers for i in range (1, n + 1): no_of_groups += v[i] // i v[i] = v[i] % i i = 1 total = 0 for i in range ( 1, n + 1): # Condition for finding first # leftover element if (v[i] != 0): total = v[i] break i += 1 while (i <= n): # Condition for current # leftover element if (v[i] != 0): total += v[i] # Condition if group size # is equal to or more than # current element if (total >= i): rem = total - i no_of_groups += 1 total = rem i += 1 # Printing maximum # number of groups print (no_of_groups) # Driver Codeif __name__ == \"__main__\": arr = [2, 3, 1, 2, 2] size = len(arr) makeGroups(arr, size) # This code is contributed by Chitranayal", "e": 31079, "s": 29855, "text": null }, { "code": "// C# implementation of above approachusing System;class GFG{ // Function that prints the number// of maximum groupsstatic void makeGroups(int []a, int n){ int []v = new int[n + 1]; int i = 0; // Store the number of // occurrence of elements for(i = 0; i < n; i++) { v[a[i]]++; } int no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for(i = 1; i <= n; i++) { no_of_groups += v[i] / i; v[i] = v[i] % i; } i = 1; int total = 0; for(i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { int rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups Console.Write(no_of_groups + \"\\n\");} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 3, 1, 2, 2 }; int size = arr.Length; makeGroups(arr, size);}} // This code is contributed by sapnasingh4991", "e": 32522, "s": 31079, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function that prints the number// of maximum groupsfunction makeGroups(a, n){ let v = Array.from({length: n+1}, (_, i) => 0); // Store the number of // occurrence of elements for (let i = 0; i < n; i++) { v[a[i]]++; } let no_of_groups = 0; // Make all groups of similar // elements and store the // left numbers for (let i = 1; i <= n; i++) { no_of_groups += Math.floor(v[i] / i); v[i] = v[i] % i; } let i = 1; let total = 0; for (i = 1; i <= n; i++) { // Condition for finding first // leftover element if (v[i] != 0) { total = v[i]; break; } } i++; while (i <= n) { // Condition for current // leftover element if (v[i] != 0) { total += v[i]; // Condition if group size // is equal to or more than // current element if (total >= i) { let rem = total - i; no_of_groups++; total = rem; } } i++; } // Printing maximum // number of groups document.write(no_of_groups + \"\\n\");} // Driver Code let arr = [ 2, 3, 1, 2, 2 ]; let size = arr.length; makeGroups(arr, size); </script>", "e": 33922, "s": 32522, "text": null }, { "code": null, "e": 33924, "s": 33922, "text": "2" }, { "code": null, "e": 33949, "s": 33926, "text": "Time Complexity: O(N) " }, { "code": null, "e": 33964, "s": 33949, "text": "sapnasingh4991" }, { "code": null, "e": 33970, "s": 33964, "text": "ukasp" }, { "code": null, "e": 33980, "s": 33970, "text": "sanjoy_62" }, { "code": null, "e": 33997, "s": 33980, "text": "arorakashish0911" }, { "code": null, "e": 34013, "s": 33997, "text": "array-rearrange" }, { "code": null, "e": 34020, "s": 34013, "text": "Arrays" }, { "code": null, "e": 34033, "s": 34020, "text": "Mathematical" }, { "code": null, "e": 34043, "s": 34033, "text": "Searching" }, { "code": null, "e": 34050, "s": 34043, "text": "Arrays" }, { "code": null, "e": 34060, "s": 34050, "text": "Searching" }, { "code": null, "e": 34073, "s": 34060, "text": "Mathematical" }, { "code": null, "e": 34171, "s": 34073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34239, "s": 34171, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34262, "s": 34239, "text": "Introduction to Arrays" }, { "code": null, "e": 34294, "s": 34262, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34308, "s": 34294, "text": "Linear Search" }, { "code": null, "e": 34329, "s": 34308, "text": "Linked List vs Array" }, { "code": null, "e": 34389, "s": 34329, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34404, "s": 34389, "text": "C++ Data Types" }, { "code": null, "e": 34447, "s": 34404, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34471, "s": 34447, "text": "Merge two sorted arrays" } ]
Deadlock Prevention And Avoidance - GeeksforGeeks
21 Sep, 2021 Deadlock Characteristics As discussed in the previous post, deadlock has following characteristics. Mutual ExclusionHold and WaitNo preemptionCircular wait Mutual Exclusion Hold and Wait No preemption Circular wait Deadlock Prevention We can prevent Deadlock by eliminating any of the above four conditions. Eliminate Mutual Exclusion It is not possible to dis-satisfy the mutual exclusion because some resources, such as the tape drive and printer, are inherently non-shareable. Eliminate Hold and wait Allocate all required resources to the process before the start of its execution, this way hold and wait condition is eliminated but it will lead to low device utilization. for example, if a process requires printer at a later time and we have allocated printer before the start of its execution printer will remain blocked till it has completed its execution. The process will make a new request for resources after releasing the current set of resources. This solution may lead to starvation. Allocate all required resources to the process before the start of its execution, this way hold and wait condition is eliminated but it will lead to low device utilization. for example, if a process requires printer at a later time and we have allocated printer before the start of its execution printer will remain blocked till it has completed its execution. The process will make a new request for resources after releasing the current set of resources. This solution may lead to starvation. Eliminate No Preemption Preempt resources from the process when resources required by other high priority processes. Eliminate Circular Wait Each resource will be assigned with a numerical number. A process can request the resources increasing/decreasing. order of numbering. For Example, if P1 process is allocated R5 resources, now next time if P1 ask for R4, R3 lesser than R5 such request will not be granted, only request for resources more than R5 will be granted. Deadlock Avoidance Deadlock avoidance can be done with Banker’s Algorithm. Banker’s Algorithm Bankers’s Algorithm is resource allocation and deadlock avoidance algorithm which test all the request made by processes for resources, it checks for the safe state, if after granting request system remains in the safe state it allows the request and if there is no safe state it doesn’t allow the request made by the process. Inputs to Banker’s Algorithm: Max need of resources by each process. Currently, allocated resources by each process. Max free available resources in the system. Max need of resources by each process. Currently, allocated resources by each process. Max free available resources in the system. The request will only be granted under the below condition: If the request made by the process is less than equal to max need to that process. If the request made by the process is less than equal to the freely available resource in the system. If the request made by the process is less than equal to max need to that process. If the request made by the process is less than equal to the freely available resource in the system. Example: Total resources in system: A B C D 6 5 7 6 Available system resources are: A B C D 3 1 1 2 Processes (currently allocated resources): A B C D P1 1 2 2 1 P2 1 0 3 3 P3 1 2 1 0 Processes (maximum resources): A B C D P1 3 3 2 2 P2 1 2 3 4 P3 1 3 5 0 Need = maximum resources - currently allocated resources. Processes (need resources): A B C D P1 2 1 0 1 P2 0 2 0 1 P3 0 1 4 0 Note: Deadlock prevention is more strict than Deadlock Avoidance. VaibhavRai3 bhaluram18 Deadlocks Articles Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Questions Differences and Applications of List, Tuple, Set and Dictionary in Python Service-Oriented Architecture Const keyword in C++ Functional Dependency and Attribute Closure Cache Memory in Computer Organization LRU Cache Implementation 'crontab' in Linux with Examples Memory Management in Operating System Difference between Internal and External fragmentation
[ { "code": null, "e": 29429, "s": 29401, "text": "\n21 Sep, 2021" }, { "code": null, "e": 29531, "s": 29429, "text": "Deadlock Characteristics As discussed in the previous post, deadlock has following characteristics. " }, { "code": null, "e": 29587, "s": 29531, "text": "Mutual ExclusionHold and WaitNo preemptionCircular wait" }, { "code": null, "e": 29604, "s": 29587, "text": "Mutual Exclusion" }, { "code": null, "e": 29618, "s": 29604, "text": "Hold and Wait" }, { "code": null, "e": 29632, "s": 29618, "text": "No preemption" }, { "code": null, "e": 29646, "s": 29632, "text": "Circular wait" }, { "code": null, "e": 29741, "s": 29646, "text": "Deadlock Prevention We can prevent Deadlock by eliminating any of the above four conditions. " }, { "code": null, "e": 29914, "s": 29741, "text": "Eliminate Mutual Exclusion It is not possible to dis-satisfy the mutual exclusion because some resources, such as the tape drive and printer, are inherently non-shareable. " }, { "code": null, "e": 29939, "s": 29914, "text": "Eliminate Hold and wait " }, { "code": null, "e": 30435, "s": 29939, "text": "Allocate all required resources to the process before the start of its execution, this way hold and wait condition is eliminated but it will lead to low device utilization. for example, if a process requires printer at a later time and we have allocated printer before the start of its execution printer will remain blocked till it has completed its execution. The process will make a new request for resources after releasing the current set of resources. This solution may lead to starvation." }, { "code": null, "e": 30798, "s": 30435, "text": "Allocate all required resources to the process before the start of its execution, this way hold and wait condition is eliminated but it will lead to low device utilization. for example, if a process requires printer at a later time and we have allocated printer before the start of its execution printer will remain blocked till it has completed its execution. " }, { "code": null, "e": 30932, "s": 30798, "text": "The process will make a new request for resources after releasing the current set of resources. This solution may lead to starvation." }, { "code": null, "e": 31052, "s": 30934, "text": "Eliminate No Preemption Preempt resources from the process when resources required by other high priority processes. " }, { "code": null, "e": 31408, "s": 31052, "text": " Eliminate Circular Wait Each resource will be assigned with a numerical number. A process can request the resources increasing/decreasing. order of numbering. For Example, if P1 process is allocated R5 resources, now next time if P1 ask for R4, R3 lesser than R5 such request will not be granted, only request for resources more than R5 will be granted. " }, { "code": null, "e": 31485, "s": 31408, "text": " Deadlock Avoidance Deadlock avoidance can be done with Banker’s Algorithm. " }, { "code": null, "e": 31832, "s": 31485, "text": "Banker’s Algorithm Bankers’s Algorithm is resource allocation and deadlock avoidance algorithm which test all the request made by processes for resources, it checks for the safe state, if after granting request system remains in the safe state it allows the request and if there is no safe state it doesn’t allow the request made by the process. " }, { "code": null, "e": 31864, "s": 31832, "text": "Inputs to Banker’s Algorithm: " }, { "code": null, "e": 31995, "s": 31864, "text": "Max need of resources by each process. Currently, allocated resources by each process. Max free available resources in the system." }, { "code": null, "e": 32035, "s": 31995, "text": "Max need of resources by each process. " }, { "code": null, "e": 32084, "s": 32035, "text": "Currently, allocated resources by each process. " }, { "code": null, "e": 32128, "s": 32084, "text": "Max free available resources in the system." }, { "code": null, "e": 32189, "s": 32128, "text": "The request will only be granted under the below condition: " }, { "code": null, "e": 32374, "s": 32189, "text": "If the request made by the process is less than equal to max need to that process. If the request made by the process is less than equal to the freely available resource in the system." }, { "code": null, "e": 32458, "s": 32374, "text": "If the request made by the process is less than equal to max need to that process. " }, { "code": null, "e": 32560, "s": 32458, "text": "If the request made by the process is less than equal to the freely available resource in the system." }, { "code": null, "e": 32570, "s": 32560, "text": "Example: " }, { "code": null, "e": 32613, "s": 32570, "text": "Total resources in system:\nA B C D\n6 5 7 6" }, { "code": null, "e": 32663, "s": 32615, "text": "Available system resources are:\nA B C D\n3 1 1 2" }, { "code": null, "e": 32756, "s": 32665, "text": "Processes (currently allocated resources):\n A B C D\nP1 1 2 2 1\nP2 1 0 3 3\nP3 1 2 1 0" }, { "code": null, "e": 32837, "s": 32758, "text": "Processes (maximum resources):\n A B C D\nP1 3 3 2 2\nP2 1 2 3 4\nP3 1 3 5 0" }, { "code": null, "e": 32973, "s": 32839, "text": "Need = maximum resources - currently allocated resources.\nProcesses (need resources):\n A B C D\nP1 2 1 0 1\nP2 0 2 0 1\nP3 0 1 4 0" }, { "code": null, "e": 33040, "s": 32973, "text": "Note: Deadlock prevention is more strict than Deadlock Avoidance. " }, { "code": null, "e": 33052, "s": 33040, "text": "VaibhavRai3" }, { "code": null, "e": 33063, "s": 33052, "text": "bhaluram18" }, { "code": null, "e": 33073, "s": 33063, "text": "Deadlocks" }, { "code": null, "e": 33082, "s": 33073, "text": "Articles" }, { "code": null, "e": 33100, "s": 33082, "text": "Operating Systems" }, { "code": null, "e": 33118, "s": 33100, "text": "Operating Systems" }, { "code": null, "e": 33216, "s": 33118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33243, "s": 33216, "text": "Amazon Interview Questions" }, { "code": null, "e": 33317, "s": 33243, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 33347, "s": 33317, "text": "Service-Oriented Architecture" }, { "code": null, "e": 33368, "s": 33347, "text": "Const keyword in C++" }, { "code": null, "e": 33412, "s": 33368, "text": "Functional Dependency and Attribute Closure" }, { "code": null, "e": 33450, "s": 33412, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 33475, "s": 33450, "text": "LRU Cache Implementation" }, { "code": null, "e": 33508, "s": 33475, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 33546, "s": 33508, "text": "Memory Management in Operating System" } ]
Extract the HTML code of the given tag and its parent using BeautifulSoup - GeeksforGeeks
16 Mar, 2021 In this article, we will discuss how to extract the HTML code of the given tag and its parent using BeautifulSoup. First, we need to install all these modules on our computer. BeautifulSoup: Our primary module contains a method to access a webpage over HTTP. pip install bs4 lxml: Helper library to process webpages in python language. pip install lxml requests: Makes the process of sending HTTP requests flawless.the output of the function. pip install requests We import our beautifulsoup module and requests. We declared Header and added a user agent. This ensures that the target website we are going to web scrape doesn’t consider traffic from our program as spam and finally gets blocked by them. Python3 # importing the modulesfrom bs4 import BeautifulSoupimport requests # URL to the scrapedURL = "https://en.wikipedia.org/wiki/Machine_learning" # getting the contents of the website and parsing themwebpage = requests.get(URL)soup = BeautifulSoup(webpage.content, "lxml") Now to target the element about which you want to get the info right click it and click inspect element. Then from the inspect element window try to find an HTML attribute that is unique to others. Most of the time it’s the Id of the element. Here to extract the HTML of the title of the site, we can extract this easily using the id of the title. Python3 # getting the h1 with id as firstHeading and printing ittitle = soup.find("h1", attrs={"id": 'firstHeading'})print(title) Now extracting the content of the concerned tag, we can simply use the .get_text() method. The implementation would be as below: Python3 # getting the text/content inside the h1 tag we# parsed on the previous linecont = title.get_text()print(cont) Now to extract the HTML of the parent element of a concerning element, let’s take an example of a span having the ID “Machine_learning_approaches”. We need to extract it that displays the HTML in lists of lists form. Python3 # getting the HTML of the parent parent of # the h1 tag we parsed earlierparent = soup.find("span", attrs={"id": 'Machine_learning_approaches'}).parent()print(parent) Below is the complete program: Python3 # importing the modulesfrom bs4 import BeautifulSoup import requests # URL to the scrapedURL = "https://en.wikipedia.org/wiki/Machine_learning" # getting the contents of the website and parsing themwebpage = requests.get(URL) soup = BeautifulSoup(webpage.content, "lxml") # getting the h1 with id as firstHeading and printing ittitle = soup.find("h1", attrs={"id": 'firstHeading'})print(title) # getting the text/content inside the h1 tag we # parsed on the previous linecont = title.get_text()print(cont) # getting the HTML of the parent parent of # the h1 tag we parsed earlierparent = soup.find("span", attrs={"id": 'Machine_learning_approaches'}).parent()print(parent) Output: Picked Python BeautifulSoup Python bs4-Exercises Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25652, "s": 25537, "text": "In this article, we will discuss how to extract the HTML code of the given tag and its parent using BeautifulSoup." }, { "code": null, "e": 25713, "s": 25652, "text": "First, we need to install all these modules on our computer." }, { "code": null, "e": 25796, "s": 25713, "text": "BeautifulSoup: Our primary module contains a method to access a webpage over HTTP." }, { "code": null, "e": 25812, "s": 25796, "text": "pip install bs4" }, { "code": null, "e": 25873, "s": 25812, "text": "lxml: Helper library to process webpages in python language." }, { "code": null, "e": 25890, "s": 25873, "text": "pip install lxml" }, { "code": null, "e": 25980, "s": 25890, "text": "requests: Makes the process of sending HTTP requests flawless.the output of the function." }, { "code": null, "e": 26001, "s": 25980, "text": "pip install requests" }, { "code": null, "e": 26241, "s": 26001, "text": "We import our beautifulsoup module and requests. We declared Header and added a user agent. This ensures that the target website we are going to web scrape doesn’t consider traffic from our program as spam and finally gets blocked by them." }, { "code": null, "e": 26249, "s": 26241, "text": "Python3" }, { "code": "# importing the modulesfrom bs4 import BeautifulSoupimport requests # URL to the scrapedURL = \"https://en.wikipedia.org/wiki/Machine_learning\" # getting the contents of the website and parsing themwebpage = requests.get(URL)soup = BeautifulSoup(webpage.content, \"lxml\")", "e": 26521, "s": 26249, "text": null }, { "code": null, "e": 26764, "s": 26521, "text": "Now to target the element about which you want to get the info right click it and click inspect element. Then from the inspect element window try to find an HTML attribute that is unique to others. Most of the time it’s the Id of the element." }, { "code": null, "e": 26869, "s": 26764, "text": "Here to extract the HTML of the title of the site, we can extract this easily using the id of the title." }, { "code": null, "e": 26877, "s": 26869, "text": "Python3" }, { "code": "# getting the h1 with id as firstHeading and printing ittitle = soup.find(\"h1\", attrs={\"id\": 'firstHeading'})print(title)", "e": 26999, "s": 26877, "text": null }, { "code": null, "e": 27128, "s": 26999, "text": "Now extracting the content of the concerned tag, we can simply use the .get_text() method. The implementation would be as below:" }, { "code": null, "e": 27136, "s": 27128, "text": "Python3" }, { "code": "# getting the text/content inside the h1 tag we# parsed on the previous linecont = title.get_text()print(cont)", "e": 27247, "s": 27136, "text": null }, { "code": null, "e": 27395, "s": 27247, "text": "Now to extract the HTML of the parent element of a concerning element, let’s take an example of a span having the ID “Machine_learning_approaches”." }, { "code": null, "e": 27464, "s": 27395, "text": "We need to extract it that displays the HTML in lists of lists form." }, { "code": null, "e": 27472, "s": 27464, "text": "Python3" }, { "code": "# getting the HTML of the parent parent of # the h1 tag we parsed earlierparent = soup.find(\"span\", attrs={\"id\": 'Machine_learning_approaches'}).parent()print(parent)", "e": 27658, "s": 27472, "text": null }, { "code": null, "e": 27689, "s": 27658, "text": "Below is the complete program:" }, { "code": null, "e": 27697, "s": 27689, "text": "Python3" }, { "code": "# importing the modulesfrom bs4 import BeautifulSoup import requests # URL to the scrapedURL = \"https://en.wikipedia.org/wiki/Machine_learning\" # getting the contents of the website and parsing themwebpage = requests.get(URL) soup = BeautifulSoup(webpage.content, \"lxml\") # getting the h1 with id as firstHeading and printing ittitle = soup.find(\"h1\", attrs={\"id\": 'firstHeading'})print(title) # getting the text/content inside the h1 tag we # parsed on the previous linecont = title.get_text()print(cont) # getting the HTML of the parent parent of # the h1 tag we parsed earlierparent = soup.find(\"span\", attrs={\"id\": 'Machine_learning_approaches'}).parent()print(parent)", "e": 28395, "s": 27697, "text": null }, { "code": null, "e": 28403, "s": 28395, "text": "Output:" }, { "code": null, "e": 28410, "s": 28403, "text": "Picked" }, { "code": null, "e": 28431, "s": 28410, "text": "Python BeautifulSoup" }, { "code": null, "e": 28452, "s": 28431, "text": "Python bs4-Exercises" }, { "code": null, "e": 28459, "s": 28452, "text": "Python" }, { "code": null, "e": 28557, "s": 28459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28589, "s": 28557, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28631, "s": 28589, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28673, "s": 28631, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28729, "s": 28673, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28756, "s": 28729, "text": "Python Classes and Objects" }, { "code": null, "e": 28795, "s": 28756, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28826, "s": 28795, "text": "Python | os.path.join() method" }, { "code": null, "e": 28855, "s": 28826, "text": "Create a directory in Python" }, { "code": null, "e": 28877, "s": 28855, "text": "Defaultdict in Python" } ]
How to erase an element from a vector using erase() and reverse_iterator? - GeeksforGeeks
10 Oct, 2019 Given a vector, the task is to erase an element from this vector using erase() and reverse_iterator. Example: Input: vector = {1, 4, 7, 10, 13, 16, 19}, element = 16 Output: 1 4 7 10 13 19 Input: vector = {99, 89, 79, 69, 59}, element = 89 Output: 99 79 69 59 Approach: Get the vector and the element to be deleted Initialize a reverse iterator on the vector Erase the required element with the help of base() and erase()Reason for using base(): erase() returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense. So we can’t use the same process while using reverse iterators where we want to go in the reverse direction instead of forward. And also we can’t pass a reverse iterator as a parameter to erase() function or it will give a compilation error.A reverse_iterator is just an iterator adaptor that reverses the direction of a given iterator. All operations on the reverse_iterator really occur on that underlying iterator. We can obtain that iterator using the reverse_iterator::base() function. Infact the relationship between itr.base() and itr is:&*(reverse_iterator(itr))==&*(itr-1) Reason for using base(): erase() returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense. So we can’t use the same process while using reverse iterators where we want to go in the reverse direction instead of forward. And also we can’t pass a reverse iterator as a parameter to erase() function or it will give a compilation error. A reverse_iterator is just an iterator adaptor that reverses the direction of a given iterator. All operations on the reverse_iterator really occur on that underlying iterator. We can obtain that iterator using the reverse_iterator::base() function. Infact the relationship between itr.base() and itr is: &*(reverse_iterator(itr))==&*(itr-1) Below is the implementation of the above approach: // C++ program to delete an element of a vector// using erase() and reverse iterator. #include <iostream>#include <vector> using namespace std; // Function to delete element// 'num' from vector 'vec'vector<int> delete_ele(vector<int> vec, int num){ // initializing a reverse iterator vector<int>::reverse_iterator itr1; for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) { if (*itr1 == num) { // erasing element = 16 vec.erase((itr1 + 1).base()); } } return vec;} // Driver codeint main(){ vector<int> vec = { 1, 4, 7, 10, 13, 16, 19 }; // we want to delete element = 16 int num = 16; vector<int>::iterator itr1; cout << "Vector originally: \n"; for (itr1 = vec.begin(); itr1 < vec.end(); itr1++) { // printing the original elements of vector cout << *itr1 << " "; } cout << "\n\nElement to be deleted: " << num << "\n\n"; // reinitializing vector 'vec' // after deleting 'num' // from the vector // and keeping other remaining // elements as they are vec = delete_ele(vec, num); vector<int>::iterator itr2; cout << "Vector after deletion: \n"; for (itr2 = vec.begin(); itr2 < vec.end(); itr2++) { // printing the remaining elements of vector cout << *itr2 << " "; } return 0;}// This code is contributed by supratik_mitra Vector originally: 1 4 7 10 13 16 19 Element to be deleted: 16 Vector after deletion: 1 4 7 10 13 19 cpp-vector C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Iterators in C++ STL Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character Sorting a Map by value in C++ STL
[ { "code": null, "e": 24124, "s": 24096, "text": "\n10 Oct, 2019" }, { "code": null, "e": 24225, "s": 24124, "text": "Given a vector, the task is to erase an element from this vector using erase() and reverse_iterator." }, { "code": null, "e": 24234, "s": 24225, "text": "Example:" }, { "code": null, "e": 24386, "s": 24234, "text": "Input: vector = {1, 4, 7, 10, 13, 16, 19}, element = 16\nOutput: 1 4 7 10 13 19\n\nInput: vector = {99, 89, 79, 69, 59}, element = 89\nOutput: 99 79 69 59\n" }, { "code": null, "e": 24396, "s": 24386, "text": "Approach:" }, { "code": null, "e": 24441, "s": 24396, "text": "Get the vector and the element to be deleted" }, { "code": null, "e": 24485, "s": 24441, "text": "Initialize a reverse iterator on the vector" }, { "code": null, "e": 25288, "s": 24485, "text": "Erase the required element with the help of base() and erase()Reason for using base(): erase() returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense. So we can’t use the same process while using reverse iterators where we want to go in the reverse direction instead of forward. And also we can’t pass a reverse iterator as a parameter to erase() function or it will give a compilation error.A reverse_iterator is just an iterator adaptor that reverses the direction of a given iterator. All operations on the reverse_iterator really occur on that underlying iterator. We can obtain that iterator using the reverse_iterator::base() function. Infact the relationship between itr.base() and itr is:&*(reverse_iterator(itr))==&*(itr-1)" }, { "code": null, "e": 25689, "s": 25288, "text": "Reason for using base(): erase() returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense. So we can’t use the same process while using reverse iterators where we want to go in the reverse direction instead of forward. And also we can’t pass a reverse iterator as a parameter to erase() function or it will give a compilation error." }, { "code": null, "e": 25994, "s": 25689, "text": "A reverse_iterator is just an iterator adaptor that reverses the direction of a given iterator. All operations on the reverse_iterator really occur on that underlying iterator. We can obtain that iterator using the reverse_iterator::base() function. Infact the relationship between itr.base() and itr is:" }, { "code": null, "e": 26031, "s": 25994, "text": "&*(reverse_iterator(itr))==&*(itr-1)" }, { "code": null, "e": 26082, "s": 26031, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to delete an element of a vector// using erase() and reverse iterator. #include <iostream>#include <vector> using namespace std; // Function to delete element// 'num' from vector 'vec'vector<int> delete_ele(vector<int> vec, int num){ // initializing a reverse iterator vector<int>::reverse_iterator itr1; for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) { if (*itr1 == num) { // erasing element = 16 vec.erase((itr1 + 1).base()); } } return vec;} // Driver codeint main(){ vector<int> vec = { 1, 4, 7, 10, 13, 16, 19 }; // we want to delete element = 16 int num = 16; vector<int>::iterator itr1; cout << \"Vector originally: \\n\"; for (itr1 = vec.begin(); itr1 < vec.end(); itr1++) { // printing the original elements of vector cout << *itr1 << \" \"; } cout << \"\\n\\nElement to be deleted: \" << num << \"\\n\\n\"; // reinitializing vector 'vec' // after deleting 'num' // from the vector // and keeping other remaining // elements as they are vec = delete_ele(vec, num); vector<int>::iterator itr2; cout << \"Vector after deletion: \\n\"; for (itr2 = vec.begin(); itr2 < vec.end(); itr2++) { // printing the remaining elements of vector cout << *itr2 << \" \"; } return 0;}// This code is contributed by supratik_mitra", "e": 27483, "s": 26082, "text": null }, { "code": null, "e": 27590, "s": 27483, "text": "Vector originally: \n1 4 7 10 13 16 19 \n\nElement to be deleted: 16\n\nVector after deletion: \n1 4 7 10 13 19\n" }, { "code": null, "e": 27601, "s": 27590, "text": "cpp-vector" }, { "code": null, "e": 27605, "s": 27601, "text": "C++" }, { "code": null, "e": 27618, "s": 27605, "text": "C++ Programs" }, { "code": null, "e": 27622, "s": 27618, "text": "CPP" }, { "code": null, "e": 27720, "s": 27622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27748, "s": 27720, "text": "Operator Overloading in C++" }, { "code": null, "e": 27768, "s": 27748, "text": "Polymorphism in C++" }, { "code": null, "e": 27792, "s": 27768, "text": "Sorting a vector in C++" }, { "code": null, "e": 27825, "s": 27792, "text": "Friend class and function in C++" }, { "code": null, "e": 27846, "s": 27825, "text": "Iterators in C++ STL" }, { "code": null, "e": 27881, "s": 27846, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27940, "s": 27881, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27966, "s": 27940, "text": "C++ Program for QuickSort" }, { "code": null, "e": 28010, "s": 27966, "text": "Program to print ASCII Value of a character" } ]
IntStream sorted() in Java - GeeksforGeeks
06 Dec, 2018 IntStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream. Syntax : IntStream sorted() Where, IntStream is a sequence of primitive int-valued elements. This is the int primitive specialization of Stream. Exception : If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed. Return Value : IntStream sorted() method returns the new stream. Example 1 : Using IntStream sorted() to sort the numbers in given IntStream. // Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(10, 9, 8, 7, 6); // displaying the stream with sorted elements // using IntStream.sorted() function stream.sorted().forEach(System.out::println); }} 6 7 8 9 10 Example 2 : Using IntStream sorted() to sort the random numbers generated by IntStream generator(). // Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream by generating // random elements using IntStream.generate() IntStream stream = IntStream.generate(() -> (int)(Math.random() * 10000)) .limit(5); // displaying the stream with sorted elements // using IntStream.sorted() function stream.sorted().forEach(System.out::println); }} 501 611 7991 8467 9672 Java - util package Java-Functions java-intstream java-stream 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": "\n06 Dec, 2018" }, { "code": null, "e": 23992, "s": 23557, "text": "IntStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream." }, { "code": null, "e": 24001, "s": 23992, "text": "Syntax :" }, { "code": null, "e": 24140, "s": 24001, "text": "IntStream sorted()\n\nWhere, IntStream is a sequence of primitive int-valued \nelements. This is the int primitive specialization of Stream.\n" }, { "code": null, "e": 24289, "s": 24140, "text": "Exception : If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed." }, { "code": null, "e": 24354, "s": 24289, "text": "Return Value : IntStream sorted() method returns the new stream." }, { "code": null, "e": 24431, "s": 24354, "text": "Example 1 : Using IntStream sorted() to sort the numbers in given IntStream." }, { "code": "// Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(10, 9, 8, 7, 6); // displaying the stream with sorted elements // using IntStream.sorted() function stream.sorted().forEach(System.out::println); }}", "e": 24868, "s": 24431, "text": null }, { "code": null, "e": 24880, "s": 24868, "text": "6\n7\n8\n9\n10\n" }, { "code": null, "e": 24980, "s": 24880, "text": "Example 2 : Using IntStream sorted() to sort the random numbers generated by IntStream generator()." }, { "code": "// Java code to sort IntStream// using IntStream.sorted()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream by generating // random elements using IntStream.generate() IntStream stream = IntStream.generate(() -> (int)(Math.random() * 10000)) .limit(5); // displaying the stream with sorted elements // using IntStream.sorted() function stream.sorted().forEach(System.out::println); }}", "e": 25573, "s": 24980, "text": null }, { "code": null, "e": 25597, "s": 25573, "text": "501\n611\n7991\n8467\n9672\n" }, { "code": null, "e": 25617, "s": 25597, "text": "Java - util package" }, { "code": null, "e": 25632, "s": 25617, "text": "Java-Functions" }, { "code": null, "e": 25647, "s": 25632, "text": "java-intstream" }, { "code": null, "e": 25659, "s": 25647, "text": "java-stream" }, { "code": null, "e": 25664, "s": 25659, "text": "Java" }, { "code": null, "e": 25669, "s": 25664, "text": "Java" }, { "code": null, "e": 25767, "s": 25669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25776, "s": 25767, "text": "Comments" }, { "code": null, "e": 25789, "s": 25776, "text": "Old Comments" }, { "code": null, "e": 25819, "s": 25789, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25834, "s": 25819, "text": "Stream In Java" }, { "code": null, "e": 25855, "s": 25834, "text": "Constructors in Java" }, { "code": null, "e": 25901, "s": 25855, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25920, "s": 25901, "text": "Exceptions in Java" }, { "code": null, "e": 25937, "s": 25920, "text": "Generics in Java" }, { "code": null, "e": 25980, "s": 25937, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 25996, "s": 25980, "text": "Strings in Java" }, { "code": null, "e": 26045, "s": 25996, "text": "How to remove an element from ArrayList in Java?" } ]
How to know/change current directory in Python shell?
You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to. >>> import os >>> os.chdir('my_folder') To know the current working directory or pwd use the os module. >>> import os >>> print(os.getcwd()) /home/ayush/qna
[ { "code": null, "e": 1209, "s": 1062, "text": "You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to." }, { "code": null, "e": 1249, "s": 1209, "text": ">>> import os\n>>> os.chdir('my_folder')" }, { "code": null, "e": 1313, "s": 1249, "text": "To know the current working directory or pwd use the os module." }, { "code": null, "e": 1366, "s": 1313, "text": ">>> import os\n>>> print(os.getcwd())\n/home/ayush/qna" } ]
How to build a Gesture Controlled Web based Game using Tensorflow Object Detection Api | by Victor Dibia | Towards Data Science
Control the game paddle by waving your hand in front of your web cam. With the TensorFlow object detection api, we have seen examples where models are trained to detect custom objects in images (e.g. detecting hands, toys, racoons, mac n cheese). Naturally, an interesting next step is to explore how these models can be deployed in real world use cases — for example, interaction design. In this post, I cover a basic body-as-input interaction example where real time results from a hand tracking model (web cam stream as input) is mapped to the controls of a web-based game (Skyfall). The system demonstrates how the integration of a fairly accurate, light weight hand detection model can be used to track player hands and enable realtime body-as-input interactions. Want to try it out? Project code is available on Github. github.com Using parts of the human body as input has the benefit of being always available as the user is not required to carry any secondary device. Importantly, appropriating parts of the human body for gesture based interaction has been shown to improve user experience [2] and overall engagement [1]. While the idea of body as input is not entirely new, existing approaches which leverage computer vision, wearables and sensors (kinect, wii, [5]) etc sometimes suffer from accuracy challenges, are not always portable and can be challenging to integrate with 3rd party software. Advances in light-weight deep neural networks (DNNs), specifically models for object detection (see [3]) and key point extraction (see [4]) hold promise in addressing these issues and furthering the goal of always available (body as) input. These models allow us track the human body with good accuracy using 2D images and with the benefit of easy integration with a range of applications and devices (desktop, web, mobile). While tracking from 2D images does not give us much depth information, it is still surprisingly valuable in building interactions as shown in the Skyfall game example. Skyfall is a simple web based game created using planck.js — a 2D physics engine. The play mechanism for SkyFall is simple. 3 types of balls fall from the top of the screen in random order — white balls (worth 10 points), green balls (worth 10 points) and red balls (worth -10 points). Players earn points by moving a paddle to catch the good balls (white and green balls) and avoid bad balls (red balls). In the example below, the player can control the paddle by moving the mouse or by touch (drag) on a mobile device. HTML CSS JS Result Skip Results Iframe <div class="infordisplay "> <div class="toprow"> <img src="http://victordibia.com/skyfall/icon.png" class="icon floatleft " /> <div class="scorebox iblock "> <div class="scorevalue inscore"> 0 </div> <div class="scorelabel inscore"> pts </div> <div class="scoreadded inscore"> </div> </div> <div class="clear"></div> </div> <div class="settingsswitches"> <div class=" "> <div class="iblock floatleft"> <label class="switch"> <input type="checkbox" id="sound"> <span class="slider round"></span> </label> </div> <div class=" iblock soundofftext"> sound off</div> <div class="clear"></div> </div> </div> <div class="pausetext"> <div>Sound (s) </div> <div>Pause (space bar) </div> </div> <div id="updatenote" class="updatenote mt10"> loading model ..</div> <button id="trackbutton" class="bx--btn bx--btn--secondary mt10 trackbutton" type="button" disabled> Toggle Video Control .. </button> </div> <video class="videobox canvasbox" autoplay="autoplay" id="myvideo"></video> <canvas id="canvas" class="border canvasbox"></canvas> <div class="pauseoverlay"> <div class="overlaycenter"> Loading Handtrack.js Model .. </div> </div> body { font-family: Verdana, Geneva, Tahoma, sans-serif; } .infordisplay { position: absolute; margin: 2vw; top: 0.0vw; color: #fff; } .floatleft { float: left; } .clear { clear: both; } .dispblock { display: block; } .scorebox { height: 100%; border-bottom: 0.1vw solid #ff8800; padding: 1vw; font-size: 1.3vw; font-family: Verdana, Geneva, Tahoma, sans-serif; color: #fff; margin: 0vw 0vw 0vw 0vw; } .iblock { display: inline-block; } .inscore { display: inline-block; } .scorevalue { font-size: 2vw; font-weight: bold; } .scoreadded { position: absolute; font-size: 2vw; font-weight: bold; padding: 0vw 0vw 0vw 1vw } .scoreanimate { transform: scale(3); transition: all 2s; } .icon { font-family: Verdana, Geneva, Tahoma, sans-serif; width: 4.2vw; margin: 0vw; } .border { border: 2px solid #fff; } .settingsswitches { margin: 1vw 0vw 0vw 0vw; } .soundofftext { padding: 0.1vw 1vw 0vw 0.5vw; height: 100%; font-size: 1.2vw; } .pausetext { padding: 1vw 0vw 0vw 0vw; font-size: 1vw; } .pauseoverlay { position: fixed; /* Sit on top of the page content */ /* display: none; */ /* Hidden by default */ width: 100%; /* Full width (cover the whole page) */ height: 100%; /* Full height (cover the whole page) */ top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); /* Black background with opacity */ z-index: 2; /* Specify a stack order in case you're using a different order for other elements */ cursor: pointer; /* Add a pointer on hover */ } .overlaycenter { position: absolute; top: 50%; left: 50%; margin-top: -3vw; margin-left: -15vw; font-size: 0.1vw; color: #ff8800; opacity: 0; font-weight: bold; } /* ============= switches ================== */ /* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 4vw; height: 1.8vw; } /* Hide default HTML checkbox */ .switch input { display: none; } /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 1.2vw; width: 1.2vw; left: 0.4vw; bottom: 0.3vw; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked+.slider { background-color: #ff8800; } input:focus+.slider { box-shadow: 0 0 1px #ff8800; } input:checked+.slider:before { -webkit-transform: translateX(2vw); -ms-transform: translateX(2vw); transform: translateX(2vw); } /* Rounded sliders */ .slider.round { border-radius: 2vw; } .slider.round:before { border-radius: 50%; } .mt10 { margin-top: 10px; } .canvasbox { position: absolute; right: 10px; top: 10px; border-radius: 3px; margin-right: 10px; width: 215px; height: 162px; border-bottom: 3px solid #0063FF; box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2), 0 4px 10px 0 #00000030; } .updatenote{ padding: 12px; background: #ff8800; color: #fff; display: inline-block; /* font-weight: bold; */ } .trackbutton{ /* background: #ff8800; color: #fff; */ } const video = document.getElementById("myvideo"); const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); let trackButton = document.getElementById("trackbutton"); let updateNote = document.getElementById("updatenote"); let imgindex = 1 let isVideo = false; let model = null; let videoInterval = 100 // video.width = 500 // video.height = 400 $(".pauseoverlay").show() // $(".overlaycenter").text("Game Paused") $(".overlaycenter").animate({ opacity: 1, fontSize: "4vw" }, pauseGameAnimationDuration, function () {}); const modelParams = { flipHorizontal: true, // flip e.g for video maxNumBoxes: 1, // maximum number of boxes to detect iouThreshold: 0.5, // ioU threshold for non-max suppression scoreThreshold: 0.6, // confidence threshold for predictions. } function startVideo() { handTrack.startVideo(video).then(function (status) { console.log("video started", status); if (status) { updateNote.innerText = "Now tracking" isVideo = true runDetection() } else { updateNote.innerText = "Please enable video" } }); } function toggleVideo() { if (!isVideo) { updateNote.innerText = "Starting video" startVideo(); } else { updateNote.innerText = "Stopping video" handTrack.stopVideo(video) isVideo = false; updateNote.innerText = "Video stopped" } } trackButton.addEventListener("click", function () { toggleVideo(); }); function runDetection() { model.detect(video).then(predictions => { // console.log("Predictions: ", predictions); // get the middle x value of the bounding box and map to paddle location model.renderPredictions(predictions, canvas, context, video); if (predictions[0]) { let midval = predictions[0].bbox[0] + (predictions[0].bbox[2] / 2) gamex = document.body.clientWidth * (midval / video.width) updatePaddleControl(gamex) console.log('Predictions: ', gamex); } if (isVideo) { setTimeout(() => { runDetection(video) }, videoInterval); } }); } // Load the model. handTrack.load(modelParams).then(lmodel => { // detect objects in the image. model = lmodel updateNote.innerText = "Loaded Model!" trackButton.disabled = false $(".overlaycenter").animate({ opacity: 0, fontSize: "0vw" }, pauseGameAnimationDuration, function () { $(".pauseoverlay").hide() }); }); // =============================== var colors = ["#69d2e7", "#a7dbd8", "#e0e4cc", "#f38630", "#fa6900", "#fe4365", "#fc9d9a", "#f9cdad", "#c8c8a9", "#83af9b", "#ecd078", "#d95b43", "#c02942", "#542437", "#53777a", "#556270", "#4ecdc4", "#c7f464", "#ff6b6b", "#c44d58", "#774f38", "#e08e79", "#f1d4af", "#ece5ce", "#c5e0dc", "#e8ddcb", "#cdb380", "#036564", "#033649", "#031634", "#490a3d", "#bd1550", "#e97f02", "#f8ca00", "#8a9b0f", "#594f4f", "#547980", "#45ada8", "#9de0ad", "#e5fcc2", "#00a0b0", "#6a4a3c", "#cc333f", "#eb6841", "#edc951", "#e94e77", "#d68189", "#c6a49a", "#c6e5d9", "#f4ead5", "#3fb8af", "#7fc7af", "#dad8a7", "#ff9e9d", "#ff3d7f", "#d9ceb2", "#948c75", "#d5ded9", "#7a6a53", "#99b2b7", "#ffffff", "#cbe86b", "#f2e9e1", "#1c140d", "#cbe86b", "#efffcd", "#dce9be", "#555152", "#2e2633", "#99173c", "#343838", "#005f6b", "#008c9e", "#00b4cc", "#00dffc", "#413e4a", "#73626e", "#b38184", "#f0b49e", "#f7e4be", "#ff4e50", "#fc913a", "#f9d423", "#ede574", "#e1f5c4", "#99b898", "#fecea8", "#ff847c", "#e84a5f", "#2a363b", "#655643", "#80bca3", "#f6f7bd", "#e6ac27", "#bf4d28", "#00a8c6", "#40c0cb", "#f9f2e7", "#aee239", "#8fbe00", "#351330", "#424254", "#64908a", "#e8caa4", "#cc2a41", "#554236", "#f77825", "#d3ce3d", "#f1efa5", "#60b99a", "#ff9900", "#424242", "#e9e9e9", "#bcbcbc", "#3299bb", "#5d4157", "#838689", "#a8caba", "#cad7b2", "#ebe3aa", "#8c2318", "#5e8c6a", "#88a65e", "#bfb35a", "#f2c45a", "#fad089", "#ff9c5b", "#f5634a", "#ed303c", "#3b8183", "#ff4242", "#f4fad2", "#d4ee5e", "#e1edb9", "#f0f2eb", "#d1e751", "#ffffff", "#000000", "#4dbce9", "#26ade4", "#f8b195", "#f67280", "#c06c84", "#6c5b7b", "#355c7d", "#1b676b", "#519548", "#88c425", "#bef202", "#eafde6", "#bcbdac", "#cfbe27", "#f27435", "#f02475", "#3b2d38", "#5e412f", "#fcebb6", "#78c0a8", "#f07818", "#f0a830", "#452632", "#91204d", "#e4844a", "#e8bf56", "#e2f7ce", "#eee6ab", "#c5bc8e", "#696758", "#45484b", "#36393b", "#f0d8a8", "#3d1c00", "#86b8b1", "#f2d694", "#fa2a00", "#f04155", "#ff823a", "#f2f26f", "#fff7bd", "#95cfb7", "#2a044a", "#0b2e59", "#0d6759", "#7ab317", "#a0c55f", "#bbbb88", "#ccc68d", "#eedd99", "#eec290", "#eeaa88", "#b9d7d9", "#668284", "#2a2829", "#493736", "#7b3b3b", "#b3cc57", "#ecf081", "#ffbe40", "#ef746f", "#ab3e5b", "#a3a948", "#edb92e", "#f85931", "#ce1836", "#009989", "#67917a", "#170409", "#b8af03", "#ccbf82", "#e33258", "#e8d5b7", "#0e2430", "#fc3a51", "#f5b349", "#e8d5b9", "#aab3ab", "#c4cbb7", "#ebefc9", "#eee0b7", "#e8caaf", "#300030", "#480048", "#601848", "#c04848", "#f07241", "#ab526b", "#bca297", "#c5ceae", "#f0e2a4", "#f4ebc3", "#607848", "#789048", "#c0d860", "#f0f0d8", "#604848", "#a8e6ce", "#dcedc2", "#ffd3b5", "#ffaaa6", "#ff8c94", "#3e4147", "#fffedf", "#dfba69", "#5a2e2e", "#2a2c31", "#b6d8c0", "#c8d9bf", "#dadabd", "#ecdbbc", "#fedcba", "#fc354c", "#29221f", "#13747d", "#0abfbc", "#fcf7c5", "#1c2130", "#028f76", "#b3e099", "#ffeaad", "#d14334", "#edebe6", "#d6e1c7", "#94c7b6", "#403b33", "#d3643b", "#cc0c39", "#e6781e", "#c8cf02", "#f8fcc1", "#1693a7", "#dad6ca", "#1bb0ce", "#4f8699", "#6a5e72", "#563444", "#a7c5bd", "#e5ddcb", "#eb7b59", "#cf4647", "#524656", "#fdf1cc", "#c6d6b8", "#987f69", "#e3ad40", "#fcd036", "#5c323e", "#a82743", "#e15e32", "#c0d23e", "#e5f04c", "#230f2b", "#f21d41", "#ebebbc", "#bce3c5", "#82b3ae", "#b9d3b0", "#81bda4", "#b28774", "#f88f79", "#f6aa93", "#3a111c", "#574951", "#83988e", "#bcdea5", "#e6f9bc", "#5e3929", "#cd8c52", "#b7d1a3", "#dee8be", "#fcf7d3", "#1c0113", "#6b0103", "#a30006", "#c21a01", "#f03c02", "#382f32", "#ffeaf2", "#fcd9e5", "#fbc5d8", "#f1396d", "#e3dfba", "#c8d6bf", "#93ccc6", "#6cbdb5", "#1a1f1e", "#000000", "#9f111b", "#b11623", "#292c37", "#cccccc", "#c1b398", "#605951", "#fbeec2", "#61a6ab", "#accec0", "#8dccad", "#988864", "#fea6a2", "#f9d6ac", "#ffe9af", "#f6f6f6", "#e8e8e8", "#333333", "#990100", "#b90504", "#1b325f", "#9cc4e4", "#e9f2f9", "#3a89c9", "#f26c4f", "#5e9fa3", "#dcd1b4", "#fab87f", "#f87e7b", "#b05574", "#951f2b", "#f5f4d7", "#e0dfb1", "#a5a36c", "#535233", "#413d3d", "#040004", "#c8ff00", "#fa023c", "#4b000f", "#eff3cd", "#b2d5ba", "#61ada0", "#248f8d", "#605063", "#2d2d29", "#215a6d", "#3ca2a2", "#92c7a3", "#dfece6", "#cfffdd", "#b4dec1", "#5c5863", "#a85163", "#ff1f4c", "#4e395d", "#827085", "#8ebe94", "#ccfc8e", "#dc5b3e", "#9dc9ac", "#fffec7", "#f56218", "#ff9d2e", "#919167", "#a1dbb2", "#fee5ad", "#faca66", "#f7a541", "#f45d4c", "#ffefd3", "#fffee4", "#d0ecea", "#9fd6d2", "#8b7a5e", "#a8a7a7", "#cc527a", "#e8175d", "#474747", "#363636", "#ffedbf", "#f7803c", "#f54828", "#2e0d23", "#f8e4c1", "#f8edd1", "#d88a8a", "#474843", "#9d9d93", "#c5cfc6", "#f38a8a", "#55443d", "#a0cab5", "#cde9ca", "#f1edd0", "#4e4d4a", "#353432", "#94ba65", "#2790b0", "#2b4e72", "#0ca5b0", "#4e3f30", "#fefeeb", "#f8f4e4", "#a5b3aa", "#a70267", "#f10c49", "#fb6b41", "#f6d86b", "#339194", "#9d7e79", "#ccac95", "#9a947c", "#748b83", "#5b756c", "#edf6ee", "#d1c089", "#b3204d", "#412e28", "#151101", "#046d8b", "#309292", "#2fb8ac", "#93a42a", "#ecbe13", "#4d3b3b", "#de6262", "#ffb88c", "#ffd0b3", "#f5e0d3", "#fffbb7", "#a6f6af", "#66b6ab", "#5b7c8d", "#4f2958", "#ff003c", "#ff8a00", "#fabe28", "#88c100", "#00c176", "#fcfef5", "#e9ffe1", "#cdcfb7", "#d6e6c3", "#fafbe3", "#9cddc8", "#bfd8ad", "#ddd9ab", "#f7af63", "#633d2e", "#30261c", "#403831", "#36544f", "#1f5f61", "#0b8185", "#d1313d", "#e5625c", "#f9bf76", "#8eb2c5", "#615375", "#ffe181", "#eee9e5", "#fad3b2", "#ffba7f", "#ff9c97", "#aaff00", "#ffaa00", "#ff00aa", "#aa00ff", "#00aaff"] var colorindex = 0; let windowXRange, worldXRange = 0 let paddle let Vec2 let accelFactor // TestBed Details windowHeight = $(document).height() windowWidth = document.body.clientWidth console.log(windowHeight, windowWidth); var scale_factor = 10 var SPACE_WIDTH = windowWidth / scale_factor; var SPACE_HEIGHT = windowHeight / scale_factor; // Bead Details var NUM_BEADS = 6 var BEAD_RESTITUTION = 0.7 // Paddle Details accelFactor = 0.042 * SPACE_WIDTH; var paddleMap = new Map(); var maxNumberPaddles = 10; windowHeight = window.innerHeight windowWidth = window.innerWidth var bounceClip = new Audio('http://victordibia.com/skyfall/bounce.wav'); bounceClip.type = 'audio/wav'; var enableAudio = false; var pauseGame = false; var pauseGameAnimationDuration = 500; $("input#sound").click(function () { enableAudio = $(this).is(':checked') soundtext = enableAudio ? "sound on" : "sound off"; $(".soundofftext").text(soundtext) }); function updatePaddleControl(x) { // gamex = x; let mouseX = convertToRange(x, windowXRange, worldXRange); let lineaVeloctiy = Vec2((mouseX - paddle.getPosition().x) * accelFactor, 0) // paddle.setLinearVelocity(lineaVeloctiy) // paddle.setLinearVelocity(lineaVeloctiy) lineaVeloctiy.x = isNaN(lineaVeloctiy.x) ? 0 : lineaVeloctiy.x paddle.setLinearVelocity(lineaVeloctiy) console.log("linear velocity", lineaVeloctiy.x, lineaVeloctiy.y) } planck.testbed(function (testbed) { var pl = planck; Vec2 = pl.Vec2; var world = pl.World(Vec2(0, -30)); var BEAD = 4 var PADDLE = 5 var beadFixedDef = { density: 1.0, restitution: BEAD_RESTITUTION, userData: { name: "bead", points: 3 } }; var paddleFixedDef = { // density : 1.0, // restitution : BEAD_RESTITUTION, userData: { name: "paddle" } }; var self; testbed.step = tick; testbed.width = SPACE_WIDTH; testbed.height = SPACE_HEIGHT; var playerScore = 0; windowXRange = [0, windowWidth] worldXRange = [-(SPACE_WIDTH / 2), SPACE_WIDTH / 2] var characterBodies = []; var paddleBodies = new Map(); var globalTime = 0; var CHARACTER_LIFETIME = 6000 start() $(function () { console.log("ready!"); scoreDiv = document.createElement('div'); $(scoreDiv).addClass("classname") .text("bingo") .appendTo($("body")) //main div }); function start() { addUI() } // Remove paddles that are no longer in frame. function refreshMap(currentMap) { paddleBodies.forEach(function (item, key, mapObj) { if (!currentMap.has(key)) { world.destroyBody(paddleBodies.get(key).paddle); paddleBodies.delete(key) } }); } world.on('pre-solve', function (contact) { var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); var bodyA = contact.getFixtureA().getBody(); var bodyB = contact.getFixtureB().getBody(); var apaddle = bpaddle = false if (fixtureA.getUserData()) { apaddle = fixtureA.getUserData().name == paddleFixedDef.userData.name; } if (fixtureB.getUserData()) { bpaddle = fixtureB.getUserData().name == paddleFixedDef.userData.name; } if (apaddle || bpaddle) { // Paddle collided with something var paddle = apaddle ? fixtureA : fixtureB; var bead = !apaddle ? fixtureA : fixtureB; // console.log(paddle, bead); setTimeout(function () { paddleBeadHit(paddle, bead); }, 1); } }) function paddleBeadHit(paddle, bead) { // console.log("attempting stroke change", bead.getUserData()); //console.log("bead points ",bead.getUserData().points); playClip(bounceClip) updateScoreBox(bead.getUserData().points); } function playClip(clip) { if (enableAudio) { clip.play() } } function updateScoreBox(points) { if (!pauseGame) { playerScore += points; $(".scorevalue").text(playerScore) pointsAdded = points > 0 ? "+" + points : points $(".scoreadded").text(pointsAdded) $(".scoreadded").show().animate({ opacity: 0, fontSize: "4vw", color: "#ff8800" }, 500, function () { $(this).css({ fontSize: "2vw", opacity: 1 }).hide() }); } } function pauseGamePlay() { pauseGame = !pauseGame if (pauseGame) { paddle.setLinearVelocity(Vec2(0, 0)) $(".pauseoverlay").show() $(".overlaycenter").text("Game Paused") $(".overlaycenter").animate({ opacity: 1, fontSize: "4vw" }, pauseGameAnimationDuration, function () {}); } else { paddle.setLinearVelocity(Vec2(3, 0)) $(".overlaycenter").animate({ opacity: 0, fontSize: "0vw" }, pauseGameAnimationDuration, function () { $(".pauseoverlay").hide() }); } } // process mouse move and touch events function mouseMoveHandler(event) { if (!pauseGame) { mouseX = convertToRange(event.clientX, windowXRange, worldXRange); if (!isNaN(mouseX)) { lineaVeloctiy = Vec2((mouseX - paddle.getPosition().x) * accelFactor, 0) paddle.setLinearVelocity(lineaVeloctiy) // xdiff = mouseX - paddle.getPosition().x > 0 ? 100 : -100 // paddle.setPosition(Vec2(mouseX,0)) } } else { } } function addUI() { addPaddle() // Add mouse movement listener to move paddle // Add mouse movement listener to move paddle $(document).bind('touchmove touchstart mousemove', function (e) { e.preventDefault(); var touch if (e.type == "touchmove") { touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; } else if (e.type == "touchstart") { touch = e.targetTouches[0] } else if (e.type == "mousemove") { touch = e } mouseMoveHandler(touch) }); // Add keypress event listener to pause game document.onkeyup = function (e) { var key = e.keyCode ? e.keyCode : e.which; if (key == 32) { console.log("spacebar pressed") pauseGamePlay() } if (key == 83) { $("input#sound").click() } } var ground = world.createBody(); var groundY = -(0.3 * SPACE_HEIGHT) // ground.createFixture(pl.Edge(Vec2(-(0.95 * SPACE_WIDTH / 2), groundY), Vec2((0.95 * SPACE_WIDTH / 2), groundY)), 0.0); } function addPaddle() { paddle = world.createBody({ type: "kinematic", filterCategoryBits: PADDLE, filterMaskBits: BEAD, position: Vec2(-(0.4 * SPACE_WIDTH / 2), -(0.25 * SPACE_HEIGHT)) }) paddleLines = [ [1.8, -0.1], [1.8, 0.1], [1.2, 0.4], [0.4, 0.6], [-2.4, 0.6], [-3.2, 0.4], [-3.8, 0.1], [-3.8, -0.1] ] n = 10, radius = SPACE_WIDTH * 0.03, paddlePath = [], paddlePath = [] paddleLines.forEach(function (each) { paddlePath.push(Vec2(radius * each[0], radius * each[1])) }) paddle.createFixture(pl.Polygon(paddlePath), paddleFixedDef) paddle.render = { fill: '#ff8800', stroke: '#000000' } } // Generate Beeds falling from sky function generateBeads(numCharacters) { for (var i = 0; i < numCharacters; ++i) { var characterBody = world.createBody({ type: 'dynamic', filterCategoryBits: BEAD, filterMaskBits: PADDLE, position: Vec2(pl.Math.random(-(SPACE_WIDTH / 2), (SPACE_WIDTH / 2)), pl.Math.random((0.5 * SPACE_HEIGHT), 0.9 * SPACE_HEIGHT)) }); var beadWidthFactor = 0.005 var beadColor = { fill: '#fff', stroke: '#000000' }; var fd = { density: beadFixedDef.density, restitution: BEAD_RESTITUTION, userData: { name: beadFixedDef.userData.name, points: 3 } }; var randVal = Math.random(); if (randVal > 0.8) { // green ball, + 20 beadColor.fill = '#32CD32' beadWidthFactor = 0.007 fd.userData.points = 20; } else if (randVal < 0.2) { // Red Ball, - 10 beadWidthFactor = 0.007 beadColor.fill = '#ff0000' fd.userData.points = -10; } else { // White ball +10 beadColor.fill = '#fff' beadWidthFactor = 0.007 fd.userData.points = 10; } var shape = pl.Circle(SPACE_WIDTH * beadWidthFactor); characterBody.createFixture(shape, fd); characterBody.render = beadColor characterBody.dieTime = globalTime + CHARACTER_LIFETIME characterBodies.push(characterBody); } } function tick(dt) { globalTime += dt; if (world.m_stepCount % 80 == 0) { if (!pauseGame) { generateBeads(NUM_BEADS); //console.log("car size", characterBodies.length); for (var i = 0; i !== characterBodies.length; i++) { var characterBody = characterBodies[i]; //If the character is old, delete it if (characterBody.dieTime <= globalTime) { characterBodies.splice(i, 1); world.destroyBody(characterBody); i--; continue; } } } } // wrap(box) wrap(paddle) paddleBodies.forEach(function (item, key, mapObj) { stayPaddle(item.paddle) }); } function stayPaddle(paddle) { var p = paddle.getPosition() if (p.x < -SPACE_WIDTH / 2) { p.x = -SPACE_WIDTH / 2 paddle.setPosition(p) } else if (p.x > SPACE_WIDTH / 2) { p.x = SPACE_WIDTH / 2 paddle.setPosition(p) } } // Returns a random number between -0.5 and 0.5 function rand(value) { return (Math.random() - 0.5) * (value || 1); } // If the body is out of space bounds, wrap it to the other side function wrap(body) { var p = body.getPosition(); p.x = wrapNumber(p.x, -SPACE_WIDTH / 2, SPACE_WIDTH / 2); p.y = wrapNumber(p.y, -SPACE_HEIGHT / 2, SPACE_HEIGHT / 2); body.setPosition(p); } function wrapNumber(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } } // rest of your code return world; // make sure you return the world }); function convertToRange(value, srcRange, dstRange) { // value is outside source range return if (value < srcRange[0] || value > srcRange[1]) { return NaN; } var srcMax = srcRange[1] - srcRange[0], dstMax = dstRange[1] - dstRange[0], adjValue = value - srcRange[0]; return (adjValue * dstMax / srcMax) + dstRange[0]; } This Pen is owned by Victor D on CodePen. See more by @victordibia on CodePen
[ { "code": null, "e": 241, "s": 171, "text": "Control the game paddle by waving your hand in front of your web cam." }, { "code": null, "e": 560, "s": 241, "text": "With the TensorFlow object detection api, we have seen examples where models are trained to detect custom objects in images (e.g. detecting hands, toys, racoons, mac n cheese). Naturally, an interesting next step is to explore how these models can be deployed in real world use cases — for example, interaction design." }, { "code": null, "e": 940, "s": 560, "text": "In this post, I cover a basic body-as-input interaction example where real time results from a hand tracking model (web cam stream as input) is mapped to the controls of a web-based game (Skyfall). The system demonstrates how the integration of a fairly accurate, light weight hand detection model can be used to track player hands and enable realtime body-as-input interactions." }, { "code": null, "e": 997, "s": 940, "text": "Want to try it out? Project code is available on Github." }, { "code": null, "e": 1008, "s": 997, "text": "github.com" }, { "code": null, "e": 2174, "s": 1008, "text": "Using parts of the human body as input has the benefit of being always available as the user is not required to carry any secondary device. Importantly, appropriating parts of the human body for gesture based interaction has been shown to improve user experience [2] and overall engagement [1]. While the idea of body as input is not entirely new, existing approaches which leverage computer vision, wearables and sensors (kinect, wii, [5]) etc sometimes suffer from accuracy challenges, are not always portable and can be challenging to integrate with 3rd party software. Advances in light-weight deep neural networks (DNNs), specifically models for object detection (see [3]) and key point extraction (see [4]) hold promise in addressing these issues and furthering the goal of always available (body as) input. These models allow us track the human body with good accuracy using 2D images and with the benefit of easy integration with a range of applications and devices (desktop, web, mobile). While tracking from 2D images does not give us much depth information, it is still surprisingly valuable in building interactions as shown in the Skyfall game example." }, { "code": null, "e": 2695, "s": 2174, "text": "Skyfall is a simple web based game created using planck.js — a 2D physics engine. The play mechanism for SkyFall is simple. 3 types of balls fall from the top of the screen in random order — white balls (worth 10 points), green balls (worth 10 points) and red balls (worth -10 points). Players earn points by moving a paddle to catch the good balls (white and green balls) and avoid bad balls (red balls). In the example below, the player can control the paddle by moving the mouse or by touch (drag) on a mobile device." }, { "code": null, "e": 2704, "s": 2695, "text": "\n\nHTML\n\n" }, { "code": null, "e": 2712, "s": 2704, "text": "\n\nCSS\n\n" }, { "code": null, "e": 2719, "s": 2712, "text": "\n\nJS\n\n" }, { "code": null, "e": 2730, "s": 2719, "text": "\n\nResult\n\n" }, { "code": null, "e": 2752, "s": 2730, "text": "\nSkip Results Iframe\n" }, { "code": null, "e": 4332, "s": 2752, "text": " <div class=\"infordisplay \">\n <div class=\"toprow\">\n <img src=\"http://victordibia.com/skyfall/icon.png\" class=\"icon floatleft \" />\n <div class=\"scorebox iblock \">\n <div class=\"scorevalue inscore\"> 0 </div>\n <div class=\"scorelabel inscore\"> pts </div>\n <div class=\"scoreadded inscore\"> </div>\n </div>\n <div class=\"clear\"></div>\n </div>\n\n\n <div class=\"settingsswitches\">\n <div class=\" \">\n <div class=\"iblock floatleft\">\n <label class=\"switch\">\n <input type=\"checkbox\" id=\"sound\">\n <span class=\"slider round\"></span>\n </label>\n </div>\n <div class=\" iblock soundofftext\"> sound off</div>\n <div class=\"clear\"></div>\n </div>\n\n </div>\n\n <div class=\"pausetext\">\n <div>Sound (s) </div>\n <div>Pause (space bar) </div>\n </div>\n\n <div id=\"updatenote\" class=\"updatenote mt10\"> loading model ..</div>\n <button id=\"trackbutton\" class=\"bx--btn bx--btn--secondary mt10 trackbutton\" type=\"button\" disabled>\n Toggle Video Control ..\n </button>\n\n\n </div>\n <video class=\"videobox canvasbox\" autoplay=\"autoplay\" id=\"myvideo\"></video>\n <canvas id=\"canvas\" class=\"border canvasbox\"></canvas>\n\n <div class=\"pauseoverlay\">\n <div class=\"overlaycenter\">\n Loading Handtrack.js Model ..\n </div>\n </div>" }, { "code": null, "e": 7783, "s": 4332, "text": "body {\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n}\n\n.infordisplay {\n position: absolute;\n margin: 2vw;\n top: 0.0vw;\n color: #fff;\n}\n\n.floatleft {\n float: left;\n}\n\n.clear {\n clear: both;\n}\n\n.dispblock {\n display: block;\n}\n\n.scorebox {\n height: 100%;\n border-bottom: 0.1vw solid #ff8800;\n padding: 1vw;\n font-size: 1.3vw;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n color: #fff;\n margin: 0vw 0vw 0vw 0vw;\n}\n\n.iblock {\n display: inline-block;\n}\n\n.inscore {\n display: inline-block;\n}\n\n.scorevalue {\n font-size: 2vw;\n font-weight: bold;\n}\n\n.scoreadded {\n position: absolute;\n font-size: 2vw;\n font-weight: bold;\n padding: 0vw 0vw 0vw 1vw\n}\n\n.scoreanimate {\n transform: scale(3);\n transition: all 2s;\n}\n\n.icon {\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n width: 4.2vw;\n margin: 0vw;\n}\n\n.border {\n border: 2px solid #fff;\n}\n\n.settingsswitches {\n margin: 1vw 0vw 0vw 0vw;\n}\n\n.soundofftext {\n padding: 0.1vw 1vw 0vw 0.5vw;\n height: 100%;\n font-size: 1.2vw;\n}\n\n.pausetext {\n padding: 1vw 0vw 0vw 0vw;\n font-size: 1vw;\n}\n\n.pauseoverlay {\n position: fixed;\n /* Sit on top of the page content */\n /* display: none; */\n /* Hidden by default */\n width: 100%;\n /* Full width (cover the whole page) */\n height: 100%;\n /* Full height (cover the whole page) */\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n /* Black background with opacity */\n z-index: 2;\n /* Specify a stack order in case you're using a different order for other elements */\n cursor: pointer;\n /* Add a pointer on hover */\n}\n\n.overlaycenter {\n position: absolute;\n top: 50%;\n left: 50%;\n margin-top: -3vw;\n margin-left: -15vw;\n font-size: 0.1vw;\n color: #ff8800;\n opacity: 0;\n font-weight: bold;\n}\n\n/* ============= switches ================== */\n\n/* The switch - the box around the slider */\n.switch {\n position: relative;\n display: inline-block;\n width: 4vw;\n height: 1.8vw;\n}\n\n/* Hide default HTML checkbox */\n.switch input {\n display: none;\n}\n\n/* The slider */\n.slider {\n position: absolute;\n cursor: pointer;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #ccc;\n -webkit-transition: .4s;\n transition: .4s;\n}\n\n.slider:before {\n position: absolute;\n content: \"\";\n height: 1.2vw;\n width: 1.2vw;\n left: 0.4vw;\n bottom: 0.3vw;\n background-color: white;\n -webkit-transition: .4s;\n transition: .4s;\n}\n\ninput:checked+.slider {\n background-color: #ff8800;\n}\n\ninput:focus+.slider {\n box-shadow: 0 0 1px #ff8800;\n}\n\ninput:checked+.slider:before {\n -webkit-transform: translateX(2vw);\n -ms-transform: translateX(2vw);\n transform: translateX(2vw);\n}\n\n/* Rounded sliders */\n.slider.round {\n border-radius: 2vw;\n}\n\n.slider.round:before {\n border-radius: 50%;\n}\n\n.mt10 {\n margin-top: 10px;\n}\n\n.canvasbox {\n position: absolute;\n right: 10px;\n top: 10px;\n border-radius: 3px;\n margin-right: 10px;\n width: 215px;\n height: 162px;\n border-bottom: 3px solid #0063FF;\n box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2), 0 4px 10px 0 #00000030;\n\n}\n\n\n.updatenote{\n padding: 12px;\n background: #ff8800;\n color: #fff;\n display: inline-block;\n /* font-weight: bold; */\n\n}\n\n.trackbutton{\n /* background: #ff8800;\n color: #fff; */\n}" }, { "code": null, "e": 28296, "s": 7783, "text": "const video = document.getElementById(\"myvideo\");\nconst canvas = document.getElementById(\"canvas\");\nconst context = canvas.getContext(\"2d\");\nlet trackButton = document.getElementById(\"trackbutton\");\nlet updateNote = document.getElementById(\"updatenote\");\n\nlet imgindex = 1\nlet isVideo = false;\nlet model = null;\nlet videoInterval = 100\n\n// video.width = 500\n// video.height = 400\n\n$(\".pauseoverlay\").show()\n// $(\".overlaycenter\").text(\"Game Paused\")\n$(\".overlaycenter\").animate({\n opacity: 1,\n fontSize: \"4vw\"\n}, pauseGameAnimationDuration, function () {});\n\nconst modelParams = {\n flipHorizontal: true, // flip e.g for video \n maxNumBoxes: 1, // maximum number of boxes to detect\n iouThreshold: 0.5, // ioU threshold for non-max suppression\n scoreThreshold: 0.6, // confidence threshold for predictions.\n}\n\nfunction startVideo() {\n handTrack.startVideo(video).then(function (status) {\n console.log(\"video started\", status);\n if (status) {\n updateNote.innerText = \"Now tracking\"\n isVideo = true\n runDetection()\n } else {\n updateNote.innerText = \"Please enable video\"\n }\n });\n}\n\nfunction toggleVideo() {\n if (!isVideo) {\n updateNote.innerText = \"Starting video\"\n startVideo();\n } else {\n updateNote.innerText = \"Stopping video\"\n handTrack.stopVideo(video)\n isVideo = false;\n updateNote.innerText = \"Video stopped\"\n }\n}\n\n\n\ntrackButton.addEventListener(\"click\", function () {\n toggleVideo();\n});\n\n\n\nfunction runDetection() {\n model.detect(video).then(predictions => {\n // console.log(\"Predictions: \", predictions);\n // get the middle x value of the bounding box and map to paddle location\n model.renderPredictions(predictions, canvas, context, video);\n if (predictions[0]) {\n let midval = predictions[0].bbox[0] + (predictions[0].bbox[2] / 2)\n gamex = document.body.clientWidth * (midval / video.width)\n updatePaddleControl(gamex)\n console.log('Predictions: ', gamex);\n\n }\n if (isVideo) {\n setTimeout(() => {\n runDetection(video)\n }, videoInterval);\n }\n });\n}\n\n// Load the model.\nhandTrack.load(modelParams).then(lmodel => {\n // detect objects in the image.\n model = lmodel\n updateNote.innerText = \"Loaded Model!\"\n trackButton.disabled = false\n\n $(\".overlaycenter\").animate({\n opacity: 0,\n fontSize: \"0vw\"\n }, pauseGameAnimationDuration, function () {\n $(\".pauseoverlay\").hide()\n });\n});\n\n// ===============================\n\nvar colors = [\"#69d2e7\", \"#a7dbd8\", \"#e0e4cc\", \"#f38630\", \"#fa6900\", \"#fe4365\", \"#fc9d9a\", \"#f9cdad\", \"#c8c8a9\", \"#83af9b\", \"#ecd078\", \"#d95b43\", \"#c02942\", \"#542437\", \"#53777a\", \"#556270\", \"#4ecdc4\", \"#c7f464\", \"#ff6b6b\", \"#c44d58\", \"#774f38\", \"#e08e79\", \"#f1d4af\", \"#ece5ce\", \"#c5e0dc\", \"#e8ddcb\", \"#cdb380\", \"#036564\", \"#033649\", \"#031634\", \"#490a3d\", \"#bd1550\", \"#e97f02\", \"#f8ca00\", \"#8a9b0f\", \"#594f4f\", \"#547980\", \"#45ada8\", \"#9de0ad\", \"#e5fcc2\", \"#00a0b0\", \"#6a4a3c\", \"#cc333f\", \"#eb6841\", \"#edc951\", \"#e94e77\", \"#d68189\", \"#c6a49a\", \"#c6e5d9\", \"#f4ead5\", \"#3fb8af\", \"#7fc7af\", \"#dad8a7\", \"#ff9e9d\", \"#ff3d7f\", \"#d9ceb2\", \"#948c75\", \"#d5ded9\", \"#7a6a53\", \"#99b2b7\", \"#ffffff\", \"#cbe86b\", \"#f2e9e1\", \"#1c140d\", \"#cbe86b\", \"#efffcd\", \"#dce9be\", \"#555152\", \"#2e2633\", \"#99173c\", \"#343838\", \"#005f6b\", \"#008c9e\", \"#00b4cc\", \"#00dffc\", \"#413e4a\", \"#73626e\", \"#b38184\", \"#f0b49e\", \"#f7e4be\", \"#ff4e50\", \"#fc913a\", \"#f9d423\", \"#ede574\", \"#e1f5c4\", \"#99b898\", \"#fecea8\", \"#ff847c\", \"#e84a5f\", \"#2a363b\", \"#655643\", \"#80bca3\", \"#f6f7bd\", \"#e6ac27\", \"#bf4d28\", \"#00a8c6\", \"#40c0cb\", \"#f9f2e7\", \"#aee239\", \"#8fbe00\", \"#351330\", \"#424254\", \"#64908a\", \"#e8caa4\", \"#cc2a41\", \"#554236\", \"#f77825\", \"#d3ce3d\", \"#f1efa5\", \"#60b99a\", \"#ff9900\", \"#424242\", \"#e9e9e9\", \"#bcbcbc\", \"#3299bb\", \"#5d4157\", \"#838689\", \"#a8caba\", \"#cad7b2\", \"#ebe3aa\", \"#8c2318\", \"#5e8c6a\", \"#88a65e\", \"#bfb35a\", \"#f2c45a\", \"#fad089\", \"#ff9c5b\", \"#f5634a\", \"#ed303c\", \"#3b8183\", \"#ff4242\", \"#f4fad2\", \"#d4ee5e\", \"#e1edb9\", \"#f0f2eb\", \"#d1e751\", \"#ffffff\", \"#000000\", \"#4dbce9\", \"#26ade4\", \"#f8b195\", \"#f67280\", \"#c06c84\", \"#6c5b7b\", \"#355c7d\", \"#1b676b\", \"#519548\", \"#88c425\", \"#bef202\", \"#eafde6\", \"#bcbdac\", \"#cfbe27\", \"#f27435\", \"#f02475\", \"#3b2d38\", \"#5e412f\", \"#fcebb6\", \"#78c0a8\", \"#f07818\", \"#f0a830\", \"#452632\", \"#91204d\", \"#e4844a\", \"#e8bf56\", \"#e2f7ce\", \"#eee6ab\", \"#c5bc8e\", \"#696758\", \"#45484b\", \"#36393b\", \"#f0d8a8\", \"#3d1c00\", \"#86b8b1\", \"#f2d694\", \"#fa2a00\", \"#f04155\", \"#ff823a\", \"#f2f26f\", \"#fff7bd\", \"#95cfb7\", \"#2a044a\", \"#0b2e59\", \"#0d6759\", \"#7ab317\", \"#a0c55f\", \"#bbbb88\", \"#ccc68d\", \"#eedd99\", \"#eec290\", \"#eeaa88\", \"#b9d7d9\", \"#668284\", \"#2a2829\", \"#493736\", \"#7b3b3b\", \"#b3cc57\", \"#ecf081\", \"#ffbe40\", \"#ef746f\", \"#ab3e5b\", \"#a3a948\", \"#edb92e\", \"#f85931\", \"#ce1836\", \"#009989\", \"#67917a\", \"#170409\", \"#b8af03\", \"#ccbf82\", \"#e33258\", \"#e8d5b7\", \"#0e2430\", \"#fc3a51\", \"#f5b349\", \"#e8d5b9\", \"#aab3ab\", \"#c4cbb7\", \"#ebefc9\", \"#eee0b7\", \"#e8caaf\", \"#300030\", \"#480048\", \"#601848\", \"#c04848\", \"#f07241\", \"#ab526b\", \"#bca297\", \"#c5ceae\", \"#f0e2a4\", \"#f4ebc3\", \"#607848\", \"#789048\", \"#c0d860\", \"#f0f0d8\", \"#604848\", \"#a8e6ce\", \"#dcedc2\", \"#ffd3b5\", \"#ffaaa6\", \"#ff8c94\", \"#3e4147\", \"#fffedf\", \"#dfba69\", \"#5a2e2e\", \"#2a2c31\", \"#b6d8c0\", \"#c8d9bf\", \"#dadabd\", \"#ecdbbc\", \"#fedcba\", \"#fc354c\", \"#29221f\", \"#13747d\", \"#0abfbc\", \"#fcf7c5\", \"#1c2130\", \"#028f76\", \"#b3e099\", \"#ffeaad\", \"#d14334\", \"#edebe6\", \"#d6e1c7\", \"#94c7b6\", \"#403b33\", \"#d3643b\", \"#cc0c39\", \"#e6781e\", \"#c8cf02\", \"#f8fcc1\", \"#1693a7\", \"#dad6ca\", \"#1bb0ce\", \"#4f8699\", \"#6a5e72\", \"#563444\", \"#a7c5bd\", \"#e5ddcb\", \"#eb7b59\", \"#cf4647\", \"#524656\", \"#fdf1cc\", \"#c6d6b8\", \"#987f69\", \"#e3ad40\", \"#fcd036\", \"#5c323e\", \"#a82743\", \"#e15e32\", \"#c0d23e\", \"#e5f04c\", \"#230f2b\", \"#f21d41\", \"#ebebbc\", \"#bce3c5\", \"#82b3ae\", \"#b9d3b0\", \"#81bda4\", \"#b28774\", \"#f88f79\", \"#f6aa93\", \"#3a111c\", \"#574951\", \"#83988e\", \"#bcdea5\", \"#e6f9bc\", \"#5e3929\", \"#cd8c52\", \"#b7d1a3\", \"#dee8be\", \"#fcf7d3\", \"#1c0113\", \"#6b0103\", \"#a30006\", \"#c21a01\", \"#f03c02\", \"#382f32\", \"#ffeaf2\", \"#fcd9e5\", \"#fbc5d8\", \"#f1396d\", \"#e3dfba\", \"#c8d6bf\", \"#93ccc6\", \"#6cbdb5\", \"#1a1f1e\", \"#000000\", \"#9f111b\", \"#b11623\", \"#292c37\", \"#cccccc\", \"#c1b398\", \"#605951\", \"#fbeec2\", \"#61a6ab\", \"#accec0\", \"#8dccad\", \"#988864\", \"#fea6a2\", \"#f9d6ac\", \"#ffe9af\", \"#f6f6f6\", \"#e8e8e8\", \"#333333\", \"#990100\", \"#b90504\", \"#1b325f\", \"#9cc4e4\", \"#e9f2f9\", \"#3a89c9\", \"#f26c4f\", \"#5e9fa3\", \"#dcd1b4\", \"#fab87f\", \"#f87e7b\", \"#b05574\", \"#951f2b\", \"#f5f4d7\", \"#e0dfb1\", \"#a5a36c\", \"#535233\", \"#413d3d\", \"#040004\", \"#c8ff00\", \"#fa023c\", \"#4b000f\", \"#eff3cd\", \"#b2d5ba\", \"#61ada0\", \"#248f8d\", \"#605063\", \"#2d2d29\", \"#215a6d\", \"#3ca2a2\", \"#92c7a3\", \"#dfece6\", \"#cfffdd\", \"#b4dec1\", \"#5c5863\", \"#a85163\", \"#ff1f4c\", \"#4e395d\", \"#827085\", \"#8ebe94\", \"#ccfc8e\", \"#dc5b3e\", \"#9dc9ac\", \"#fffec7\", \"#f56218\", \"#ff9d2e\", \"#919167\", \"#a1dbb2\", \"#fee5ad\", \"#faca66\", \"#f7a541\", \"#f45d4c\", \"#ffefd3\", \"#fffee4\", \"#d0ecea\", \"#9fd6d2\", \"#8b7a5e\", \"#a8a7a7\", \"#cc527a\", \"#e8175d\", \"#474747\", \"#363636\", \"#ffedbf\", \"#f7803c\", \"#f54828\", \"#2e0d23\", \"#f8e4c1\", \"#f8edd1\", \"#d88a8a\", \"#474843\", \"#9d9d93\", \"#c5cfc6\", \"#f38a8a\", \"#55443d\", \"#a0cab5\", \"#cde9ca\", \"#f1edd0\", \"#4e4d4a\", \"#353432\", \"#94ba65\", \"#2790b0\", \"#2b4e72\", \"#0ca5b0\", \"#4e3f30\", \"#fefeeb\", \"#f8f4e4\", \"#a5b3aa\", \"#a70267\", \"#f10c49\", \"#fb6b41\", \"#f6d86b\", \"#339194\", \"#9d7e79\", \"#ccac95\", \"#9a947c\", \"#748b83\", \"#5b756c\", \"#edf6ee\", \"#d1c089\", \"#b3204d\", \"#412e28\", \"#151101\", \"#046d8b\", \"#309292\", \"#2fb8ac\", \"#93a42a\", \"#ecbe13\", \"#4d3b3b\", \"#de6262\", \"#ffb88c\", \"#ffd0b3\", \"#f5e0d3\", \"#fffbb7\", \"#a6f6af\", \"#66b6ab\", \"#5b7c8d\", \"#4f2958\", \"#ff003c\", \"#ff8a00\", \"#fabe28\", \"#88c100\", \"#00c176\", \"#fcfef5\", \"#e9ffe1\", \"#cdcfb7\", \"#d6e6c3\", \"#fafbe3\", \"#9cddc8\", \"#bfd8ad\", \"#ddd9ab\", \"#f7af63\", \"#633d2e\", \"#30261c\", \"#403831\", \"#36544f\", \"#1f5f61\", \"#0b8185\", \"#d1313d\", \"#e5625c\", \"#f9bf76\", \"#8eb2c5\", \"#615375\", \"#ffe181\", \"#eee9e5\", \"#fad3b2\", \"#ffba7f\", \"#ff9c97\", \"#aaff00\", \"#ffaa00\", \"#ff00aa\", \"#aa00ff\", \"#00aaff\"]\nvar colorindex = 0;\n\n\nlet windowXRange, worldXRange = 0\nlet paddle\nlet Vec2\nlet accelFactor\n\n// TestBed Details\nwindowHeight = $(document).height()\nwindowWidth = document.body.clientWidth\n\nconsole.log(windowHeight, windowWidth);\n\nvar scale_factor = 10\nvar SPACE_WIDTH = windowWidth / scale_factor;\nvar SPACE_HEIGHT = windowHeight / scale_factor;\n\n\n// Bead Details\nvar NUM_BEADS = 6\nvar BEAD_RESTITUTION = 0.7\n\n// Paddle Details\naccelFactor = 0.042 * SPACE_WIDTH;\n\n\n\n\nvar paddleMap = new Map();\nvar maxNumberPaddles = 10;\nwindowHeight = window.innerHeight\nwindowWidth = window.innerWidth\n\nvar bounceClip = new Audio('http://victordibia.com/skyfall/bounce.wav');\nbounceClip.type = 'audio/wav';\nvar enableAudio = false;\nvar pauseGame = false;\nvar pauseGameAnimationDuration = 500;\n\n$(\"input#sound\").click(function () {\n enableAudio = $(this).is(':checked')\n soundtext = enableAudio ? \"sound on\" : \"sound off\";\n $(\".soundofftext\").text(soundtext)\n});\n\n\nfunction updatePaddleControl(x) {\n // gamex = x;\n let mouseX = convertToRange(x, windowXRange, worldXRange);\n let lineaVeloctiy = Vec2((mouseX - paddle.getPosition().x) * accelFactor, 0)\n // paddle.setLinearVelocity(lineaVeloctiy)\n // paddle.setLinearVelocity(lineaVeloctiy)\n lineaVeloctiy.x = isNaN(lineaVeloctiy.x) ? 0 : lineaVeloctiy.x\n paddle.setLinearVelocity(lineaVeloctiy)\n console.log(\"linear velocity\", lineaVeloctiy.x, lineaVeloctiy.y)\n}\n\n\n\nplanck.testbed(function (testbed) {\n var pl = planck;\n Vec2 = pl.Vec2;\n\n var world = pl.World(Vec2(0, -30));\n var BEAD = 4\n var PADDLE = 5\n\n\n var beadFixedDef = {\n density: 1.0,\n restitution: BEAD_RESTITUTION,\n userData: {\n name: \"bead\",\n points: 3\n }\n };\n var paddleFixedDef = {\n // density : 1.0,\n // restitution : BEAD_RESTITUTION,\n userData: {\n name: \"paddle\"\n }\n };\n\n var self;\n\n testbed.step = tick;\n testbed.width = SPACE_WIDTH;\n testbed.height = SPACE_HEIGHT;\n\n var playerScore = 0;\n windowXRange = [0, windowWidth]\n worldXRange = [-(SPACE_WIDTH / 2), SPACE_WIDTH / 2]\n\n\n var characterBodies = [];\n var paddleBodies = new Map();\n\n var globalTime = 0;\n var CHARACTER_LIFETIME = 6000\n\n start()\n\n $(function () {\n console.log(\"ready!\");\n scoreDiv = document.createElement('div');\n $(scoreDiv).addClass(\"classname\")\n .text(\"bingo\")\n .appendTo($(\"body\")) //main div\n });\n\n function start() {\n addUI()\n }\n\n\n\n // Remove paddles that are no longer in frame.\n function refreshMap(currentMap) {\n paddleBodies.forEach(function (item, key, mapObj) {\n if (!currentMap.has(key)) {\n world.destroyBody(paddleBodies.get(key).paddle);\n paddleBodies.delete(key)\n }\n });\n }\n\n world.on('pre-solve', function (contact) {\n\n var fixtureA = contact.getFixtureA();\n var fixtureB = contact.getFixtureB();\n\n var bodyA = contact.getFixtureA().getBody();\n var bodyB = contact.getFixtureB().getBody();\n\n var apaddle = bpaddle = false\n if (fixtureA.getUserData()) {\n apaddle = fixtureA.getUserData().name == paddleFixedDef.userData.name;\n }\n\n if (fixtureB.getUserData()) {\n bpaddle = fixtureB.getUserData().name == paddleFixedDef.userData.name;\n }\n if (apaddle || bpaddle) {\n // Paddle collided with something\n var paddle = apaddle ? fixtureA : fixtureB;\n var bead = !apaddle ? fixtureA : fixtureB;\n\n // console.log(paddle, bead);\n\n setTimeout(function () {\n paddleBeadHit(paddle, bead);\n }, 1);\n }\n\n })\n\n function paddleBeadHit(paddle, bead) {\n // console.log(\"attempting stroke change\", bead.getUserData());\n //console.log(\"bead points \",bead.getUserData().points);\n playClip(bounceClip)\n updateScoreBox(bead.getUserData().points);\n\n }\n\n function playClip(clip) {\n if (enableAudio) {\n clip.play()\n }\n }\n\n function updateScoreBox(points) {\n if (!pauseGame) {\n playerScore += points;\n $(\".scorevalue\").text(playerScore)\n pointsAdded = points > 0 ? \"+\" + points : points\n $(\".scoreadded\").text(pointsAdded)\n $(\".scoreadded\").show().animate({\n opacity: 0,\n fontSize: \"4vw\",\n color: \"#ff8800\"\n }, 500, function () {\n $(this).css({\n fontSize: \"2vw\",\n opacity: 1\n }).hide()\n });\n }\n }\n\n function pauseGamePlay() {\n pauseGame = !pauseGame\n if (pauseGame) {\n paddle.setLinearVelocity(Vec2(0, 0))\n $(\".pauseoverlay\").show()\n $(\".overlaycenter\").text(\"Game Paused\")\n $(\".overlaycenter\").animate({\n opacity: 1,\n fontSize: \"4vw\"\n }, pauseGameAnimationDuration, function () {});\n } else {\n paddle.setLinearVelocity(Vec2(3, 0))\n\n $(\".overlaycenter\").animate({\n opacity: 0,\n fontSize: \"0vw\"\n }, pauseGameAnimationDuration, function () {\n $(\".pauseoverlay\").hide()\n });\n }\n\n }\n\n // process mouse move and touch events\n function mouseMoveHandler(event) {\n if (!pauseGame) {\n mouseX = convertToRange(event.clientX, windowXRange, worldXRange);\n if (!isNaN(mouseX)) {\n lineaVeloctiy = Vec2((mouseX - paddle.getPosition().x) * accelFactor, 0)\n paddle.setLinearVelocity(lineaVeloctiy)\n // xdiff = mouseX - paddle.getPosition().x > 0 ? 100 : -100\n // paddle.setPosition(Vec2(mouseX,0))\n }\n } else {\n\n }\n }\n\n function addUI() {\n addPaddle()\n\n // Add mouse movement listener to move paddle\n // Add mouse movement listener to move paddle\n $(document).bind('touchmove touchstart mousemove', function (e) {\n e.preventDefault();\n var touch\n if (e.type == \"touchmove\") {\n touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];\n } else if (e.type == \"touchstart\") {\n touch = e.targetTouches[0]\n } else if (e.type == \"mousemove\") {\n touch = e\n }\n mouseMoveHandler(touch)\n });\n\n // Add keypress event listener to pause game\n document.onkeyup = function (e) {\n var key = e.keyCode ? e.keyCode : e.which;\n if (key == 32) {\n console.log(\"spacebar pressed\")\n pauseGamePlay()\n }\n if (key == 83) {\n $(\"input#sound\").click()\n }\n }\n\n var ground = world.createBody();\n var groundY = -(0.3 * SPACE_HEIGHT)\n // ground.createFixture(pl.Edge(Vec2(-(0.95 * SPACE_WIDTH / 2), groundY), Vec2((0.95 * SPACE_WIDTH / 2), groundY)), 0.0);\n }\n\n function addPaddle() {\n paddle = world.createBody({\n type: \"kinematic\",\n filterCategoryBits: PADDLE,\n filterMaskBits: BEAD,\n position: Vec2(-(0.4 * SPACE_WIDTH / 2), -(0.25 * SPACE_HEIGHT))\n })\n paddleLines = [\n [1.8, -0.1],\n [1.8, 0.1],\n [1.2, 0.4],\n [0.4, 0.6],\n [-2.4, 0.6],\n [-3.2, 0.4],\n [-3.8, 0.1],\n [-3.8, -0.1]\n ]\n\n n = 10, radius = SPACE_WIDTH * 0.03, paddlePath = [], paddlePath = []\n\n paddleLines.forEach(function (each) {\n paddlePath.push(Vec2(radius * each[0], radius * each[1]))\n })\n\n paddle.createFixture(pl.Polygon(paddlePath), paddleFixedDef)\n paddle.render = {\n fill: '#ff8800',\n stroke: '#000000'\n }\n }\n\n // Generate Beeds falling from sky\n function generateBeads(numCharacters) {\n\n for (var i = 0; i < numCharacters; ++i) {\n var characterBody = world.createBody({\n type: 'dynamic',\n filterCategoryBits: BEAD,\n filterMaskBits: PADDLE,\n position: Vec2(pl.Math.random(-(SPACE_WIDTH / 2), (SPACE_WIDTH / 2)), pl.Math.random((0.5 * SPACE_HEIGHT), 0.9 * SPACE_HEIGHT))\n });\n\n\n var beadWidthFactor = 0.005\n var beadColor = {\n fill: '#fff',\n stroke: '#000000'\n };\n\n var fd = {\n density: beadFixedDef.density,\n restitution: BEAD_RESTITUTION,\n userData: {\n name: beadFixedDef.userData.name,\n points: 3\n }\n };\n\n var randVal = Math.random();\n\n if (randVal > 0.8) {\n // green ball, + 20\n beadColor.fill = '#32CD32'\n beadWidthFactor = 0.007\n fd.userData.points = 20;\n } else if (randVal < 0.2) {\n // Red Ball, - 10\n beadWidthFactor = 0.007\n beadColor.fill = '#ff0000'\n fd.userData.points = -10;\n } else {\n // White ball +10\n beadColor.fill = '#fff'\n beadWidthFactor = 0.007\n fd.userData.points = 10;\n }\n\n\n var shape = pl.Circle(SPACE_WIDTH * beadWidthFactor);\n characterBody.createFixture(shape, fd);\n\n characterBody.render = beadColor\n\n characterBody.dieTime = globalTime + CHARACTER_LIFETIME\n\n characterBodies.push(characterBody);\n }\n\n }\n\n function tick(dt) {\n\n globalTime += dt;\n if (world.m_stepCount % 80 == 0) {\n if (!pauseGame) {\n generateBeads(NUM_BEADS);\n //console.log(\"car size\", characterBodies.length);\n for (var i = 0; i !== characterBodies.length; i++) {\n var characterBody = characterBodies[i];\n //If the character is old, delete it\n if (characterBody.dieTime <= globalTime) {\n characterBodies.splice(i, 1);\n world.destroyBody(characterBody);\n i--;\n continue;\n }\n\n }\n }\n }\n // wrap(box)\n wrap(paddle)\n paddleBodies.forEach(function (item, key, mapObj) {\n stayPaddle(item.paddle)\n });\n\n\n }\n\n function stayPaddle(paddle) {\n var p = paddle.getPosition()\n\n if (p.x < -SPACE_WIDTH / 2) {\n p.x = -SPACE_WIDTH / 2\n paddle.setPosition(p)\n } else if (p.x > SPACE_WIDTH / 2) {\n p.x = SPACE_WIDTH / 2\n paddle.setPosition(p)\n }\n }\n\n // Returns a random number between -0.5 and 0.5\n function rand(value) {\n return (Math.random() - 0.5) * (value || 1);\n }\n\n // If the body is out of space bounds, wrap it to the other side\n function wrap(body) {\n var p = body.getPosition();\n p.x = wrapNumber(p.x, -SPACE_WIDTH / 2, SPACE_WIDTH / 2);\n p.y = wrapNumber(p.y, -SPACE_HEIGHT / 2, SPACE_HEIGHT / 2);\n body.setPosition(p);\n }\n\n\n function wrapNumber(num, min, max) {\n if (typeof min === 'undefined') {\n max = 1, min = 0;\n } else if (typeof max === 'undefined') {\n max = min, min = 0;\n }\n if (max > min) {\n num = (num - min) % (max - min);\n return num + (num < 0 ? max : min);\n } else {\n num = (num - max) % (min - max);\n return num + (num <= 0 ? min : max);\n }\n }\n\n // rest of your code\n return world; // make sure you return the world\n});\n\n\nfunction convertToRange(value, srcRange, dstRange) {\n // value is outside source range return\n if (value < srcRange[0] || value > srcRange[1]) {\n return NaN;\n }\n\n var srcMax = srcRange[1] - srcRange[0],\n dstMax = dstRange[1] - dstRange[0],\n adjValue = value - srcRange[0];\n\n return (adjValue * dstMax / srcMax) + dstRange[0];\n\n}" }, { "code": null, "e": 28340, "s": 28296, "text": "\nThis Pen is owned by Victor D on CodePen.\n" } ]
How to add Matplotlib Colorbar Ticks?
To add ticks to the colorbar, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create x, y and z data points using numpy. Create x, y and z data points using numpy. Use imshow() method to display the data as an image, i.e., on a 2D regular raster. Use imshow() method to display the data as an image, i.e., on a 2D regular raster. Create ticks using numpy in the range of min and max of z. Create ticks using numpy in the range of min and max of z. Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks. Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x, y = np.mgrid[-1:1:100j, -1:1:100j] z = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2)) plt.imshow(z, extent=[-1, 1, -1, 1]) ticks = np.linspace(z.min(), z.max(), 5, endpoint=True) cb = plt.colorbar(ticks=ticks) plt.show()
[ { "code": null, "e": 1126, "s": 1062, "text": "To add ticks to the colorbar, we can take the following steps −" }, { "code": null, "e": 1202, "s": 1126, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1278, "s": 1202, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1321, "s": 1278, "text": "Create x, y and z data points using numpy." }, { "code": null, "e": 1364, "s": 1321, "text": "Create x, y and z data points using numpy." }, { "code": null, "e": 1447, "s": 1364, "text": "Use imshow() method to display the data as an image, i.e., on a 2D regular raster." }, { "code": null, "e": 1530, "s": 1447, "text": "Use imshow() method to display the data as an image, i.e., on a 2D regular raster." }, { "code": null, "e": 1589, "s": 1530, "text": "Create ticks using numpy in the range of min and max of z." }, { "code": null, "e": 1648, "s": 1589, "text": "Create ticks using numpy in the range of min and max of z." }, { "code": null, "e": 1727, "s": 1648, "text": "Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks." }, { "code": null, "e": 1806, "s": 1727, "text": "Create a colorbar for a ScalarMappable instance, *mappable*, with ticks=ticks." }, { "code": null, "e": 1848, "s": 1806, "text": "To display the figure, use show() method." }, { "code": null, "e": 1890, "s": 1848, "text": "To display the figure, use show() method." }, { "code": null, "e": 2254, "s": 1890, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx, y = np.mgrid[-1:1:100j, -1:1:100j]\nz = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2))\n\nplt.imshow(z, extent=[-1, 1, -1, 1])\n\nticks = np.linspace(z.min(), z.max(), 5, endpoint=True)\n\ncb = plt.colorbar(ticks=ticks)\n\nplt.show()" } ]
What is the use of type = "h" in base R for plotting a graph?
The type = "h" is a graphing argument in base R which is generally used inside a plot function. It helps to generate the vertical lines in the R environment instead of points. For example, if we want to plot values from 1 to 10 then type = "h" will plot the vertical lines starting from X-axis and the upper end of the lines will represent the actual value. Live Demo > plot(1:10,type="h") Live Demo > plot(rnorm(10),type="h")
[ { "code": null, "e": 1420, "s": 1062, "text": "The type = \"h\" is a graphing argument in base R which is generally used inside a plot function. It helps to generate the vertical lines in the R environment instead of points. For example, if we want to plot values from 1 to 10 then type = \"h\" will plot the vertical lines starting from X-axis and the upper end of the lines will represent the actual value." }, { "code": null, "e": 1430, "s": 1420, "text": "Live Demo" }, { "code": null, "e": 1452, "s": 1430, "text": "> plot(1:10,type=\"h\")" }, { "code": null, "e": 1462, "s": 1452, "text": "Live Demo" }, { "code": null, "e": 1489, "s": 1462, "text": "> plot(rnorm(10),type=\"h\")" } ]
How to check the website status code using PowerShell?
Website status code is meant to be the status of the website as if the website request from the client is successful or not if the website is available or any error on the webpage which is causing the handshake failed with the client. There are various website status codes. Please refer to the below link for them. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes To retrieve the status using PowerShell, we will first connect the webpage using the Invoke-WebRequest command and then we can use the property StatusCode. For example, $req = Invoke-WebRequest -uri "https://theautomationcode.com" $req StatusCode : 200 StatusDescription : OK Content : <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11"> <script>... We can see the status code in the output. Here 200 code means the connection is successful and no error on the webpage. To retrieve only the status code, $req.StatusCode In the case of page unavailability, it throws the exception and the status code can not be captured, so we need to use a try/catch mechanism for handling the exception and generating the status code. try{ $req = Invoke-WebRequest -uri "https://theautomationcode.com/Unknownpage" Write-output "Status Code -- $($req.StatusCode)" } catch{ Write-Output "Status Code --- $($_.Exception.Response.StatusCode.Value__) " } Status Code --- 404
[ { "code": null, "e": 1297, "s": 1062, "text": "Website status code is meant to be the status of the website as if the website request from the client is successful or not if the website is available or any error on the webpage which is causing the handshake failed with the client." }, { "code": null, "e": 1378, "s": 1297, "text": "There are various website status codes. Please refer to the below link for them." }, { "code": null, "e": 1434, "s": 1378, "text": "https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" }, { "code": null, "e": 1603, "s": 1434, "text": "To retrieve the status using PowerShell, we will first connect the webpage using the Invoke-WebRequest command and then we can use the property StatusCode. For example," }, { "code": null, "e": 1670, "s": 1603, "text": "$req = Invoke-WebRequest -uri \"https://theautomationcode.com\"\n$req" }, { "code": null, "e": 1972, "s": 1670, "text": "StatusCode : 200\nStatusDescription : OK\nContent : <!DOCTYPE html>\n <html lang=\"en-US\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"profile\" href=\"http://gmpg.org/xfn/11\">\n <script>..." }, { "code": null, "e": 2092, "s": 1972, "text": "We can see the status code in the output. Here 200 code means the connection is successful and no error on the webpage." }, { "code": null, "e": 2126, "s": 2092, "text": "To retrieve only the status code," }, { "code": null, "e": 2142, "s": 2126, "text": "$req.StatusCode" }, { "code": null, "e": 2342, "s": 2142, "text": "In the case of page unavailability, it throws the exception and the status code can not be captured, so we need to use a try/catch mechanism for handling the exception and generating the status code." }, { "code": null, "e": 2566, "s": 2342, "text": "try{\n $req = Invoke-WebRequest -uri \"https://theautomationcode.com/Unknownpage\" Write-output \"Status Code -- $($req.StatusCode)\"\n} catch{\n Write-Output \"Status Code --- $($_.Exception.Response.StatusCode.Value__) \"\n}" }, { "code": null, "e": 2586, "s": 2566, "text": "Status Code --- 404" } ]
Bitwise Operators in C
Bitwise operators are used to perform bit-level operations on two variables. Here is the table of bitwise operators in C language, Here is an example of bitwise operators in C language, Live Demo #include <stdio.h> int main() { int x = 10; int y = 28; int i = 0; printf("Bitwise AND : %d\n", x&y); printf("Bitwise OR : %d\n", x|y); printf("Bitwise XOR : %d\n", x^y); printf("Bitwise Complement : %d,%d\n", ~x,~-y); for(i;i<2;i++) printf("Right shift by %d: %d\n", i, x>>i); for(i;i<=3;++i) printf("Left shift by %d: %d\n", i, y<<i); return 0; } Bitwise AND : 8 Bitwise OR : 30 Bitwise XOR : 22 Bitwise Complement : -11,27 Right shift by 0: 10 Right shift by 1: 5 Left shift by 2: 112 Left shift by 3: 224
[ { "code": null, "e": 1193, "s": 1062, "text": "Bitwise operators are used to perform bit-level operations on two variables. Here is the table of bitwise operators in C language," }, { "code": null, "e": 1248, "s": 1193, "text": "Here is an example of bitwise operators in C language," }, { "code": null, "e": 1259, "s": 1248, "text": " Live Demo" }, { "code": null, "e": 1644, "s": 1259, "text": "#include <stdio.h>\nint main() {\n int x = 10;\n int y = 28;\n int i = 0;\n printf(\"Bitwise AND : %d\\n\", x&y);\n printf(\"Bitwise OR : %d\\n\", x|y);\n printf(\"Bitwise XOR : %d\\n\", x^y);\n printf(\"Bitwise Complement : %d,%d\\n\", ~x,~-y);\n for(i;i<2;i++)\n printf(\"Right shift by %d: %d\\n\", i, x>>i);\n for(i;i<=3;++i)\n printf(\"Left shift by %d: %d\\n\", i, y<<i);\n return 0;\n}" }, { "code": null, "e": 1804, "s": 1644, "text": "Bitwise AND : 8\nBitwise OR : 30\nBitwise XOR : 22\nBitwise Complement : -11,27\nRight shift by 0: 10\nRight shift by 1: 5\nLeft shift by 2: 112\nLeft shift by 3: 224" } ]
CICS - Transactions
CICS transactions are used to perform multiple operations in the CICS region. We will be discussing the important CICS transactions supplied by IBM in detail. CESN is known as CICS Execute Sign On. CESN is used to Sign on to the CICS region. CESN is used to Sign on to the CICS region. We need to provide the User-Id and Password given by the CICS administrator to log on to CICS. The following screenshot shows how the sign-on screen looks like − We need to provide the User-Id and Password given by the CICS administrator to log on to CICS. The following screenshot shows how the sign-on screen looks like − CEDA is known as CICS Execute Definition and Administration. It is used by CICS System Administrators to define CICS table entries and other administration activities. CEMT is known as CICS Execute Master Terminal. It is used to inquire and update the status of CICS environments and also for other system operations. Using CEMT command, we can manage transactions, tasks, files, programs, etc. Using CEMT command, we can manage transactions, tasks, files, programs, etc. To get all the possible options, type CEMT and press ENTER. It will display all the options. To get all the possible options, type CEMT and press ENTER. It will display all the options. CEMT is basically used for loading a new program into the CICS or for loading a new copy of the program into the CICS after the program or mapset is changed. CEMT is basically used for loading a new program into the CICS or for loading a new copy of the program into the CICS after the program or mapset is changed. One can overwrite the status of the file displayed to change it. Following example shows how to close a file − CEMT ** Press ENTER & Following Screen is displayed ** STATUS: ENTER ONE OF THE FOLLOWING Inquire Perform Set ** Command to close a file ** CEMT SET FILE (file-name) CEMT I FILE (file-name) CECI is known as CICS Execute Command Interpreter. Many CICS commands can be executed using CECI. CECI is used to check the syntax of the command. It executes the command, only if the syntax is correct. CECI is used to check the syntax of the command. It executes the command, only if the syntax is correct. Type the CECI option on the empty CICS screen after having logged in. It gives you the list of options available. Type the CECI option on the empty CICS screen after having logged in. It gives you the list of options available. Following example shows how to send mapped output data to terminal. We will be discussing about MAPS in the upcoming modules. CECI SEND MAP (map-name) MAPSET (mapset-name) ERASE CEDF is known as CICS Execute Debug Facility. It is used for debugging the program step by step, which helps in finding the errors. Type CEDF and press enter in the CICS region. The terminal is in EDF mode message will be displayed. Now type the transaction id and press the enter key. After initiation, with each enter key, a line is executed. Before executing any CICS command, it shows the screen in which we can modify the values before proceeding further. CMAC is known as CICS Messages for Abend Codes. It is used to find the explanation and reasons for CICS Abend Codes. Following example shows how to check details for an Abend code − CMAC abend-code CESF is known as CICS Execute Sign Off. It is used to Sign Off from the CICS region. Following example shows how to log off from the CICS region − CESF LOGOFF CEBR is known as CICS Execute Temporary storage Browse. It is used to display contents of a temporary storage queue or TSQ. CEBR is used while debugging to check if the items of the queue are being written and retrieved properly. We will discuss more about TSQ in the upcoming modules. Following example shows how to invoke the CEBR command − CEBR queue-id Each command could be achieved by executing a series of CICS macros. We will discuss some basic features which will help us understand the concepts better − This feature of operating system allows more than one task to be executed concurrently. The task may be sharing the same program or using different programs. The CICS schedules the task in its own region. This feature of the operating system allows more than one task to be executed concurrently sharing the same program. For multi-threading to be possible, an application program should be a re-entrant program under the operating system or a quasi-reentrant under the CICS. A re-entrant program is one which does not modify itself and can re-enter in itself and continue processing after an interruption by the operating system. A quasi-reentrant program is a re-entrant program under CICS environment. CICS ensures re-entrancy by acquiring a unique storage area for each task. Between CICS commands, the CICS has the exclusive right to use the CPU resources and it can execute other CICS commands of other tasks. There are times when many users are concurrently using the same program; this is what we call multi-threading. For example, let’s suppose 50 users are using a program A. Here the CICS will provide 50 working storage for that program but one Procedure Division. And this technique is known as quasi-reentrancy. Print Add Notes Bookmark this page
[ { "code": null, "e": 2085, "s": 1926, "text": "CICS transactions are used to perform multiple operations in the CICS region. We will be discussing the important CICS transactions supplied by IBM in detail." }, { "code": null, "e": 2124, "s": 2085, "text": "CESN is known as CICS Execute Sign On." }, { "code": null, "e": 2168, "s": 2124, "text": "CESN is used to Sign on to the CICS region." }, { "code": null, "e": 2212, "s": 2168, "text": "CESN is used to Sign on to the CICS region." }, { "code": null, "e": 2374, "s": 2212, "text": "We need to provide the User-Id and Password given by the CICS administrator to log on to CICS. The following screenshot shows how the sign-on screen looks like −" }, { "code": null, "e": 2536, "s": 2374, "text": "We need to provide the User-Id and Password given by the CICS administrator to log on to CICS. The following screenshot shows how the sign-on screen looks like −" }, { "code": null, "e": 2704, "s": 2536, "text": "CEDA is known as CICS Execute Definition and Administration. It is used by CICS System Administrators to define CICS table entries and other administration activities." }, { "code": null, "e": 2854, "s": 2704, "text": "CEMT is known as CICS Execute Master Terminal. It is used to inquire and update the status of CICS environments and also for other system operations." }, { "code": null, "e": 2931, "s": 2854, "text": "Using CEMT command, we can manage transactions, tasks, files, programs, etc." }, { "code": null, "e": 3008, "s": 2931, "text": "Using CEMT command, we can manage transactions, tasks, files, programs, etc." }, { "code": null, "e": 3101, "s": 3008, "text": "To get all the possible options, type CEMT and press ENTER. It will display all the options." }, { "code": null, "e": 3194, "s": 3101, "text": "To get all the possible options, type CEMT and press ENTER. It will display all the options." }, { "code": null, "e": 3352, "s": 3194, "text": "CEMT is basically used for loading a new program into the CICS or for loading a new copy of the program into the CICS after the program or mapset is changed." }, { "code": null, "e": 3510, "s": 3352, "text": "CEMT is basically used for loading a new program into the CICS or for loading a new copy of the program into the CICS after the program or mapset is changed." }, { "code": null, "e": 3621, "s": 3510, "text": "One can overwrite the status of the file displayed to change it. Following example shows how to close a file −" }, { "code": null, "e": 3829, "s": 3621, "text": "CEMT \n \n** Press ENTER & Following Screen is displayed ** \n\nSTATUS: ENTER ONE OF THE FOLLOWING \nInquire \nPerform \nSet \n \n** Command to close a file **\n \nCEMT SET FILE (file-name) \nCEMT I FILE (file-name)\n" }, { "code": null, "e": 3927, "s": 3829, "text": "CECI is known as CICS Execute Command Interpreter. Many CICS commands can be executed using CECI." }, { "code": null, "e": 4032, "s": 3927, "text": "CECI is used to check the syntax of the command. It executes the command, only if the syntax is correct." }, { "code": null, "e": 4137, "s": 4032, "text": "CECI is used to check the syntax of the command. It executes the command, only if the syntax is correct." }, { "code": null, "e": 4251, "s": 4137, "text": "Type the CECI option on the empty CICS screen after having logged in. It gives you the list of options available." }, { "code": null, "e": 4365, "s": 4251, "text": "Type the CECI option on the empty CICS screen after having logged in. It gives you the list of options available." }, { "code": null, "e": 4491, "s": 4365, "text": "Following example shows how to send mapped output data to terminal. We will be discussing about MAPS in the upcoming modules." }, { "code": null, "e": 4545, "s": 4491, "text": "CECI SEND MAP (map-name) MAPSET (mapset-name) ERASE \n" }, { "code": null, "e": 4677, "s": 4545, "text": "CEDF is known as CICS Execute Debug Facility. It is used for debugging the program step by step, which helps in finding the errors." }, { "code": null, "e": 5006, "s": 4677, "text": "Type CEDF and press enter in the CICS region. The terminal is in EDF mode message will be displayed. Now type the transaction id and press the enter key. After initiation, with each enter key, a line is executed. Before executing any CICS command, it shows the screen in which we can modify the values before proceeding further." }, { "code": null, "e": 5123, "s": 5006, "text": "CMAC is known as CICS Messages for Abend Codes. It is used to find the explanation and reasons for CICS Abend Codes." }, { "code": null, "e": 5188, "s": 5123, "text": "Following example shows how to check details for an Abend code −" }, { "code": null, "e": 5205, "s": 5188, "text": "CMAC abend-code\n" }, { "code": null, "e": 5290, "s": 5205, "text": "CESF is known as CICS Execute Sign Off. It is used to Sign Off from the CICS region." }, { "code": null, "e": 5352, "s": 5290, "text": "Following example shows how to log off from the CICS region −" }, { "code": null, "e": 5365, "s": 5352, "text": "CESF LOGOFF\n" }, { "code": null, "e": 5489, "s": 5365, "text": "CEBR is known as CICS Execute Temporary storage Browse. It is used to display contents of a temporary storage queue or TSQ." }, { "code": null, "e": 5651, "s": 5489, "text": "CEBR is used while debugging to check if the items of the queue are being written and retrieved properly. We will discuss more about TSQ in the upcoming modules." }, { "code": null, "e": 5708, "s": 5651, "text": "Following example shows how to invoke the CEBR command −" }, { "code": null, "e": 5723, "s": 5708, "text": "CEBR queue-id\n" }, { "code": null, "e": 5880, "s": 5723, "text": "Each command could be achieved by executing a series of CICS macros. We will discuss some basic features which will help us understand the concepts better −" }, { "code": null, "e": 6085, "s": 5880, "text": "This feature of operating system allows more than one task to be executed concurrently. The task may be sharing the same program or using different programs. The CICS schedules the task in its own region." }, { "code": null, "e": 6356, "s": 6085, "text": "This feature of the operating system allows more than one task to be executed concurrently sharing the same program. For multi-threading to be possible, an application program should be a re-entrant program under the operating system or a quasi-reentrant under the CICS." }, { "code": null, "e": 6511, "s": 6356, "text": "A re-entrant program is one which does not modify itself and can re-enter in itself and continue processing after an interruption by the operating system." }, { "code": null, "e": 6796, "s": 6511, "text": "A quasi-reentrant program is a re-entrant program under CICS environment. CICS ensures re-entrancy by acquiring a unique storage area for each task. Between CICS commands, the CICS has the exclusive right to use the CPU resources and it can execute other CICS commands of other tasks." }, { "code": null, "e": 7106, "s": 6796, "text": "There are times when many users are concurrently using the same program; this is what we call multi-threading. For example, let’s suppose 50 users are using a program A. Here the CICS will provide 50 working storage for that program but one Procedure Division. And this technique is known as quasi-reentrancy." }, { "code": null, "e": 7113, "s": 7106, "text": " Print" }, { "code": null, "e": 7124, "s": 7113, "text": " Add Notes" } ]
Delete all occurrences of a given key in a doubly linked list - GeeksforGeeks
29 Oct, 2021 Given a doubly linked list and a key x. The problem is to delete all occurrences of the given key x from the doubly linked list.Examples: Algorithm: delAllOccurOfGivenKey(head_ref, x) if head_ref == NULL return Initialize current = head_ref Declare next while current != NULL if current->data == x next = current->next deleteNode(head_ref, current) current = next else current = current->next The algorithm for deleteNode(head_ref, current) (which deletes the node using the pointer to the node) is discussed in this post. C++ Java Python3 C# Javascript /* C++ implementation to delete all occurrences of a given key in a doubly linked list */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* function to delete all occurrences of the given key 'x' */void deleteAllOccurOfX(struct Node** head_ref, int x){ /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list up to the end */ while (current != NULL) { /* if node found with the value 'x' */ if (current->data == x) { /* save current's next node in the pointer 'next' */ next = current->next; /* delete the node pointed to by 'current' */ deleteNode(head_ref, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current->next; }} /* Function to insert a node at the beginning of the Doubly Linked List */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; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ /* if list is empty */ if (head == NULL) cout << "Doubly Linked list empty"; while (head != NULL) { cout << head->data << " "; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ push(&head, 2); push(&head, 5); push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); push(&head, 2); push(&head, 2); cout << "Original Doubly linked list:n"; printList(head); int x = 2; /* delete all occurrences of 'x' */ deleteAllOccurOfX(&head, x); cout << "\nDoubly linked list after deletion of " << x << ":n"; printList(head); return 0;} /* Java implementation to delete all occurrences of a given key in a doubly linked list */import java.util.*;import java.io.*; // a node of the doubly linked listclass Node { int data; Node next, prev;} class GFG { /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* function to delete all occurrences of the given key 'x' */ static Node deleteAllOccurOfX(Node head, int x) { // if list is empty if (head == null) return null; Node current = head; Node next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* save current's next node in the pointer 'next' */ next = current.next; /* delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* Function to insert a node at the beginning of the Doubly Linked List */ static Node push (Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* Function to print nodes in a given doubly linked list */ static void printList (Node temp) { if (temp == null) System.out.print("Doubly Linked list empty"); while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); System.out.println("Original Doubly linked list: "); printList(head); int x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); System.out.println("\nDoubly linked list after deletion of" + x +":"); printList(head); }} // This code is contributed by rachana soma # Python3 implementation to delete all occurrences # of a given key in a doubly linked list import math # a node of the doubly linked list class Node: def __init__(self,data): self.data = data self.next = None self.prev = None # Function to delete a node in a Doubly Linked List.# head_ref --> pointer to head node pointer.# del --> pointer to node to be deleted. def deleteNode(head, delete): # base case if (head == None or delete == None): return None # If node to be deleted is head node if (head == delete): head = delete.next # Change next only if node to be deleted # is NOT the last node if (delete.next != None): delete.next.prev = delete.prev # Change prev only if node to be deleted # is NOT the first node if (delete.prev != None): delete.prev.next = delete.next # Finally, free the memory occupied by del # free(del) delete = None return head # function to delete all occurrences of the given# key 'x' def deleteAllOccurOfX(head, x): # if list is empty if (head == None): return current = head # traverse the list up to the end while (current != None): # if node found with the value 'x' if (current.data == x): # save current's next node in the #pointer 'next' next = current.next # delete the node pointed to by # 'current' head = deleteNode(head, current) # update current current = next # else simply move to the next node else: current = current.next return head # Function to insert a node at the beginning # of the Doubly Linked List def push(head,new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, #prev is always None new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node return head # Function to print nodes in a given doubly# linked list def printList(head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None) : print(head.data,end=" ") head = head.next # Driver functionsif __name__=='__main__': # Start with the empty list head = None # Create the doubly linked list: # 2<->2<->10<->8<->4<->2<->5<->2 head = push(head, 2) head = push(head, 5) head = push(head, 2) head = push(head, 4) head = push(head, 8) head = push(head, 10) head = push(head, 2) head = push(head, 2) print("Original Doubly linked list:") printList(head) x = 2 # delete all occurrences of 'x' head = deleteAllOccurOfX(head, x) print("\nDoubly linked list after deletion of ",x,":") printList(head) # This article contributed by Srathore /* C# implementation to delete all occurrences of a given key in a doubly linked list */using System;using System.Collections; // a node of the doubly linked list public class Node { public int data; public Node next, prev; } class GFG { /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* function to delete all occurrences of the given key 'x' */ static Node deleteAllOccurOfX(Node head, int x) { // if list is empty if (head == null) return null; Node current = head; Node next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* save current's next node in the pointer 'next' */ next = current.next; /* delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* Function to insert a node at the beginning of the Doubly Linked List */ static Node push (Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* Function to print nodes in a given doubly linked list */ static void printList (Node temp) { if (temp == null) Console.Write("Doubly Linked list empty"); while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); Console.WriteLine("Original Doubly linked list: "); printList(head); int x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); Console.WriteLine("\nDoubly linked list after deletion of" + x +":"); printList(head); } } // This code is contributed by Arnab Kundu <script>/* javascript implementation to delete all occurrences of a given key in a doubly linked list */// a node of the doubly linked list class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* * Function to delete a node in a Doubly Linked List. head_ref --> pointer to * head node pointer. del --> pointer to node to be deleted. */ function deleteNode(head, del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* * Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* * Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* * function to delete all occurrences of the given key 'x' */ function deleteAllOccurOfX(head , x) { // if list is empty if (head == null) return null; var current = head;var next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* * save current's next node in the pointer 'next' */ next = current.next; /* * delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(head , new_data) { // allocate nodevar new_node = new Node(); // put in the data new_node.data = new_data; /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* * Function to print nodes in a given doubly linked list */ function printList(temp) { if (temp == null) document.write("Doubly Linked list empty"); while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver code // Start with the empty listvar head = null; /* * Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); document.write("Original Doubly linked list: <br/>"); printList(head); var x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); document.write("<br/>Doubly linked list after deletion of " + x + " :<br/>"); printList(head); // This code contributed by gauravrajput1 </script> Output: Original Doubly linked list: 2 2 10 8 4 2 5 2 Doubly linked list after deletion of 2: 10 8 4 5 Time Complexity: O(n)This article is contributed by Ayush Jauhari. 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. rachana soma andrew1234 nidhi_biet sapnasingh4991 GauravRajput1 simranarora5sos doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List vs Array Delete a Linked List node at a given position Merge two sorted linked lists Queue - Linked List Implementation Implementing a Linked List in Java using Class Find the middle of a given linked list Implement a stack using singly linked list Circular Linked List | Set 1 (Introduction and Applications) Merge Sort for Linked Lists Remove duplicates from a sorted linked list
[ { "code": null, "e": 25248, "s": 25220, "text": "\n29 Oct, 2021" }, { "code": null, "e": 25387, "s": 25248, "text": "Given a doubly linked list and a key x. The problem is to delete all occurrences of the given key x from the doubly linked list.Examples: " }, { "code": null, "e": 25402, "s": 25389, "text": "Algorithm: " }, { "code": null, "e": 25762, "s": 25402, "text": "delAllOccurOfGivenKey(head_ref, x)\n if head_ref == NULL\n return\n Initialize current = head_ref\n Declare next\n while current != NULL\n if current->data == x\n next = current->next\n deleteNode(head_ref, current)\n current = next\n else\n current = current->next" }, { "code": null, "e": 25893, "s": 25762, "text": "The algorithm for deleteNode(head_ref, current) (which deletes the node using the pointer to the node) is discussed in this post. " }, { "code": null, "e": 25897, "s": 25893, "text": "C++" }, { "code": null, "e": 25902, "s": 25897, "text": "Java" }, { "code": null, "e": 25910, "s": 25902, "text": "Python3" }, { "code": null, "e": 25913, "s": 25910, "text": "C#" }, { "code": null, "e": 25924, "s": 25913, "text": "Javascript" }, { "code": "/* C++ implementation to delete all occurrences of a given key in a doubly linked list */#include <bits/stdc++.h> using namespace std; /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del);} /* function to delete all occurrences of the given key 'x' */void deleteAllOccurOfX(struct Node** head_ref, int x){ /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list up to the end */ while (current != NULL) { /* if node found with the value 'x' */ if (current->data == x) { /* save current's next node in the pointer 'next' */ next = current->next; /* delete the node pointed to by 'current' */ deleteNode(head_ref, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current->next; }} /* Function to insert a node at the beginning of the Doubly Linked List */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; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list */void printList(struct Node* head){ /* if list is empty */ if (head == NULL) cout << \"Doubly Linked list empty\"; while (head != NULL) { cout << head->data << \" \"; head = head->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ push(&head, 2); push(&head, 5); push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); push(&head, 2); push(&head, 2); cout << \"Original Doubly linked list:n\"; printList(head); int x = 2; /* delete all occurrences of 'x' */ deleteAllOccurOfX(&head, x); cout << \"\\nDoubly linked list after deletion of \" << x << \":n\"; printList(head); return 0;}", "e": 29270, "s": 25924, "text": null }, { "code": "/* Java implementation to delete all occurrences of a given key in a doubly linked list */import java.util.*;import java.io.*; // a node of the doubly linked listclass Node { int data; Node next, prev;} class GFG { /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* function to delete all occurrences of the given key 'x' */ static Node deleteAllOccurOfX(Node head, int x) { // if list is empty if (head == null) return null; Node current = head; Node next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* save current's next node in the pointer 'next' */ next = current.next; /* delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* Function to insert a node at the beginning of the Doubly Linked List */ static Node push (Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* Function to print nodes in a given doubly linked list */ static void printList (Node temp) { if (temp == null) System.out.print(\"Doubly Linked list empty\"); while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); System.out.println(\"Original Doubly linked list: \"); printList(head); int x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); System.out.println(\"\\nDoubly linked list after deletion of\" + x +\":\"); printList(head); }} // This code is contributed by rachana soma", "e": 33005, "s": 29270, "text": null }, { "code": "# Python3 implementation to delete all occurrences # of a given key in a doubly linked list import math # a node of the doubly linked list class Node: def __init__(self,data): self.data = data self.next = None self.prev = None # Function to delete a node in a Doubly Linked List.# head_ref --> pointer to head node pointer.# del --> pointer to node to be deleted. def deleteNode(head, delete): # base case if (head == None or delete == None): return None # If node to be deleted is head node if (head == delete): head = delete.next # Change next only if node to be deleted # is NOT the last node if (delete.next != None): delete.next.prev = delete.prev # Change prev only if node to be deleted # is NOT the first node if (delete.prev != None): delete.prev.next = delete.next # Finally, free the memory occupied by del # free(del) delete = None return head # function to delete all occurrences of the given# key 'x' def deleteAllOccurOfX(head, x): # if list is empty if (head == None): return current = head # traverse the list up to the end while (current != None): # if node found with the value 'x' if (current.data == x): # save current's next node in the #pointer 'next' next = current.next # delete the node pointed to by # 'current' head = deleteNode(head, current) # update current current = next # else simply move to the next node else: current = current.next return head # Function to insert a node at the beginning # of the Doubly Linked List def push(head,new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, #prev is always None new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node return head # Function to print nodes in a given doubly# linked list def printList(head): # if list is empty if (head == None): print(\"Doubly Linked list empty\") while (head != None) : print(head.data,end=\" \") head = head.next # Driver functionsif __name__=='__main__': # Start with the empty list head = None # Create the doubly linked list: # 2<->2<->10<->8<->4<->2<->5<->2 head = push(head, 2) head = push(head, 5) head = push(head, 2) head = push(head, 4) head = push(head, 8) head = push(head, 10) head = push(head, 2) head = push(head, 2) print(\"Original Doubly linked list:\") printList(head) x = 2 # delete all occurrences of 'x' head = deleteAllOccurOfX(head, x) print(\"\\nDoubly linked list after deletion of \",x,\":\") printList(head) # This article contributed by Srathore", "e": 36109, "s": 33005, "text": null }, { "code": "/* C# implementation to delete all occurrences of a given key in a doubly linked list */using System;using System.Collections; // a node of the doubly linked list public class Node { public int data; public Node next, prev; } class GFG { /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ static Node deleteNode(Node head, Node del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* function to delete all occurrences of the given key 'x' */ static Node deleteAllOccurOfX(Node head, int x) { // if list is empty if (head == null) return null; Node current = head; Node next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* save current's next node in the pointer 'next' */ next = current.next; /* delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* Function to insert a node at the beginning of the Doubly Linked List */ static Node push (Node head, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* Function to print nodes in a given doubly linked list */ static void printList (Node temp) { if (temp == null) Console.Write(\"Doubly Linked list empty\"); while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); Console.WriteLine(\"Original Doubly linked list: \"); printList(head); int x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); Console.WriteLine(\"\\nDoubly linked list after deletion of\" + x +\":\"); printList(head); } } // This code is contributed by Arnab Kundu", "e": 39937, "s": 36109, "text": null }, { "code": "<script>/* javascript implementation to delete all occurrences of a given key in a doubly linked list */// a node of the doubly linked list class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* * Function to delete a node in a Doubly Linked List. head_ref --> pointer to * head node pointer. del --> pointer to node to be deleted. */ function deleteNode(head, del) { // base case if (head == null || del == null) return null; /* If node to be deleted is head node */ if (head == del) head = del.next; /* * Change next only if node to be deleted is NOT the last node */ if (del.next != null) del.next.prev = del.prev; /* * Change prev only if node to be deleted is NOT the first node */ if (del.prev != null) del.prev.next = del.next; del = null; return head; } /* * function to delete all occurrences of the given key 'x' */ function deleteAllOccurOfX(head , x) { // if list is empty if (head == null) return null; var current = head;var next; /* traverse the list up to the end */ while (current != null) { // if node found with the value 'x' if (current.data == x) { /* * save current's next node in the pointer 'next' */ next = current.next; /* * delete the node pointed to by 'current' */ head = deleteNode(head, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current.next; } return head; } /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(head , new_data) { // allocate nodevar new_node = new Node(); // put in the data new_node.data = new_data; /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } /* * Function to print nodes in a given doubly linked list */ function printList(temp) { if (temp == null) document.write(\"Doubly Linked list empty\"); while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver code // Start with the empty listvar head = null; /* * Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ head = push(head, 2); head = push(head, 5); head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); head = push(head, 2); head = push(head, 2); document.write(\"Original Doubly linked list: <br/>\"); printList(head); var x = 2; // delete all occurrences of 'x' head = deleteAllOccurOfX(head, x); document.write(\"<br/>Doubly linked list after deletion of \" + x + \" :<br/>\"); printList(head); // This code contributed by gauravrajput1 </script>", "e": 43572, "s": 39937, "text": null }, { "code": null, "e": 43582, "s": 43572, "text": "Output: " }, { "code": null, "e": 43677, "s": 43582, "text": "Original Doubly linked list:\n2 2 10 8 4 2 5 2\nDoubly linked list after deletion of 2:\n10 8 4 5" }, { "code": null, "e": 44120, "s": 43677, "text": "Time Complexity: O(n)This article is contributed by Ayush Jauhari. 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": 44133, "s": 44120, "text": "rachana soma" }, { "code": null, "e": 44144, "s": 44133, "text": "andrew1234" }, { "code": null, "e": 44155, "s": 44144, "text": "nidhi_biet" }, { "code": null, "e": 44170, "s": 44155, "text": "sapnasingh4991" }, { "code": null, "e": 44184, "s": 44170, "text": "GauravRajput1" }, { "code": null, "e": 44200, "s": 44184, "text": "simranarora5sos" }, { "code": null, "e": 44219, "s": 44200, "text": "doubly linked list" }, { "code": null, "e": 44231, "s": 44219, "text": "Linked List" }, { "code": null, "e": 44243, "s": 44231, "text": "Linked List" }, { "code": null, "e": 44341, "s": 44243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44362, "s": 44341, "text": "Linked List vs Array" }, { "code": null, "e": 44408, "s": 44362, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 44438, "s": 44408, "text": "Merge two sorted linked lists" }, { "code": null, "e": 44473, "s": 44438, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 44520, "s": 44473, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 44559, "s": 44520, "text": "Find the middle of a given linked list" }, { "code": null, "e": 44602, "s": 44559, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 44663, "s": 44602, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 44691, "s": 44663, "text": "Merge Sort for Linked Lists" } ]
How to generate data with Union ALL and Insert ALL in Oracle?
Problem: You wanted to know the difference between Union ALL and Insert ALL to generate small amounts of data. Solution: I have been recently generating small amounts of data for testing some functionality and came across a couple of options in Oracle. Union All and Insert All are two options commonly used for generating small amounts of data in Oracle. The most common set operators in Oracle are UNION and UNION ALL. These operators are used to combine sets of data, even if there are no relationships between these sets. UNION creates a distinct set, whereas UNION ALL allows for duplicates. Removing duplicates can have a huge performance impact, so it is ideal to use UNION ALL by default and later on handle the duplicates. The most common use of UNION ALL is to generate data. In Oracle, we must always select from something, so there is a special pseudo-table named DUAL. The DUAL table only has one row, so if we want to create multiple rows, we must combine statements with UNION ALL like this SELECT 'something' FROM DUAL UNION ALL SELECT 'something_else' FROM DUAL UNION ALL SELECT 'something_more' FROM DUAL UNION ALL SELECT 'something' FROM DUAL UNION ALL SELECT 'something_else' FROM DUAL UNION ALL SELECT 'something_more' FROM DUAL UNION ALL I have used UNION ALL as shown below to generate the data and insert into my target table -- CREATE a table CREATE TABLE tennis_stats ( tennis_player VARCHAR2(100), grandslam_titles NUMBER(2) ); COMMIT; -- Generating data using Union All INSERT INTO tennis_stats SELECT REGEXP_SUBSTR(t.tennis_stats, '[^,]+', 1, 1) tennis_player, REGEXP_SUBSTR(t.tennis_stats, '[^,]+', 1, 2) grandslam_titles FROM ( SELECT 'ROGER FEDERER' || ',' || 20 AS tennis_stats FROM DUAL UNION ALL SELECT 'RAFAEL NADAL' || ',' || 19 AS tennis_stats FROM DUAL UNION ALL SELECT 'NOVAK DJOKOVIC' || ',' || 17 AS tennis_stats FROM DUAL ) t ; COMMIT; Oracle SQL has a multi-table insert operation that lets us insert data into multiple tables in one single statement. Multi-table inserts are useful when we have one source that populates multiple destinations. The INSERT ALL syntax was intended to add data to multiple tables, but I commonly use to generate data and insert multiple rows into the same table. For example, let’s say we want to load the same data shown above using Insert All Option. -- CREATE a table CREATE TABLE tennis_stats ( tennis_player VARCHAR2(100), grandslam_titles NUMBER(2) ); COMMIT; -- CREATE a table CREATE TABLE tennis_stats ( tennis_player VARCHAR2(100), grandslam_titles NUMBER(2) ); COMMIT; -- Generating data using Insert All INSERT ALL INTO tennis_stats VALUES ( 'ROGER FEDERER', 20) INTO tennis_stats VALUES ( 'RAFAEL NADAL', 19) INTO tennis_stats VALUES ( 'NOVAK DJOKOVIC', 17) SELECT * FROM dual; COMMIT; Note INSERT ALL does not use sequences. INSERT ALL only increments the sequence once per the statement, not once per reference. There’s a minor issue with the INSERT ALL statement – the above code doesn’t list all the column names. In a real-world SQL statement, we wouldn’t want to waste so much space repeating the same list of columns. Also, excluding the column names future-proofs the query. If a future version of the table tennis_stats adds a new column, the preceding statement would raise an exception, instead of silently writing bad data. On the other hand, listing the column names ensures the values go in the right columns, even if the column order changes. Excluding column names is a debatable style choice. The INSERT ALL looks neat and easy, but the UNION ALL is overall better for generating data. The INSERT ALL statement is slower to parse than UNION ALL, especially for large statements with hundreds of rows. If our applications are generating lots of data, an INSERT ALL is better than multiple INSERT statements. In conclusion, Insert ALL looks neat but really not meant for generating large amounts of data.
[ { "code": null, "e": 1071, "s": 1062, "text": "Problem:" }, { "code": null, "e": 1173, "s": 1071, "text": "You wanted to know the difference between Union ALL and Insert ALL to generate small amounts of data." }, { "code": null, "e": 1183, "s": 1173, "text": "Solution:" }, { "code": null, "e": 1418, "s": 1183, "text": "I have been recently generating small amounts of data for testing some functionality and came across a couple of options in Oracle. Union All and Insert All are two options commonly used for generating small amounts of data in Oracle." }, { "code": null, "e": 1588, "s": 1418, "text": "The most common set operators in Oracle are UNION and UNION ALL. These operators are used to combine sets of data, even if there are no relationships between these sets." }, { "code": null, "e": 1794, "s": 1588, "text": "UNION creates a distinct set, whereas UNION ALL allows for duplicates. Removing duplicates can have a huge performance impact, so it is ideal to use UNION ALL by default and later on handle the duplicates." }, { "code": null, "e": 1944, "s": 1794, "text": "The most common use of UNION ALL is to generate data. In Oracle, we must always select from something, so there is a special pseudo-table named DUAL." }, { "code": null, "e": 2068, "s": 1944, "text": "The DUAL table only has one row, so if we want to create multiple rows, we must combine statements with UNION ALL like this" }, { "code": null, "e": 2195, "s": 2068, "text": "SELECT 'something' FROM DUAL UNION ALL\nSELECT 'something_else' FROM DUAL UNION ALL\nSELECT 'something_more' FROM DUAL UNION ALL" }, { "code": null, "e": 2322, "s": 2195, "text": "SELECT 'something' FROM DUAL UNION ALL\nSELECT 'something_else' FROM DUAL UNION ALL\nSELECT 'something_more' FROM DUAL UNION ALL" }, { "code": null, "e": 2412, "s": 2322, "text": "I have used UNION ALL as shown below to generate the data and insert into my target table" }, { "code": null, "e": 2530, "s": 2412, "text": "-- CREATE a table\nCREATE TABLE tennis_stats\n( tennis_player VARCHAR2(100),\n grandslam_titles NUMBER(2) );\nCOMMIT;" }, { "code": null, "e": 2960, "s": 2530, "text": "-- Generating data using Union All\nINSERT INTO tennis_stats\nSELECT REGEXP_SUBSTR(t.tennis_stats, '[^,]+', 1, 1) tennis_player,\n REGEXP_SUBSTR(t.tennis_stats, '[^,]+', 1, 2) grandslam_titles\n FROM (\nSELECT 'ROGER FEDERER' || ',' || 20 AS tennis_stats FROM DUAL \nUNION ALL\nSELECT 'RAFAEL NADAL' || ',' || 19 AS tennis_stats FROM DUAL\nUNION ALL\nSELECT 'NOVAK DJOKOVIC' || ',' || 17 AS tennis_stats FROM DUAL ) t ;\nCOMMIT;" }, { "code": null, "e": 3170, "s": 2960, "text": "Oracle SQL has a multi-table insert operation that lets us insert data into multiple tables in one single statement. Multi-table inserts are useful when we have one source that populates multiple destinations." }, { "code": null, "e": 3319, "s": 3170, "text": "The INSERT ALL syntax was intended to add data to multiple tables, but I commonly use to generate data and insert multiple rows into the same table." }, { "code": null, "e": 3409, "s": 3319, "text": "For example, let’s say we want to load the same data shown above using Insert All Option." }, { "code": null, "e": 3527, "s": 3409, "text": "-- CREATE a table\nCREATE TABLE tennis_stats\n( tennis_player VARCHAR2(100),\n grandslam_titles NUMBER(2) );\nCOMMIT;" }, { "code": null, "e": 3645, "s": 3527, "text": "-- CREATE a table\nCREATE TABLE tennis_stats\n( tennis_player VARCHAR2(100),\n grandslam_titles NUMBER(2) );\nCOMMIT;" }, { "code": null, "e": 3864, "s": 3645, "text": "-- Generating data using Insert All\nINSERT ALL\nINTO tennis_stats VALUES ( 'ROGER FEDERER', 20)\nINTO tennis_stats VALUES ( 'RAFAEL NADAL', 19)\nINTO tennis_stats VALUES ( 'NOVAK DJOKOVIC', 17)\nSELECT * FROM dual;\nCOMMIT;" }, { "code": null, "e": 3992, "s": 3864, "text": "Note INSERT ALL does not use sequences. INSERT ALL only increments the sequence once per the statement, not once per reference." }, { "code": null, "e": 4261, "s": 3992, "text": "There’s a minor issue with the INSERT ALL statement – the above code doesn’t list all the column names. In a real-world SQL statement, we wouldn’t want to waste so much space repeating the same list of columns. Also, excluding the column names future-proofs the query." }, { "code": null, "e": 4588, "s": 4261, "text": "If a future version of the table tennis_stats adds a new column, the preceding statement would raise an exception, instead of silently writing bad data. On the other hand, listing the column names ensures the values go in the right columns, even if the column order changes. Excluding column names is a debatable style choice." }, { "code": null, "e": 4796, "s": 4588, "text": "The INSERT ALL looks neat and easy, but the UNION ALL is overall better for generating data. The INSERT ALL statement is slower to parse than UNION ALL, especially for large statements with hundreds of rows." }, { "code": null, "e": 4902, "s": 4796, "text": "If our applications are generating lots of data, an INSERT ALL is better than multiple INSERT statements." }, { "code": null, "e": 4998, "s": 4902, "text": "In conclusion, Insert ALL looks neat but really not meant for generating large amounts of data." } ]
Function Overloading and Overriding in PHP
Function overloading is a feature that permits making creating several methods with a similar name that works differently from one another in the type of the input parameters it accepts as arguments. Let us now see an example to implement function overloading− Live Demo <?php class Shape { const PI = 3.142 ; function __call($name,$arg){ if($name == 'area') switch(count($arg)){ case 0 : return 0 ; case 1 : return self::PI * $arg[0] ; case 2 : return $arg[0] * $arg[1]; } } } $circle = new Shape(); echo $circle->area(3); $rect = new Shape(); echo $rect->area(8,6); ?> This will produce the following output− 9.42648 In function overriding, the parent and child classes have the same function name with and number of arguments Let us now see an example to implement function overriding− Live Demo <?php class Base { function display() { echo "\nBase class function declared final!"; } function demo() { echo "\nBase class function!"; } } class Derived extends Base { function demo() { echo "\nDerived class function!"; } } $ob = new Base; $ob->demo(); $ob->display(); $ob2 = new Derived; $ob2->demo(); $ob2->display(); ?> This will produce the following output− Base class function! Base class function declared final! Derived class function! Base class function declared final!
[ { "code": null, "e": 1262, "s": 1062, "text": "Function overloading is a feature that permits making creating several methods with a similar name that works differently from one another in the type of the input parameters it accepts as arguments." }, { "code": null, "e": 1323, "s": 1262, "text": "Let us now see an example to implement function overloading−" }, { "code": null, "e": 1334, "s": 1323, "text": " Live Demo" }, { "code": null, "e": 1748, "s": 1334, "text": "<?php\n class Shape {\n const PI = 3.142 ;\n function __call($name,$arg){\n if($name == 'area')\n switch(count($arg)){\n case 0 : return 0 ;\n case 1 : return self::PI * $arg[0] ;\n case 2 : return $arg[0] * $arg[1];\n }\n }\n }\n $circle = new Shape();\n echo $circle->area(3);\n $rect = new Shape();\n echo $rect->area(8,6);\n?>" }, { "code": null, "e": 1788, "s": 1748, "text": "This will produce the following output−" }, { "code": null, "e": 1796, "s": 1788, "text": "9.42648" }, { "code": null, "e": 1906, "s": 1796, "text": "In function overriding, the parent and child classes have the same function name with and number of arguments" }, { "code": null, "e": 1966, "s": 1906, "text": "Let us now see an example to implement function overriding−" }, { "code": null, "e": 1977, "s": 1966, "text": " Live Demo" }, { "code": null, "e": 2395, "s": 1977, "text": "<?php\n class Base {\n function display() {\n echo \"\\nBase class function declared final!\";\n }\n function demo() {\n echo \"\\nBase class function!\";\n }\n }\n class Derived extends Base {\n function demo() {\n echo \"\\nDerived class function!\";\n }\n }\n $ob = new Base;\n $ob->demo();\n $ob->display();\n $ob2 = new Derived;\n $ob2->demo();\n $ob2->display();\n?>" }, { "code": null, "e": 2435, "s": 2395, "text": "This will produce the following output−" }, { "code": null, "e": 2552, "s": 2435, "text": "Base class function!\nBase class function declared final!\nDerived class function!\nBase class function declared final!" } ]
Python Pandas - Fill NaN values with the specified value in an Index object
To fill NaN values with the specified value in an Index object, use the index.fillna() method in Pandas. At first, import the required libraries − import pandas as pd import numpy as np Creating Pandas index with some NaN values as well − index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30]) Display the Pandas index − print("Pandas Index...\n",index) Fill the NaN with some specific value − print("\nIndex object after filling NaN value...\n",index.fillna('Amit')) Following is the code − import pandas as pd import numpy as np # Creating Pandas index with some NaN values as well index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30]) # Display the Pandas index print("Pandas Index...\n",index) # Return the number of elements in the Index print("\nNumber of elements in the index...\n",index.size) # Return the dtype of the data print("\nThe dtype object...\n",index.dtype) # Fill the NaN with some specific value print("\nIndex object after filling NaN value...\n",index.fillna('Amit')) This will produce the following output − Pandas Index... Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64') Number of elements in the index... 9 The dtype object... float64 Index object after filling NaN value... Index([50.0, 10.0, 70.0, 'Amit', 90.0, 50.0, 'Amit', 'Amit', 30.0], dtype='object')
[ { "code": null, "e": 1209, "s": 1062, "text": "To fill NaN values with the specified value in an Index object, use the index.fillna() method in Pandas. At first, import the required libraries −" }, { "code": null, "e": 1248, "s": 1209, "text": "import pandas as pd\nimport numpy as np" }, { "code": null, "e": 1301, "s": 1248, "text": "Creating Pandas index with some NaN values as well −" }, { "code": null, "e": 1369, "s": 1301, "text": "index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])\n" }, { "code": null, "e": 1396, "s": 1369, "text": "Display the Pandas index −" }, { "code": null, "e": 1429, "s": 1396, "text": "print(\"Pandas Index...\\n\",index)" }, { "code": null, "e": 1469, "s": 1429, "text": "Fill the NaN with some specific value −" }, { "code": null, "e": 1544, "s": 1469, "text": "print(\"\\nIndex object after filling NaN value...\\n\",index.fillna('Amit'))\n" }, { "code": null, "e": 1568, "s": 1544, "text": "Following is the code −" }, { "code": null, "e": 2086, "s": 1568, "text": "import pandas as pd\nimport numpy as np\n\n# Creating Pandas index with some NaN values as well\nindex = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])\n\n# Display the Pandas index\nprint(\"Pandas Index...\\n\",index)\n\n# Return the number of elements in the Index\nprint(\"\\nNumber of elements in the index...\\n\",index.size)\n\n# Return the dtype of the data\nprint(\"\\nThe dtype object...\\n\",index.dtype)\n\n# Fill the NaN with some specific value\nprint(\"\\nIndex object after filling NaN value...\\n\",index.fillna('Amit'))" }, { "code": null, "e": 2127, "s": 2086, "text": "This will produce the following output −" }, { "code": null, "e": 2418, "s": 2127, "text": "Pandas Index...\nFloat64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')\n\nNumber of elements in the index...\n9\n\nThe dtype object...\nfloat64\n\nIndex object after filling NaN value...\nIndex([50.0, 10.0, 70.0, 'Amit', 90.0, 50.0, 'Amit', 'Amit', 30.0], dtype='object')" } ]
C# | Char.IsPunctuation() Method - GeeksforGeeks
31 Jan, 2019 In C#, Char.IsPunctuation() is a System.Char struct method which is used to check whether an Unicode character can be categorized as a punctuation mark or not. This method can be overloaded by passing different type and number of arguments to it. Char.IsPunctuation(Char) MethodChar.IsPunctuation(String, Int32) Method Char.IsPunctuation(Char) Method Char.IsPunctuation(String, Int32) Method This method is used to check whether the specified Unicode character matches with any punctuation mark or not. If it matches then it returns True otherwise return False. Syntax: public static bool IsPunctuation(char ch); Parameter: ch: It is the required Unicode character of System.char type which is to be compared. Return Type: This method returns True, if it successfully matches any punctuation mark, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsPunctuation(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if dot(.) // is a punctuation mark char ch1 = '.'; result = Char.IsPunctuation(ch1); Console.WriteLine(result); // checking if semi-colon( ; ) // is a punctuation mark char ch2 = ';'; result = Char.IsPunctuation(ch2); Console.WriteLine(result); // checking if comma (, ) // is a punctuation mark char ch3 = ', '; result = Char.IsPunctuation(ch3); Console.WriteLine(result); // checking if 'g' is // a punctuation mark char ch5 = 'g'; result = Char.IsPunctuation(ch5); Console.WriteLine(result); }} True True True False This method is used to check whether the specified string at specified position matches with any punctuation mark or not. If it matches then it returns True otherwise returns False. Syntax: public static bool IsPunctuation(string str, int index); Parameters: str: It is the required string of System.String type which is to be compared.index: It is the position of character in string which is to be compared and type of this parameter is System.Int32. Return Type: The method returns True, if it successfully matches punctuation mark at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean. Exceptions: If the value of str is null then this method will give ArgumentNullException If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException. Example: // C# program to illustrate the// Char.IsPunctuation(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for punctuation // in a string at specific location string str1 = "GeeksforGeeks"; result = Char.IsPunctuation(str1, 2); Console.WriteLine(result); // checking for punctuation // in a string at specific location string str2 = "www.geeksforgeeks.org"; result = Char.IsPunctuation(str2, 3); Console.WriteLine(result); }} False True Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.ispunctuation?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples C# | Method Overriding C# Dictionary with examples C# | Arrays of Strings Difference between Ref and Out keywords in C# C# | Delegates Destructors in C#
[ { "code": null, "e": 23938, "s": 23910, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24185, "s": 23938, "text": "In C#, Char.IsPunctuation() is a System.Char struct method which is used to check whether an Unicode character can be categorized as a punctuation mark or not. This method can be overloaded by passing different type and number of arguments to it." }, { "code": null, "e": 24257, "s": 24185, "text": "Char.IsPunctuation(Char) MethodChar.IsPunctuation(String, Int32) Method" }, { "code": null, "e": 24289, "s": 24257, "text": "Char.IsPunctuation(Char) Method" }, { "code": null, "e": 24330, "s": 24289, "text": "Char.IsPunctuation(String, Int32) Method" }, { "code": null, "e": 24500, "s": 24330, "text": "This method is used to check whether the specified Unicode character matches with any punctuation mark or not. If it matches then it returns True otherwise return False." }, { "code": null, "e": 24508, "s": 24500, "text": "Syntax:" }, { "code": null, "e": 24552, "s": 24508, "text": "public static bool IsPunctuation(char ch);\n" }, { "code": null, "e": 24563, "s": 24552, "text": "Parameter:" }, { "code": null, "e": 24649, "s": 24563, "text": "ch: It is the required Unicode character of System.char type which is to be compared." }, { "code": null, "e": 24812, "s": 24649, "text": "Return Type: This method returns True, if it successfully matches any punctuation mark, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 24821, "s": 24812, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsPunctuation(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if dot(.) // is a punctuation mark char ch1 = '.'; result = Char.IsPunctuation(ch1); Console.WriteLine(result); // checking if semi-colon( ; ) // is a punctuation mark char ch2 = ';'; result = Char.IsPunctuation(ch2); Console.WriteLine(result); // checking if comma (, ) // is a punctuation mark char ch3 = ', '; result = Char.IsPunctuation(ch3); Console.WriteLine(result); // checking if 'g' is // a punctuation mark char ch5 = 'g'; result = Char.IsPunctuation(ch5); Console.WriteLine(result); }}", "e": 25685, "s": 24821, "text": null }, { "code": null, "e": 25707, "s": 25685, "text": "True\nTrue\nTrue\nFalse\n" }, { "code": null, "e": 25889, "s": 25707, "text": "This method is used to check whether the specified string at specified position matches with any punctuation mark or not. If it matches then it returns True otherwise returns False." }, { "code": null, "e": 25897, "s": 25889, "text": "Syntax:" }, { "code": null, "e": 25955, "s": 25897, "text": "public static bool IsPunctuation(string str, int index);\n" }, { "code": null, "e": 25967, "s": 25955, "text": "Parameters:" }, { "code": null, "e": 26161, "s": 25967, "text": "str: It is the required string of System.String type which is to be compared.index: It is the position of character in string which is to be compared and type of this parameter is System.Int32." }, { "code": null, "e": 26366, "s": 26161, "text": "Return Type: The method returns True, if it successfully matches punctuation mark at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 26378, "s": 26366, "text": "Exceptions:" }, { "code": null, "e": 26455, "s": 26378, "text": "If the value of str is null then this method will give ArgumentNullException" }, { "code": null, "e": 26583, "s": 26455, "text": "If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException." }, { "code": null, "e": 26592, "s": 26583, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsPunctuation(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for punctuation // in a string at specific location string str1 = \"GeeksforGeeks\"; result = Char.IsPunctuation(str1, 2); Console.WriteLine(result); // checking for punctuation // in a string at specific location string str2 = \"www.geeksforgeeks.org\"; result = Char.IsPunctuation(str2, 3); Console.WriteLine(result); }}", "e": 27212, "s": 26592, "text": null }, { "code": null, "e": 27224, "s": 27212, "text": "False\nTrue\n" }, { "code": null, "e": 27329, "s": 27224, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.ispunctuation?view=netframework-4.7.2" }, { "code": null, "e": 27348, "s": 27329, "text": "CSharp-Char-Struct" }, { "code": null, "e": 27362, "s": 27348, "text": "CSharp-method" }, { "code": null, "e": 27365, "s": 27362, "text": "C#" }, { "code": null, "e": 27463, "s": 27365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27517, "s": 27463, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 27579, "s": 27517, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 27607, "s": 27579, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 27649, "s": 27607, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 27672, "s": 27649, "text": "C# | Method Overriding" }, { "code": null, "e": 27700, "s": 27672, "text": "C# Dictionary with examples" }, { "code": null, "e": 27723, "s": 27700, "text": "C# | Arrays of Strings" }, { "code": null, "e": 27769, "s": 27723, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27784, "s": 27769, "text": "C# | Delegates" } ]
Understanding Distributions using R | by Sowmya Krishnan | Towards Data Science
How do you communicate data-driven findings? Data Visualizations! There are various tools to achieve this and this article will be speaking of one such tool — R. But even before we can start with visualizing data using R, there are certain concepts and terms we need to understand. By the end of this article, I hope you’ll be able to understand: a) distributions and how to use them to summarize your data set b) the difference between a histogram and a density plot c) normal distribution & the use of standard units d) how to check for normal distribution using quantile plots e) when and how to use boxplots Let us introduce a problem here. Pretend there is an overlord from another planet to whom we need to describe the heights of say, a set of students. To achieve this, we will first need to collect data on the students’ sex and heights in inches. One way to explain the dataset to the extraterrestrial overlord would be to simply share the dataset with it. Another simpler way to showcase this data would be through distributions — the most basic statistical summary of any list. Different forms of distributions are made use of while describing a list of categorical or continuous variables. For instance, in this case the variable ‘sex’ here can be summarized using the prop.table() command to generate a frequency table and help us understand the proportions of the two categories — male and female, in the given dataset. library(dslabs)data(heights)# make a table of category proportionsprop.table(table(heights$sex)) With a greater number of categories, we can make use of a bar plot to describe the distributions. But with numerical data, plotting distributions can be far more challenging. That is because the individual data points may not be unique. A person may report his/her height to be 68.897 inches while another person may report the same as 68.503 inches. It is clear that these people have converted their heights from 175 and 174 inches respectively. Representation of such entries requires a distribution function. This is where the concept of ‘Cumulative Distribution Function’ comes into play. The CDF of a random variable X is defined as, Let us assume that X is a discrete random variable with range R = {x1, x2, x3....} and the range R is bounded from below (i.e. x1). The below given figure shows the general form of the resulting CDF. The CDF is a non-decreasing function and approaches 1 as x becomes large enough. Coming back to the height’s dataset example, when we construct a CDF for it we need to assess if it answers important questions like — where is the distribution centered around, what range contains majority of the data, etc. although CDF can help answer these kind of questions, but it is a lot more difficult. In comparison, we now make use of a histogram to better our understanding of the data. One look at the plot and the overlord would be able to infer important information from it. We can a symmetric distribution around 69 inches and most of the data lying between 63 and 74 inches. With an approximation of this kind, we always loose some kind of information. In this particular case, the implications are negligible. We can also make use of smooth density plots to visualize this distribution of data. While smoothening out the noise, the plot’s peaks help identify the regions or range over which majority of the values are concentrated. One major advantage the density plots have over a histogram is that they are much better at determining the shape of the distribution. E.g., a histogram with say, 5 bins will not produce as distinguishable a shape as a 15-bin histogram would. However, there is no such issue while using density plots. Let us take the summary statistics one step further and calculate the mean and average deviation on this dataset. We are all familiar with what a normal distribution means. When you plot the points from a random collection of data from independent sources, it generates a bell shape curve (or a Gaussian curve). In this graph, the curve’s centre will give you the mean of the dataset. Following are the built-in functions in R used to generate a normal distribution function: dnorm() — Used to find the height of the probability distribution at each point for a given mean and standard deviation. dnorm() — Used to find the height of the probability distribution at each point for a given mean and standard deviation. x <- seq(-20, 20, by = .1)y <- dnorm(x, mean = 5, sd = 0.5)plot(x,y) 2. pnorm() — Also known as the ‘Cumulatibe distribution Function’(CDF), pnorm is used to find the probability of a normally distributed random number to be less that the value of a given number. x <- seq(-10,10,by = .2)y <- pnorm(x, mean = 2.5, sd = 2)plot(x,y) 3. qnorm() — This takes the probability value and gives a number whose cumulative value matches the probability value. x <- seq(0, 1, by = 0.02)y <- qnorm(x, mean = 2, sd = 1)plot(x,y) 4. rnorm() — This function is used to generate random numbers whose distribution is normal. y <- rnorm(50)hist(y, main = "Normal DIstribution") Equation for Normal Distribution: # define x as vector of male heightslibrary(tidyverse)library(dslabs)data(heights)index <- heights$sex=="Male"x <- heights$height[index]# calculate the mean and standard deviation manuallyaverage <- sum(x)/length(x)SD <- sqrt(sum((x - average)^2)/length(x))# built-in mean and sd functions average <- mean(x)SD <- sd(x)c(average = average, SD = SD) In case of the heights of the dataset, this distribution is centred around the average and most data points are within two standard deviations from the average. We observe this distribution is defined only by two parameters — mean and standard deviations and therefore it implies that if a dataset follows a normal distribution, it can be summarized by these two values. In R, we make use of the function scale to obtain standard units. Mathematically, standard unit is defined as follows: It basically tells us of the number of standard deviations an object x (in this case the height) is away from the mean. # calculate standard units z <- scale(x)# calculate proportion of values within 2 SD of mean mean(abs(z) < 2) The proportion of values within -2 and +2 turns of the mean, turns out to be around 95%, which is exactly what the normal distribution predicts it to be. But how do we check if the distributions are well approximated by a normal distribution? The main concept here is that we define a series of proportion p, and based on that define quantile q, such that the proportion of values in the data below q is p. Therefore, if the quantiles for the data are equal to those of the normal distributions we can conclude that the data is approximated by a normal distribution. Let us now calculate the sample and theoretical quantiles to check if the data points fall on an identity line or not. # calculate observed and theoretical quantilesp <- seq(0.05, 0.95, 0.05)observed_quantiles <- quantile(x, p)theoretical_quantiles <- qnorm(p, mean = mean(x), sd = sd(x))# make QQ-plotplot(theoretical_quantiles, observed_quantiles)abline(0,1) Indeed, the values fall on the identity line implying the distributions are well approximated by a normal distribution. Note: a) A special case of quantiles, percentiles are the quantiles obtained while defining p = 0.01, 0.02, 0.03...., 0.99 b) Quartiles are the 25th, 50th and the 75th percentiles and the 50th percentile gives us the values of the median. What happens in case your dataset does not follow a normal distribution and the two parameters — mean and standard deviation are not enough to summarize the data? Boxplots can be helpful in such cases. Dividing the dataset into three quartiles, the boxplot graph represents the first quartile, third quartile, minimum, maximum and median in a dataset. Let us use the same “heights” data set to create a basic boxplot for the relation between the sex (male/female) and heights of the students. data(heights)boxplot(height~sex, data=heights, xlab="Sex",ylab="height") From the above plot we can infer that the standard deviations for the two groups are almost similar although on an average, mean are found to be taller than women. If you want to learn further about other/less common distributions in test statistics, please refer to the ‘Distributions’ in the R Stats Package (link given below)
[ { "code": null, "e": 217, "s": 172, "text": "How do you communicate data-driven findings?" }, { "code": null, "e": 238, "s": 217, "text": "Data Visualizations!" }, { "code": null, "e": 334, "s": 238, "text": "There are various tools to achieve this and this article will be speaking of one such tool — R." }, { "code": null, "e": 519, "s": 334, "text": "But even before we can start with visualizing data using R, there are certain concepts and terms we need to understand. By the end of this article, I hope you’ll be able to understand:" }, { "code": null, "e": 583, "s": 519, "text": "a) distributions and how to use them to summarize your data set" }, { "code": null, "e": 640, "s": 583, "text": "b) the difference between a histogram and a density plot" }, { "code": null, "e": 691, "s": 640, "text": "c) normal distribution & the use of standard units" }, { "code": null, "e": 752, "s": 691, "text": "d) how to check for normal distribution using quantile plots" }, { "code": null, "e": 784, "s": 752, "text": "e) when and how to use boxplots" }, { "code": null, "e": 1139, "s": 784, "text": "Let us introduce a problem here. Pretend there is an overlord from another planet to whom we need to describe the heights of say, a set of students. To achieve this, we will first need to collect data on the students’ sex and heights in inches. One way to explain the dataset to the extraterrestrial overlord would be to simply share the dataset with it." }, { "code": null, "e": 1607, "s": 1139, "text": "Another simpler way to showcase this data would be through distributions — the most basic statistical summary of any list. Different forms of distributions are made use of while describing a list of categorical or continuous variables. For instance, in this case the variable ‘sex’ here can be summarized using the prop.table() command to generate a frequency table and help us understand the proportions of the two categories — male and female, in the given dataset." }, { "code": null, "e": 1704, "s": 1607, "text": "library(dslabs)data(heights)# make a table of category proportionsprop.table(table(heights$sex))" }, { "code": null, "e": 2152, "s": 1704, "text": "With a greater number of categories, we can make use of a bar plot to describe the distributions. But with numerical data, plotting distributions can be far more challenging. That is because the individual data points may not be unique. A person may report his/her height to be 68.897 inches while another person may report the same as 68.503 inches. It is clear that these people have converted their heights from 175 and 174 inches respectively." }, { "code": null, "e": 2344, "s": 2152, "text": "Representation of such entries requires a distribution function. This is where the concept of ‘Cumulative Distribution Function’ comes into play. The CDF of a random variable X is defined as," }, { "code": null, "e": 2625, "s": 2344, "text": "Let us assume that X is a discrete random variable with range R = {x1, x2, x3....} and the range R is bounded from below (i.e. x1). The below given figure shows the general form of the resulting CDF. The CDF is a non-decreasing function and approaches 1 as x becomes large enough." }, { "code": null, "e": 2936, "s": 2625, "text": "Coming back to the height’s dataset example, when we construct a CDF for it we need to assess if it answers important questions like — where is the distribution centered around, what range contains majority of the data, etc. although CDF can help answer these kind of questions, but it is a lot more difficult." }, { "code": null, "e": 3115, "s": 2936, "text": "In comparison, we now make use of a histogram to better our understanding of the data. One look at the plot and the overlord would be able to infer important information from it." }, { "code": null, "e": 3353, "s": 3115, "text": "We can a symmetric distribution around 69 inches and most of the data lying between 63 and 74 inches. With an approximation of this kind, we always loose some kind of information. In this particular case, the implications are negligible." }, { "code": null, "e": 3575, "s": 3353, "text": "We can also make use of smooth density plots to visualize this distribution of data. While smoothening out the noise, the plot’s peaks help identify the regions or range over which majority of the values are concentrated." }, { "code": null, "e": 3877, "s": 3575, "text": "One major advantage the density plots have over a histogram is that they are much better at determining the shape of the distribution. E.g., a histogram with say, 5 bins will not produce as distinguishable a shape as a 15-bin histogram would. However, there is no such issue while using density plots." }, { "code": null, "e": 4262, "s": 3877, "text": "Let us take the summary statistics one step further and calculate the mean and average deviation on this dataset. We are all familiar with what a normal distribution means. When you plot the points from a random collection of data from independent sources, it generates a bell shape curve (or a Gaussian curve). In this graph, the curve’s centre will give you the mean of the dataset." }, { "code": null, "e": 4353, "s": 4262, "text": "Following are the built-in functions in R used to generate a normal distribution function:" }, { "code": null, "e": 4474, "s": 4353, "text": "dnorm() — Used to find the height of the probability distribution at each point for a given mean and standard deviation." }, { "code": null, "e": 4595, "s": 4474, "text": "dnorm() — Used to find the height of the probability distribution at each point for a given mean and standard deviation." }, { "code": null, "e": 4664, "s": 4595, "text": "x <- seq(-20, 20, by = .1)y <- dnorm(x, mean = 5, sd = 0.5)plot(x,y)" }, { "code": null, "e": 4859, "s": 4664, "text": "2. pnorm() — Also known as the ‘Cumulatibe distribution Function’(CDF), pnorm is used to find the probability of a normally distributed random number to be less that the value of a given number." }, { "code": null, "e": 4926, "s": 4859, "text": "x <- seq(-10,10,by = .2)y <- pnorm(x, mean = 2.5, sd = 2)plot(x,y)" }, { "code": null, "e": 5045, "s": 4926, "text": "3. qnorm() — This takes the probability value and gives a number whose cumulative value matches the probability value." }, { "code": null, "e": 5111, "s": 5045, "text": "x <- seq(0, 1, by = 0.02)y <- qnorm(x, mean = 2, sd = 1)plot(x,y)" }, { "code": null, "e": 5203, "s": 5111, "text": "4. rnorm() — This function is used to generate random numbers whose distribution is normal." }, { "code": null, "e": 5255, "s": 5203, "text": "y <- rnorm(50)hist(y, main = \"Normal DIstribution\")" }, { "code": null, "e": 5289, "s": 5255, "text": "Equation for Normal Distribution:" }, { "code": null, "e": 5638, "s": 5289, "text": "# define x as vector of male heightslibrary(tidyverse)library(dslabs)data(heights)index <- heights$sex==\"Male\"x <- heights$height[index]# calculate the mean and standard deviation manuallyaverage <- sum(x)/length(x)SD <- sqrt(sum((x - average)^2)/length(x))# built-in mean and sd functions average <- mean(x)SD <- sd(x)c(average = average, SD = SD)" }, { "code": null, "e": 6009, "s": 5638, "text": "In case of the heights of the dataset, this distribution is centred around the average and most data points are within two standard deviations from the average. We observe this distribution is defined only by two parameters — mean and standard deviations and therefore it implies that if a dataset follows a normal distribution, it can be summarized by these two values." }, { "code": null, "e": 6128, "s": 6009, "text": "In R, we make use of the function scale to obtain standard units. Mathematically, standard unit is defined as follows:" }, { "code": null, "e": 6248, "s": 6128, "text": "It basically tells us of the number of standard deviations an object x (in this case the height) is away from the mean." }, { "code": null, "e": 6358, "s": 6248, "text": "# calculate standard units z <- scale(x)# calculate proportion of values within 2 SD of mean mean(abs(z) < 2)" }, { "code": null, "e": 6512, "s": 6358, "text": "The proportion of values within -2 and +2 turns of the mean, turns out to be around 95%, which is exactly what the normal distribution predicts it to be." }, { "code": null, "e": 6601, "s": 6512, "text": "But how do we check if the distributions are well approximated by a normal distribution?" }, { "code": null, "e": 6925, "s": 6601, "text": "The main concept here is that we define a series of proportion p, and based on that define quantile q, such that the proportion of values in the data below q is p. Therefore, if the quantiles for the data are equal to those of the normal distributions we can conclude that the data is approximated by a normal distribution." }, { "code": null, "e": 7044, "s": 6925, "text": "Let us now calculate the sample and theoretical quantiles to check if the data points fall on an identity line or not." }, { "code": null, "e": 7286, "s": 7044, "text": "# calculate observed and theoretical quantilesp <- seq(0.05, 0.95, 0.05)observed_quantiles <- quantile(x, p)theoretical_quantiles <- qnorm(p, mean = mean(x), sd = sd(x))# make QQ-plotplot(theoretical_quantiles, observed_quantiles)abline(0,1)" }, { "code": null, "e": 7406, "s": 7286, "text": "Indeed, the values fall on the identity line implying the distributions are well approximated by a normal distribution." }, { "code": null, "e": 7412, "s": 7406, "text": "Note:" }, { "code": null, "e": 7529, "s": 7412, "text": "a) A special case of quantiles, percentiles are the quantiles obtained while defining p = 0.01, 0.02, 0.03...., 0.99" }, { "code": null, "e": 7645, "s": 7529, "text": "b) Quartiles are the 25th, 50th and the 75th percentiles and the 50th percentile gives us the values of the median." }, { "code": null, "e": 7997, "s": 7645, "text": "What happens in case your dataset does not follow a normal distribution and the two parameters — mean and standard deviation are not enough to summarize the data? Boxplots can be helpful in such cases. Dividing the dataset into three quartiles, the boxplot graph represents the first quartile, third quartile, minimum, maximum and median in a dataset." }, { "code": null, "e": 8138, "s": 7997, "text": "Let us use the same “heights” data set to create a basic boxplot for the relation between the sex (male/female) and heights of the students." }, { "code": null, "e": 8211, "s": 8138, "text": "data(heights)boxplot(height~sex, data=heights, xlab=\"Sex\",ylab=\"height\")" }, { "code": null, "e": 8375, "s": 8211, "text": "From the above plot we can infer that the standard deviations for the two groups are almost similar although on an average, mean are found to be taller than women." } ]
Amazon Interview Experience - GeeksforGeeks
08 Mar, 2021 Hello Coders, This is my Interview Experience for the position of SDE1 at Amazon (2019). Round 1(Online Round): 2 Coding Questions and 28 MCQ’s Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence. (https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/)Given Equation for num1, num2, and X in the form of a string, and you have to find the value of X in the string.Ex: String is 100000+200000=X X will be 300000 String is 100000+X=500000 X will be 400000 Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence. (https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/) Given Equation for num1, num2, and X in the form of a string, and you have to find the value of X in the string.Ex: String is 100000+200000=X X will be 300000 String is 100000+X=500000 X will be 400000 Ex: String is 100000+200000=X X will be 300000 String is 100000+X=500000 X will be 400000 I Solved both the coding Questions. Be prepared with all pointer concepts and how to return the char string, etc. Round 2(Algorithm Round): I was told to introduce myself. Then he directly went on to the question. The question was : Given a square chessboard of N x N size, the position of Knight and the destination is given. you need to find out the minimum steps a Knight will take to reach the Destination and print the path for the same. (https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/) Given a square chessboard of N x N size, the position of Knight and the destination is given. you need to find out the minimum steps a Knight will take to reach the Destination and print the path for the same. (https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/) Initially, they give me a basic BFS solution that looks at all 8 K Knight modes that will take O (N * N) Time. I was told that I had done well in the code as a wise decision maker. I don’t know what the interviewer was expecting. I was thinking of the A * Search Algorithm that discarded a particular combination but lost the solution (meaning it comes close to the solution in a very short time, used by Google Maps). I did not expect to qualify for this cycle. But luckily I was called to the next round. Round 3(Algorithm Round): The interviewer was very chill. In the beginning, I introduced myself to her, and then she introduced herself. I was supposed to give a brief description of any one of my Project(10 min). Given a linked list, write a function to reverse every k node. (https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/)Given a Binary Tree, find the deepest leaf node that is left child of its parent. (https://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/) Given a linked list, write a function to reverse every k node. (https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/) Given a Binary Tree, find the deepest leaf node that is left child of its parent. (https://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/) Round 4(Fundamental + Algorithm): Initially, I introduced myself. The interviewer was very calm. He asked me about my Subjects. Then the fundamental knowledge was checked in depth. Ex- Paging / Virtual Memory CPU Scheduling Algorithm Deadlock / Semaphore / Critical Section Working of OSI Layers(CN) What happens if I type ‘google.com’ as URL. Explain the whole process. Round 5(Tech Round): The interviewer was a highly experienced person. Firstly I introduced myself. I was told to explain any one of my projects, and he told me that how will you improve the same project now. Then he asked one tree question — I was feeling headache, and I was just smiling, the interviewer thought that I was familiar with this question and asked me that whether I am familiar with the question or not, and I said yes(even the question was not familiar to me but don’t this I was lucky at that time) Then he swapped the question. And asked this – https://www.geeksforgeeks.org/check-whether-the-two-binary-search-trees-are-identical-or-not/ https://www.geeksforgeeks.org/check-whether-the-two-binary-search-trees-are-identical-or-not/ I was supposed to just tell the Algorithm orally. Then he asked me about my interests. Amazon Marketing Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Persistent Systems Interview Experience (Martian Program) Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Microsoft Interview Experience for SDE-1 (Hyderabad) Zoho Interview | Set 2 (On-Campus)
[ { "code": null, "e": 25052, "s": 25024, "text": "\n08 Mar, 2021" }, { "code": null, "e": 25141, "s": 25052, "text": "Hello Coders, This is my Interview Experience for the position of SDE1 at Amazon (2019)." }, { "code": null, "e": 25196, "s": 25141, "text": "Round 1(Online Round): 2 Coding Questions and 28 MCQ’s" }, { "code": null, "e": 25612, "s": 25196, "text": "Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence. (https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/)Given Equation for num1, num2, and X in the form of a string, and you have to find the value of X in the string.Ex: String is 100000+200000=X\nX will be 300000\nString is 100000+X=500000\nX will be 400000" }, { "code": null, "e": 25827, "s": 25612, "text": "Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence. (https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/)" }, { "code": null, "e": 26029, "s": 25827, "text": "Given Equation for num1, num2, and X in the form of a string, and you have to find the value of X in the string.Ex: String is 100000+200000=X\nX will be 300000\nString is 100000+X=500000\nX will be 400000" }, { "code": null, "e": 26119, "s": 26029, "text": "Ex: String is 100000+200000=X\nX will be 300000\nString is 100000+X=500000\nX will be 400000" }, { "code": null, "e": 26155, "s": 26119, "text": "I Solved both the coding Questions." }, { "code": null, "e": 26234, "s": 26155, "text": " Be prepared with all pointer concepts and how to return the char string, etc." }, { "code": null, "e": 26354, "s": 26234, "text": "Round 2(Algorithm Round): I was told to introduce myself. Then he directly went on to the question. The question was : " }, { "code": null, "e": 26631, "s": 26354, "text": "Given a square chessboard of N x N size, the position of Knight and the destination is given. you need to find out the minimum steps a Knight will take to reach the Destination and print the path for the same. (https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/)" }, { "code": null, "e": 26908, "s": 26631, "text": "Given a square chessboard of N x N size, the position of Knight and the destination is given. you need to find out the minimum steps a Knight will take to reach the Destination and print the path for the same. (https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/)" }, { "code": null, "e": 27019, "s": 26908, "text": "Initially, they give me a basic BFS solution that looks at all 8 K Knight modes that will take O (N * N) Time." }, { "code": null, "e": 27327, "s": 27019, "text": "I was told that I had done well in the code as a wise decision maker. I don’t know what the interviewer was expecting. I was thinking of the A * Search Algorithm that discarded a particular combination but lost the solution (meaning it comes close to the solution in a very short time, used by Google Maps)." }, { "code": null, "e": 27415, "s": 27327, "text": "I did not expect to qualify for this cycle. But luckily I was called to the next round." }, { "code": null, "e": 27629, "s": 27415, "text": "Round 3(Algorithm Round): The interviewer was very chill. In the beginning, I introduced myself to her, and then she introduced herself. I was supposed to give a brief description of any one of my Project(10 min)." }, { "code": null, "e": 27918, "s": 27629, "text": "Given a linked list, write a function to reverse every k node. (https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/)Given a Binary Tree, find the deepest leaf node that is left child of its parent. (https://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/)" }, { "code": null, "e": 28053, "s": 27918, "text": "Given a linked list, write a function to reverse every k node. (https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/)" }, { "code": null, "e": 28208, "s": 28053, "text": "Given a Binary Tree, find the deepest leaf node that is left child of its parent. (https://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/)" }, { "code": null, "e": 28393, "s": 28208, "text": "Round 4(Fundamental + Algorithm): Initially, I introduced myself. The interviewer was very calm. He asked me about my Subjects. Then the fundamental knowledge was checked in depth. Ex-" }, { "code": null, "e": 28417, "s": 28393, "text": "Paging / Virtual Memory" }, { "code": null, "e": 28442, "s": 28417, "text": "CPU Scheduling Algorithm" }, { "code": null, "e": 28482, "s": 28442, "text": "Deadlock / Semaphore / Critical Section" }, { "code": null, "e": 28508, "s": 28482, "text": "Working of OSI Layers(CN)" }, { "code": null, "e": 28579, "s": 28508, "text": "What happens if I type ‘google.com’ as URL. Explain the whole process." }, { "code": null, "e": 28787, "s": 28579, "text": "Round 5(Tech Round): The interviewer was a highly experienced person. Firstly I introduced myself. I was told to explain any one of my projects, and he told me that how will you improve the same project now." }, { "code": null, "e": 29095, "s": 28787, "text": "Then he asked one tree question — I was feeling headache, and I was just smiling, the interviewer thought that I was familiar with this question and asked me that whether I am familiar with the question or not, and I said yes(even the question was not familiar to me but don’t this I was lucky at that time)" }, { "code": null, "e": 29142, "s": 29095, "text": "Then he swapped the question. And asked this –" }, { "code": null, "e": 29236, "s": 29142, "text": "https://www.geeksforgeeks.org/check-whether-the-two-binary-search-trees-are-identical-or-not/" }, { "code": null, "e": 29330, "s": 29236, "text": "https://www.geeksforgeeks.org/check-whether-the-two-binary-search-trees-are-identical-or-not/" }, { "code": null, "e": 29417, "s": 29330, "text": "I was supposed to just tell the Algorithm orally. Then he asked me about my interests." }, { "code": null, "e": 29424, "s": 29417, "text": "Amazon" }, { "code": null, "e": 29434, "s": 29424, "text": "Marketing" }, { "code": null, "e": 29456, "s": 29434, "text": "Interview Experiences" }, { "code": null, "e": 29463, "s": 29456, "text": "Amazon" }, { "code": null, "e": 29561, "s": 29463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29620, "s": 29561, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 29670, "s": 29620, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 29708, "s": 29670, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29766, "s": 29708, "text": "Persistent Systems Interview Experience (Martian Program)" }, { "code": null, "e": 29816, "s": 29766, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 29881, "s": 29816, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 29927, "s": 29881, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 29965, "s": 29927, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 30018, "s": 29965, "text": "Microsoft Interview Experience for SDE-1 (Hyderabad)" } ]
Gradient Descent Explained. A comprehensive guide to Gradient... | by Daksh Trehan | Towards Data Science
Optimization refers to the task of minimizing/maximizing an objective function f(x) parameterized by x. In machine/deep learning terminology, it’s the task of minimizing the cost/loss function J(w) parameterized by the model’s parameters w ∈ R^d. Optimization algorithms (in the case of minimization) have one of the following goals: Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum.Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems. Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum. Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems. Gradient Descent is an optimizing algorithm used in Machine/ Deep Learning algorithms. The goal of Gradient Descent is to minimize the objective convex function f(x) using iteration. Gradient Descent on Cost function. For ease, let’s take a simple linear model. Error = Y(Predicted)-Y(Actual) A machine learning model always wants low error with maximum accuracy, in order to decrease error we will intuit our algorithm that you’re doing something wrong that is needed to be rectified, that would be done through Gradient Descent. We need to minimize our error, in order to get pointer to minima we need to walk some steps that are known as alpha(learning rate). Randomly initialize values.Update values. Randomly initialize values. Update values. 3. Repeat until slope =0 A derivative is a term that comes from calculus and is calculated as the slope of the graph at a particular point. The slope is described by drawing a tangent line to the graph at the point. So, if we are able to compute this tangent line, we might be able to compute the desired direction to reach the minima. Learning rate must be chosen wisely as:1. if it is too small, then the model will take some time to learn.2. if it is too large, model will converge as our pointer will shoot and we’ll not be able to get to minima. Vanilla gradient descent, however, can’t guarantee good convergence, due to following reasons: Picking an appropriate learning rate can be troublesome. A learning rate that is too low will lead to slow training and a higher learning rate will lead to overshooting of slope. Another key hurdle faced by Vanilla Gradient Descent is it avoid getting trapped in local minima; these local minimas are surrounded by hills of same error, which makes it really hard for vanilla Gradient Descent to escape it. In simple words, every step we take towards minima tends to decrease our slope, now if we visualize, in steep region of curve derivative is going to be large therefore steps taken by our model too would be large but as we will enter gentle region of slope our derivative will decrease and so will the time to reach minima. If we consider, Simple Gradient Descent completely relies only on calculation i.e. if there are 10000 steps, then our model would try to implement Simple Gradient Descent for 10000 times that would be obviously too much time consuming and computationally expensive. In laymen language, suppose a man is walking towards his home but he don’t know the way so he ask for direction from by passer, now we expect him to walk some distance and then ask for direction but man is asking for direction at every step he takes, that is obviously more time consuming, now compare man with Simple Gradient Descent and his goal with minima. In order to avoid drawbacks of vanilla Gradient Descent, we introduced momentum based Gradient Descent where the goal is to lower the computation time and that can be achieved when we introduce the concept of experience i.e. the confidence using previous steps. Pseudocode for momentum based Gradient Descent: update = learning_rate * gradientvelocity = previous_update * momentumparameter = parameter + velocity – update In this way rather than computing new steps again and again we are averaging the decay and as decay increases its effect in decision making decreases and thus the older the step less effect on decision making.More the history more bigger steps will be taken. Even in the gentle region, momentum based Gradient Descent is taking large steps due to the momentum it is burdening along. But due to larger steps it overshoots its goal by longer distance as it oscillate around minima due to steep slope, but despite such hurdles it is faster than vanilla Gradient Descent. In simple words, suppose a man want to reach destination that is 1200m far and he doesn’t know the path, so he decided that after every 250m he will ask for direction, now if he asked direction for 5 times he would’ve travelled 1250m that’s he has already passed his goal and to achieve that goal he would need to trace his steps back. Similar is the case of Momentum based GD where due to high experience our model is taking larger steps that is leading to overshooting and hence missing the goal but to achieve minima model have to trace back its steps. To overcome the problems of momentum based Gradient Descent we use NAG, in this we move first and then compute gradient so that if our oscillations overshoots then it must be insignificant as compared to that of Momentum Based Gradient Descent. Nesterov accelerated Gradient(NAG) is a way to provide history to our momentum. We can now adequately look forward by computing the angle not w.r.t. to our present parameters θ. In this, learning happens on every example: Shuffle the training data set to avoid pre-existing order of examples. Partition the training data set into m examples. Advantages : — a. Easy to fit in memoryb. Computationally fastc. Efficient for large dataset Disadvantages :- a. Due to frequent updates steps taken towards minima are very noisy.b. Noise can make it large to wait.c. Frequent updates are computationally expensive. It is a greedy approach where we have to sum over all examples for each update. Advantages :- a. Less noisy stepsb. produces stable GD convergence.c. Computationally efficient as all resources aren’t used for single sample but rather for all training samples Disadvantages :- a. Additional memory might be needed.b. It can take long to process large database.c. Approximate gradients Instead of going over all examples, Mini-batch Gradient Descent sums up over lower number of examples based on the batch size. It is sum of both Batch Gradient Descent and Stochastic Gradient Descent. Advantages :- a. Easy fit in memory.b. Computationally efficient.c. Stable error go and convergence. In case of sparse data, we would experience sparse ON(1) features and more frequent OFF(0) features, now, most of the time gradient update will be NULL as derivative is zero in most cases and when it will be one, the steps would be too small to reach minima. For frequent features we require low learning rate, but for high features we require high learning rate. So, in order to boost our model for sparse nature data, we need to chose adaptive learning rate. If you like this article, please consider subscribing to my newsletter: Daksh Trehan’s Weekly Newsletter. Hopefully, this article has not only increased your understanding of Gradient Descent but also made you realize machine learning is not difficult and is already happening in your daily life. As always, thank you so much for reading, and please share this article if you found it useful! :) To know more about parameters optimization techniques, follow :- towardsdatascience.com [1] Gradient Descent Algorithm and Its Variants by Imad Dabbura [2] Learning Parameters, Part 2: Momentum-Based & Nesterov Accelerated Gradient Descent by Akshay L Chandra [3] An overview of gradient descent optimization algorithms by Sebastian Ruder [4] Understanding the Mathematics behind Gradient Descent by Parul Pandey. [5] Deep Learning (padhAI) by Dr. Mitesh Khapra and Dr. Pratyush Kumar The cover template is designed by me on canva.com, the source is mentioned on every visual, and the un-mentioned visuals are from my notebook. Join me at www.dakshtrehan.com LinkedIN ~ https://www.linkedin.com/in/dakshtrehan/ Instagram ~ https://www.instagram.com/_daksh_trehan_/ Github ~ https://github.com/dakshtrehan Check my other articles:- Detecting COVID-19 using Deep Learning. Logistic Regression Explained Linear Regression Explained Determining perfect fit for your ML Model. Serving Data Science to a Rookie. Relating Machine Learning techniques to Real Life. Follow for further Machine Learning/ Deep Learning blogs. Cheers. No rights reserved by the author.
[ { "code": null, "e": 506, "s": 172, "text": "Optimization refers to the task of minimizing/maximizing an objective function f(x) parameterized by x. In machine/deep learning terminology, it’s the task of minimizing the cost/loss function J(w) parameterized by the model’s parameters w ∈ R^d. Optimization algorithms (in the case of minimization) have one of the following goals:" }, { "code": null, "e": 844, "s": 506, "text": "Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum.Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems." }, { "code": null, "e": 993, "s": 844, "text": "Find the global minimum of the objective function. This is feasible if the objective function is convex, i.e. any local minimum is a global minimum." }, { "code": null, "e": 1183, "s": 993, "text": "Find the lowest possible value of the objective function within its neighborhood. That’s usually the case if the objective function is not convex as the case in most deep learning problems." }, { "code": null, "e": 1366, "s": 1183, "text": "Gradient Descent is an optimizing algorithm used in Machine/ Deep Learning algorithms. The goal of Gradient Descent is to minimize the objective convex function f(x) using iteration." }, { "code": null, "e": 1401, "s": 1366, "text": "Gradient Descent on Cost function." }, { "code": null, "e": 1445, "s": 1401, "text": "For ease, let’s take a simple linear model." }, { "code": null, "e": 1476, "s": 1445, "text": "Error = Y(Predicted)-Y(Actual)" }, { "code": null, "e": 1714, "s": 1476, "text": "A machine learning model always wants low error with maximum accuracy, in order to decrease error we will intuit our algorithm that you’re doing something wrong that is needed to be rectified, that would be done through Gradient Descent." }, { "code": null, "e": 1846, "s": 1714, "text": "We need to minimize our error, in order to get pointer to minima we need to walk some steps that are known as alpha(learning rate)." }, { "code": null, "e": 1888, "s": 1846, "text": "Randomly initialize values.Update values." }, { "code": null, "e": 1916, "s": 1888, "text": "Randomly initialize values." }, { "code": null, "e": 1931, "s": 1916, "text": "Update values." }, { "code": null, "e": 1956, "s": 1931, "text": "3. Repeat until slope =0" }, { "code": null, "e": 2267, "s": 1956, "text": "A derivative is a term that comes from calculus and is calculated as the slope of the graph at a particular point. The slope is described by drawing a tangent line to the graph at the point. So, if we are able to compute this tangent line, we might be able to compute the desired direction to reach the minima." }, { "code": null, "e": 2482, "s": 2267, "text": "Learning rate must be chosen wisely as:1. if it is too small, then the model will take some time to learn.2. if it is too large, model will converge as our pointer will shoot and we’ll not be able to get to minima." }, { "code": null, "e": 2577, "s": 2482, "text": "Vanilla gradient descent, however, can’t guarantee good convergence, due to following reasons:" }, { "code": null, "e": 2756, "s": 2577, "text": "Picking an appropriate learning rate can be troublesome. A learning rate that is too low will lead to slow training and a higher learning rate will lead to overshooting of slope." }, { "code": null, "e": 2983, "s": 2756, "text": "Another key hurdle faced by Vanilla Gradient Descent is it avoid getting trapped in local minima; these local minimas are surrounded by hills of same error, which makes it really hard for vanilla Gradient Descent to escape it." }, { "code": null, "e": 3306, "s": 2983, "text": "In simple words, every step we take towards minima tends to decrease our slope, now if we visualize, in steep region of curve derivative is going to be large therefore steps taken by our model too would be large but as we will enter gentle region of slope our derivative will decrease and so will the time to reach minima." }, { "code": null, "e": 3572, "s": 3306, "text": "If we consider, Simple Gradient Descent completely relies only on calculation i.e. if there are 10000 steps, then our model would try to implement Simple Gradient Descent for 10000 times that would be obviously too much time consuming and computationally expensive." }, { "code": null, "e": 3933, "s": 3572, "text": "In laymen language, suppose a man is walking towards his home but he don’t know the way so he ask for direction from by passer, now we expect him to walk some distance and then ask for direction but man is asking for direction at every step he takes, that is obviously more time consuming, now compare man with Simple Gradient Descent and his goal with minima." }, { "code": null, "e": 4195, "s": 3933, "text": "In order to avoid drawbacks of vanilla Gradient Descent, we introduced momentum based Gradient Descent where the goal is to lower the computation time and that can be achieved when we introduce the concept of experience i.e. the confidence using previous steps." }, { "code": null, "e": 4243, "s": 4195, "text": "Pseudocode for momentum based Gradient Descent:" }, { "code": null, "e": 4355, "s": 4243, "text": "update = learning_rate * gradientvelocity = previous_update * momentumparameter = parameter + velocity – update" }, { "code": null, "e": 4614, "s": 4355, "text": "In this way rather than computing new steps again and again we are averaging the decay and as decay increases its effect in decision making decreases and thus the older the step less effect on decision making.More the history more bigger steps will be taken." }, { "code": null, "e": 4738, "s": 4614, "text": "Even in the gentle region, momentum based Gradient Descent is taking large steps due to the momentum it is burdening along." }, { "code": null, "e": 4923, "s": 4738, "text": "But due to larger steps it overshoots its goal by longer distance as it oscillate around minima due to steep slope, but despite such hurdles it is faster than vanilla Gradient Descent." }, { "code": null, "e": 5479, "s": 4923, "text": "In simple words, suppose a man want to reach destination that is 1200m far and he doesn’t know the path, so he decided that after every 250m he will ask for direction, now if he asked direction for 5 times he would’ve travelled 1250m that’s he has already passed his goal and to achieve that goal he would need to trace his steps back. Similar is the case of Momentum based GD where due to high experience our model is taking larger steps that is leading to overshooting and hence missing the goal but to achieve minima model have to trace back its steps." }, { "code": null, "e": 5724, "s": 5479, "text": "To overcome the problems of momentum based Gradient Descent we use NAG, in this we move first and then compute gradient so that if our oscillations overshoots then it must be insignificant as compared to that of Momentum Based Gradient Descent." }, { "code": null, "e": 5902, "s": 5724, "text": "Nesterov accelerated Gradient(NAG) is a way to provide history to our momentum. We can now adequately look forward by computing the angle not w.r.t. to our present parameters θ." }, { "code": null, "e": 5946, "s": 5902, "text": "In this, learning happens on every example:" }, { "code": null, "e": 6017, "s": 5946, "text": "Shuffle the training data set to avoid pre-existing order of examples." }, { "code": null, "e": 6066, "s": 6017, "text": "Partition the training data set into m examples." }, { "code": null, "e": 6081, "s": 6066, "text": "Advantages : —" }, { "code": null, "e": 6159, "s": 6081, "text": "a. Easy to fit in memoryb. Computationally fastc. Efficient for large dataset" }, { "code": null, "e": 6176, "s": 6159, "text": "Disadvantages :-" }, { "code": null, "e": 6331, "s": 6176, "text": "a. Due to frequent updates steps taken towards minima are very noisy.b. Noise can make it large to wait.c. Frequent updates are computationally expensive." }, { "code": null, "e": 6411, "s": 6331, "text": "It is a greedy approach where we have to sum over all examples for each update." }, { "code": null, "e": 6425, "s": 6411, "text": "Advantages :-" }, { "code": null, "e": 6590, "s": 6425, "text": "a. Less noisy stepsb. produces stable GD convergence.c. Computationally efficient as all resources aren’t used for single sample but rather for all training samples" }, { "code": null, "e": 6607, "s": 6590, "text": "Disadvantages :-" }, { "code": null, "e": 6715, "s": 6607, "text": "a. Additional memory might be needed.b. It can take long to process large database.c. Approximate gradients" }, { "code": null, "e": 6842, "s": 6715, "text": "Instead of going over all examples, Mini-batch Gradient Descent sums up over lower number of examples based on the batch size." }, { "code": null, "e": 6916, "s": 6842, "text": "It is sum of both Batch Gradient Descent and Stochastic Gradient Descent." }, { "code": null, "e": 6930, "s": 6916, "text": "Advantages :-" }, { "code": null, "e": 7017, "s": 6930, "text": "a. Easy fit in memory.b. Computationally efficient.c. Stable error go and convergence." }, { "code": null, "e": 7276, "s": 7017, "text": "In case of sparse data, we would experience sparse ON(1) features and more frequent OFF(0) features, now, most of the time gradient update will be NULL as derivative is zero in most cases and when it will be one, the steps would be too small to reach minima." }, { "code": null, "e": 7381, "s": 7276, "text": "For frequent features we require low learning rate, but for high features we require high learning rate." }, { "code": null, "e": 7478, "s": 7381, "text": "So, in order to boost our model for sparse nature data, we need to chose adaptive learning rate." }, { "code": null, "e": 7584, "s": 7478, "text": "If you like this article, please consider subscribing to my newsletter: Daksh Trehan’s Weekly Newsletter." }, { "code": null, "e": 7775, "s": 7584, "text": "Hopefully, this article has not only increased your understanding of Gradient Descent but also made you realize machine learning is not difficult and is already happening in your daily life." }, { "code": null, "e": 7874, "s": 7775, "text": "As always, thank you so much for reading, and please share this article if you found it useful! :)" }, { "code": null, "e": 7939, "s": 7874, "text": "To know more about parameters optimization techniques, follow :-" }, { "code": null, "e": 7962, "s": 7939, "text": "towardsdatascience.com" }, { "code": null, "e": 8026, "s": 7962, "text": "[1] Gradient Descent Algorithm and Its Variants by Imad Dabbura" }, { "code": null, "e": 8134, "s": 8026, "text": "[2] Learning Parameters, Part 2: Momentum-Based & Nesterov Accelerated Gradient Descent by Akshay L Chandra" }, { "code": null, "e": 8213, "s": 8134, "text": "[3] An overview of gradient descent optimization algorithms by Sebastian Ruder" }, { "code": null, "e": 8288, "s": 8213, "text": "[4] Understanding the Mathematics behind Gradient Descent by Parul Pandey." }, { "code": null, "e": 8359, "s": 8288, "text": "[5] Deep Learning (padhAI) by Dr. Mitesh Khapra and Dr. Pratyush Kumar" }, { "code": null, "e": 8502, "s": 8359, "text": "The cover template is designed by me on canva.com, the source is mentioned on every visual, and the un-mentioned visuals are from my notebook." }, { "code": null, "e": 8533, "s": 8502, "text": "Join me at www.dakshtrehan.com" }, { "code": null, "e": 8585, "s": 8533, "text": "LinkedIN ~ https://www.linkedin.com/in/dakshtrehan/" }, { "code": null, "e": 8639, "s": 8585, "text": "Instagram ~ https://www.instagram.com/_daksh_trehan_/" }, { "code": null, "e": 8679, "s": 8639, "text": "Github ~ https://github.com/dakshtrehan" }, { "code": null, "e": 8705, "s": 8679, "text": "Check my other articles:-" }, { "code": null, "e": 8745, "s": 8705, "text": "Detecting COVID-19 using Deep Learning." }, { "code": null, "e": 8775, "s": 8745, "text": "Logistic Regression Explained" }, { "code": null, "e": 8803, "s": 8775, "text": "Linear Regression Explained" }, { "code": null, "e": 8846, "s": 8803, "text": "Determining perfect fit for your ML Model." }, { "code": null, "e": 8880, "s": 8846, "text": "Serving Data Science to a Rookie." }, { "code": null, "e": 8931, "s": 8880, "text": "Relating Machine Learning techniques to Real Life." }, { "code": null, "e": 8989, "s": 8931, "text": "Follow for further Machine Learning/ Deep Learning blogs." }, { "code": null, "e": 8997, "s": 8989, "text": "Cheers." }, { "code": null, "e": 9016, "s": 8997, "text": "No rights reserved" } ]
Space Science with Python — A look at Kepler’s first law | Towards Data Science
This is the 2nd part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy! The orbit of a planet is an ellipse with the Sun at one of the two foci This is the first (of three) Kepler’s laws of planetary motion. 400 years ago Johannes Kepler derived the laws based on long term observations from his and Tycho Brahe’s research. He used a huge amount of manually determined planetary position data that lead him to his conclusions. Imagine being a data scientist with tons of printed Excel sheets, no computer, some mechanical mathematical devices and some patience. No GPU optimization or Cloud Computing. This was a true commitment to science. But is the Sun really and exclusively in the centre of our Solar System? Considering Newton’s law of mechanic our home planet, asteroids, planets and also the Sun revolve around a common centre of gravity. The Sun contains over 99 % of the Solar System’s mass. So is a possible movement of the so-called Solar System Barycentre (SSB) with respect to the Sun’s centre that significant? We will answer this question today with our Python skills and our SPICE knowledge from the first tutorial. Last time we learned about SPICE and its way to compute miscellaneous parameters using so called kernels. We loaded the necessary kernels using the SPICE function furnsh. Each kernel was loaded individually. However, larger projects may require to load dozens of kernels. That would bloat our Python code and one could easily lose track of one’s code. To prevent this, SPICE introduced the kernel meta files. A meta file contains the relative or absolute paths to the needed kernels. For this tutorial, each part has its own meta file that sets the relative path to the _kernels directory. Let’s have a look at the meta file: The first 6 lines start with the command \begintext. The following text block is a comment section, where one can add up any project relevant information. The last block starts with \begindata. This indicates SPICE that all following parts are relevant for the coding part. KERNELS_TO_LOAD lists all kernel files that are used in this tutorial part. Please note: If you load kernels that contain similar information (e.g., by accident you load first the naif0012.tls leap seconds kernel and afterwards the naif0011.tls kernel), SPICE considers the order and takes the last one. Now we are prepared for our project. First of all, we need to import the necessary modules. If you have not installed NumPy yet, please install it via pip3. We will need it frequently. Then function furnsh is used to load our newly created kernel meta file. For the position computation we need to set a starting / initial and ending time-stamp. Here, we set the date 2000–01–01 (midnight) UTC and add up 10,000 days (around 27.5 years; this value is chosen randomly by me). These computations can be done with the Python library datetime. Afterwards, the initial and ending times are converted to strings in line 14 and 15, respectively. Finally, the UTC strings are converted to the corresponding Ephemeris times. Why are leap-seconds kernels necessary? A day has 24 hours, a year has 365 days and every 4 years another day is added. This applies to our everyday life. From a detailed scientific point of view our Earth revolves around itself and around the Sun in slightly varying times that need to be compensated. How much time is added in this 10,000 days interval starting at the millennium? A day has 86,400 seconds. This value times 10,000 days leads to 864,000,000 seconds. Subtracting the initial time in ET from the ending time in ET (line 5) leads to 864,000,005.0012845 seconds. Approximately 5 seconds have been added. This is not crucial for our tutorial, but in some high precision scientific fields every millisecond counts. We finally set a NumPy array that contains 10,000 time steps between the starting and ending times. Now we are ready to compute the Solar System Barycentre (SSB) position in x, y, z direction with respect to the Sun’s centre. For this purpose, we compute the position using the SPICE function spkgps (in the last tutorial we used a similar function spkgeo that returns the state vector (position and velocity)). This function requires the following input parameters: targ: The NAIF ID code of the SSB (0). The sophisticated SPICE documentation lists all available ID codes of the Solar System as well as spacecraft missions et: The Ephemeris time ref: The reference frame of interest. In our case, we compute the position in ECLIPJ2000. So, the ecliptic plane of our home planet is the reference plane obs: The NAIF ID of the Sun (10) spkgps returns the position of the SSB w.r.t. the Sun at a certain Ephemeris time computed in the ECLIPJ2000 reference frame. The second output value is the so called light time and stores the travelling time of the light between the Sun’s centre and the SSB. Since we do not need this value, we use a single underscore. Let’s print the result at the initial time point to get a feeling of the x, y, z components and the distance. We get the following output: Position (components) of the Solar System Barycentre w.r.t thecentre of the Sun (at initial time): X = 1068000.0 kmY = 417681.0 kmZ = -30845.0 kmDistance between the Solar System Barycentre w.r.t thecentre of the Sun (at initial time): d = 1147185.0 km Well ... we got some large numbers. A distance between the Sun’s centre and the SSB of over 1 Million kilometres (around 3 times the distance between the Earth and the Moon). Is this ... a lot? Comprehending large numbers in astronomy leads mostly to scaling, like e.g., 1 Astronomical Unit (AU) or 1 Light-year. Here, we can define our own scale, by using the radius of the Sun (around 700,000 km). The Sun’s radius can be extracted from the corresponding SPICE kernel. Before we go into the programming part we need to answer another question. What is the radius of the Sun? It is somehow connected to the surface, but what is the surface of a huge plasma ball? The answer is complex. Different methods are available for the definition of the Sun’s surface. Helioseismological measurements, time measurements of mercury transits, or coupling the definition of the surface with a certain layer of the Photosphere (where one can observe the convection cells and sunspots) lead to different results. In 2015, the International Astronomical Union set the radius to 695,700 km, period. A slightly shifted value (696,000 km) is stored in the SPICE kernel pck00010.tpc that is loaded in the beginning of our tutorial. With the function bodvcd we can extract the radius of the Sun. The function requires 3 parameters: bodyid: The NAIF ID of the Sun (10) item: ‘RADII’ tells the function that we need the radius information of the Sun maxn: The number of expected return parameters. Since we get the radius values of an ellipsoid (x, y, z direction) the number is set to 3. The first output parameter represents the number of returned values and is not needed. We use a single underscore to ignore this value. Since all radii values are the same, we use the first entry as the Sun’s radius. Now, we can plot the Sun and the trajectory of the SSB. We use matplotlib for this task. We create a 2-dimensional projection of our results and plot only the x-y coordinates (movement on the Ecliptic plane). The following code snippet shows how the plot below is created. We add a yellow circle representing the Sun. Since the distances are scaled w.r.t. the Sun’s radius we can simply use a radius of 1. The plot shows the trajectory in blue and one can easily see, that the SSB is not within the Sun all the time (although the Sun contains over 99 % of the Solar System’s mass)! What is the percentage of time the SSB stays outside of the Sun? Let’s have a look: In total: around 65%! An astonishing result. I hope you enjoyed today’s lesson. We used some already known SPICE functions from the last tutorial and have deepen our knowledge. We will continue with that and steadily we will build up a “knowledge fundament” for more complex tasks. So answering the question from the beginning: Is the Sun in the centre in one of the foci of the orbits? Well it is the barycentre of the Solar System. The Sun is “wobbling” around this centre. Does it mean the Kepler laws are wrong? Well that’s science: You postulate a theory that describes the nature until it is proven wrong or it is improved. For no-high-precision measurements and computer models the Sun can be easily put in the centre of our Solar System. The next tutorial will be published on 29th April 2020. Stay tuned and have a great weekend,
[ { "code": null, "e": 312, "s": 172, "text": "This is the 2nd part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy!" }, { "code": null, "e": 384, "s": 312, "text": "The orbit of a planet is an ellipse with the Sun at one of the two foci" }, { "code": null, "e": 881, "s": 384, "text": "This is the first (of three) Kepler’s laws of planetary motion. 400 years ago Johannes Kepler derived the laws based on long term observations from his and Tycho Brahe’s research. He used a huge amount of manually determined planetary position data that lead him to his conclusions. Imagine being a data scientist with tons of printed Excel sheets, no computer, some mechanical mathematical devices and some patience. No GPU optimization or Cloud Computing. This was a true commitment to science." }, { "code": null, "e": 1373, "s": 881, "text": "But is the Sun really and exclusively in the centre of our Solar System? Considering Newton’s law of mechanic our home planet, asteroids, planets and also the Sun revolve around a common centre of gravity. The Sun contains over 99 % of the Solar System’s mass. So is a possible movement of the so-called Solar System Barycentre (SSB) with respect to the Sun’s centre that significant? We will answer this question today with our Python skills and our SPICE knowledge from the first tutorial." }, { "code": null, "e": 1999, "s": 1373, "text": "Last time we learned about SPICE and its way to compute miscellaneous parameters using so called kernels. We loaded the necessary kernels using the SPICE function furnsh. Each kernel was loaded individually. However, larger projects may require to load dozens of kernels. That would bloat our Python code and one could easily lose track of one’s code. To prevent this, SPICE introduced the kernel meta files. A meta file contains the relative or absolute paths to the needed kernels. For this tutorial, each part has its own meta file that sets the relative path to the _kernels directory. Let’s have a look at the meta file:" }, { "code": null, "e": 2577, "s": 1999, "text": "The first 6 lines start with the command \\begintext. The following text block is a comment section, where one can add up any project relevant information. The last block starts with \\begindata. This indicates SPICE that all following parts are relevant for the coding part. KERNELS_TO_LOAD lists all kernel files that are used in this tutorial part. Please note: If you load kernels that contain similar information (e.g., by accident you load first the naif0012.tls leap seconds kernel and afterwards the naif0011.tls kernel), SPICE considers the order and takes the last one." }, { "code": null, "e": 2835, "s": 2577, "text": "Now we are prepared for our project. First of all, we need to import the necessary modules. If you have not installed NumPy yet, please install it via pip3. We will need it frequently. Then function furnsh is used to load our newly created kernel meta file." }, { "code": null, "e": 3293, "s": 2835, "text": "For the position computation we need to set a starting / initial and ending time-stamp. Here, we set the date 2000–01–01 (midnight) UTC and add up 10,000 days (around 27.5 years; this value is chosen randomly by me). These computations can be done with the Python library datetime. Afterwards, the initial and ending times are converted to strings in line 14 and 15, respectively. Finally, the UTC strings are converted to the corresponding Ephemeris times." }, { "code": null, "e": 3676, "s": 3293, "text": "Why are leap-seconds kernels necessary? A day has 24 hours, a year has 365 days and every 4 years another day is added. This applies to our everyday life. From a detailed scientific point of view our Earth revolves around itself and around the Sun in slightly varying times that need to be compensated. How much time is added in this 10,000 days interval starting at the millennium?" }, { "code": null, "e": 4020, "s": 3676, "text": "A day has 86,400 seconds. This value times 10,000 days leads to 864,000,000 seconds. Subtracting the initial time in ET from the ending time in ET (line 5) leads to 864,000,005.0012845 seconds. Approximately 5 seconds have been added. This is not crucial for our tutorial, but in some high precision scientific fields every millisecond counts." }, { "code": null, "e": 4120, "s": 4020, "text": "We finally set a NumPy array that contains 10,000 time steps between the starting and ending times." }, { "code": null, "e": 4487, "s": 4120, "text": "Now we are ready to compute the Solar System Barycentre (SSB) position in x, y, z direction with respect to the Sun’s centre. For this purpose, we compute the position using the SPICE function spkgps (in the last tutorial we used a similar function spkgeo that returns the state vector (position and velocity)). This function requires the following input parameters:" }, { "code": null, "e": 4644, "s": 4487, "text": "targ: The NAIF ID code of the SSB (0). The sophisticated SPICE documentation lists all available ID codes of the Solar System as well as spacecraft missions" }, { "code": null, "e": 4667, "s": 4644, "text": "et: The Ephemeris time" }, { "code": null, "e": 4822, "s": 4667, "text": "ref: The reference frame of interest. In our case, we compute the position in ECLIPJ2000. So, the ecliptic plane of our home planet is the reference plane" }, { "code": null, "e": 4855, "s": 4822, "text": "obs: The NAIF ID of the Sun (10)" }, { "code": null, "e": 5176, "s": 4855, "text": "spkgps returns the position of the SSB w.r.t. the Sun at a certain Ephemeris time computed in the ECLIPJ2000 reference frame. The second output value is the so called light time and stores the travelling time of the light between the Sun’s centre and the SSB. Since we do not need this value, we use a single underscore." }, { "code": null, "e": 5286, "s": 5176, "text": "Let’s print the result at the initial time point to get a feeling of the x, y, z components and the distance." }, { "code": null, "e": 5315, "s": 5286, "text": "We get the following output:" }, { "code": null, "e": 5568, "s": 5315, "text": "Position (components) of the Solar System Barycentre w.r.t thecentre of the Sun (at initial time): X = 1068000.0 kmY = 417681.0 kmZ = -30845.0 kmDistance between the Solar System Barycentre w.r.t thecentre of the Sun (at initial time): d = 1147185.0 km" }, { "code": null, "e": 5762, "s": 5568, "text": "Well ... we got some large numbers. A distance between the Sun’s centre and the SSB of over 1 Million kilometres (around 3 times the distance between the Earth and the Moon). Is this ... a lot?" }, { "code": null, "e": 6039, "s": 5762, "text": "Comprehending large numbers in astronomy leads mostly to scaling, like e.g., 1 Astronomical Unit (AU) or 1 Light-year. Here, we can define our own scale, by using the radius of the Sun (around 700,000 km). The Sun’s radius can be extracted from the corresponding SPICE kernel." }, { "code": null, "e": 6232, "s": 6039, "text": "Before we go into the programming part we need to answer another question. What is the radius of the Sun? It is somehow connected to the surface, but what is the surface of a huge plasma ball?" }, { "code": null, "e": 6781, "s": 6232, "text": "The answer is complex. Different methods are available for the definition of the Sun’s surface. Helioseismological measurements, time measurements of mercury transits, or coupling the definition of the surface with a certain layer of the Photosphere (where one can observe the convection cells and sunspots) lead to different results. In 2015, the International Astronomical Union set the radius to 695,700 km, period. A slightly shifted value (696,000 km) is stored in the SPICE kernel pck00010.tpc that is loaded in the beginning of our tutorial." }, { "code": null, "e": 6880, "s": 6781, "text": "With the function bodvcd we can extract the radius of the Sun. The function requires 3 parameters:" }, { "code": null, "e": 6916, "s": 6880, "text": "bodyid: The NAIF ID of the Sun (10)" }, { "code": null, "e": 6996, "s": 6916, "text": "item: ‘RADII’ tells the function that we need the radius information of the Sun" }, { "code": null, "e": 7135, "s": 6996, "text": "maxn: The number of expected return parameters. Since we get the radius values of an ellipsoid (x, y, z direction) the number is set to 3." }, { "code": null, "e": 7352, "s": 7135, "text": "The first output parameter represents the number of returned values and is not needed. We use a single underscore to ignore this value. Since all radii values are the same, we use the first entry as the Sun’s radius." }, { "code": null, "e": 7561, "s": 7352, "text": "Now, we can plot the Sun and the trajectory of the SSB. We use matplotlib for this task. We create a 2-dimensional projection of our results and plot only the x-y coordinates (movement on the Ecliptic plane)." }, { "code": null, "e": 7758, "s": 7561, "text": "The following code snippet shows how the plot below is created. We add a yellow circle representing the Sun. Since the distances are scaled w.r.t. the Sun’s radius we can simply use a radius of 1." }, { "code": null, "e": 7934, "s": 7758, "text": "The plot shows the trajectory in blue and one can easily see, that the SSB is not within the Sun all the time (although the Sun contains over 99 % of the Solar System’s mass)!" }, { "code": null, "e": 8018, "s": 7934, "text": "What is the percentage of time the SSB stays outside of the Sun? Let’s have a look:" }, { "code": null, "e": 8063, "s": 8018, "text": "In total: around 65%! An astonishing result." }, { "code": null, "e": 8300, "s": 8063, "text": "I hope you enjoyed today’s lesson. We used some already known SPICE functions from the last tutorial and have deepen our knowledge. We will continue with that and steadily we will build up a “knowledge fundament” for more complex tasks." }, { "code": null, "e": 8764, "s": 8300, "text": "So answering the question from the beginning: Is the Sun in the centre in one of the foci of the orbits? Well it is the barycentre of the Solar System. The Sun is “wobbling” around this centre. Does it mean the Kepler laws are wrong? Well that’s science: You postulate a theory that describes the nature until it is proven wrong or it is improved. For no-high-precision measurements and computer models the Sun can be easily put in the centre of our Solar System." } ]
Predicting Invasive Ductal Carcinoma using Convolutional Neural Network (CNN) in Keras | by Bikram Baruah | Towards Data Science
In this blog, we will learn how to use CNN in a real world histopathology dataset. Real-world data requires a lot more preprocessing than standard datasets such as MNIST, and we will go through the process of making the data ready for classification and then use CNN to classify the images. I will also discuss the CNN architecture used and some of the hyperparameters tuned when building the model. The different sections of this blog are: Introduction Understanding the dataset Loading the dataset Data preprocessing Tackling data imbalance by random undersampling Model architecture Compiling the model Data Augmentation Training the model Making predictions Evaluating the models performance I assume that the reader knows what convolutional neural networks are and the their basic working mechanism. In this blog, we will only discuss the code which is important in the context of deep learning, and also avoid repeated explanation of code used more than once. The Github repository for this post can be found here. I’d suggest you to follow along the Jupyter Notebook while going through this tutorial. Over the past couple of years, there has been a rise in using deep learning for medical image analysis with increasing success. Deep learning in the field of healthcare is used to identify patterns, classify and segment medical images. As with most image related tasks, convolutional neural networks are used to do this. The classification problem tackled here is to classify histopathology slides of Invasive Ductal Carcinoma (IDC) as either malignant or benign. IDC is a type of breast cancer, where the cancer has spread to the surrounding breast tissue. Cancer tumours can be classified into two types: malignant and benign. A benign tumor is one which does not invade its surrounding tissues whereas a malignant tumor is one which may spread to its surrounding tissues or other parts of the body. The dataset we will use can be downloaded here. Scroll down to the Dataset Description section of the page and download the 1.6 GB zip file. The dataset consists of 162 whole mount slide images of breast cancer specimens scanned at 40x. From that,277,524 patches of size 50 x 50 were extracted, out of which 198,738 are IDC negative (benign) and 78,786 are IDC positive (malignant). Each patch’s file name is of the format: u_xX_yY_classC.png → example 10253_idx5_x1351_y1101_class0.png Where u is the patient ID (10253_idx5), X is the x-coordinate of where this patch was cropped from, Y is the y-coordinate of where this patch was cropped from, and C indicates the class where 0 is non-IDC (benign) and 1 is IDC (malignant) imagePatches = glob('C:/Users/asus/Documents/Breast cancer classification/**/*.png', recursive=True)patternZero = '*class0.png'patternOne = '*class1.png'#saves the image file location of all images with file name 'class0' classZero = fnmatch.filter(imagePatches, patternZero) #saves the image file location of all images with file name 'class1'classOne = fnmatch.filter(imagePatches, patternOne) The dataset consists of 279 folders, with sub-folders 0 and 1 inside each of the 279 folders. We first create two variables classZero and classOne, which saves the image locations of all class 0 and class 1 images respectively def process_images(lowerIndex,upperIndex): """ Returns two arrays: x is an array of resized images y is an array of labels """ height = 50 width = 50 channels = 3 x = [] #list to store image data y = [] #list to store corresponding class for img in imagePatches[lowerIndex:upperIndex]: full_size_image = cv2.imread(img) image = (cv2.resize(full_size_image, (width,height), interpolation=cv2.INTER_CUBIC)) x.append(image) if img in classZero: y.append(0) elif img in classOne: y.append(1) else: return return x,y We then create a function process_images which takes as input the starting and end index of the images. This function first reads the image using OpenCV’s cv2.imread() and also resizes the image. Resizing is done because few of the images in the dataset are not 50x50x3. The function returns two arrays: X, which is an array of the resized image data and Y, which is an array of the corresponding labels. X, Y = process_images(0,100000) For this tutorial, we will only analyze images from index 0 to 60,000. The image data (pixel values) are now stored in a list X and their corresponding classes in a list Y. X = np.array(X)X = X.astype(np.float32)X /= 255. The list X is first converted to a numpy array and then casted to the type float32 to save space. The images are first normalized by dividing it by 255. This ensures that all the values are between 0 and 1. This helps us to train the model faster and also prevents us from falling into the vanishing and exploding gradients problem. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.15) The dataset is split into training and test set, with 15% of the entire dataset reserved for testing. For a dataset of 60,000 , this means 51000 images are reserved for training and 9000 for testing. y_train.count(1) #counting the number of 1y_train.count(0) #counting the number of 0 Counting the number of 1’s and 0’s in the array Y, we find that there are 44478 images of class 0 and 15522 images of class 1. This problem is known as data imbalance and can cause our model to be more biased towards one particular class, usually the one which has more samples. Particularly in fields such as healthcare, classifying the minority class (malignant in this case) as majority class (benign in this case) can be very risky. We will deal with data imbalance by randomly undersampling the majority class, i.e removing samples of the majority class to make the number of samples of the majority and minority class equal. y_train = to_categorical(y_train)y_test = to_categorical(y_test) Before that, we need to one-hot-encode the output variable y_train and y_test. X_trainShape = X_train.shape[1]*X_train.shape[2]*X_train.shape[3]X_testShape = X_test.shape[1]*X_test.shape[2]*X_test.shape[3]X_trainFlat = X_train.reshape(X_train.shape[0], X_trainShape)X_testFlat = X_test.reshape(X_test.shape[0], X_testShape) We also need to reshape X_train and X_test to use the Random Under Sampler. from imblearn.under_sampling import RandomUnderSamplerrandom_under_sampler = RandomUnderSampler(ratio='majority')X_trainRos, Y_trainRos = random_under_sampler.fit_sample(X_trainFlat, y_train)X_testRos, Y_testRos = random_under_sampler.fit_sample(X_testFlat, y_test) The parameter ‘ratio=majority’ states the random under sampler to under sample the majority class. Checking the number of samples of each class again after performing random undersampling, we find that we have equal number of samples of both the classes. The image data is then converted back to its original shape of 50 x 50 x 3. We use a similar architecture to the one discussed in this paper. batch_size = 256num_classes = 2epochs = 80model = Sequential()model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(50,50,3)))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(64, (3,3), activation='relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Conv2D(128, (3, 3), activation='relu'))model.add(Conv2D(256, (3, 3), activation='relu'))model.add(Flatten()) #this converts our 3D feature maps to 1D feature vectors for the dense layer belowmodel.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(Dense(num_classes, activation='sigmoid')) The model is a sequential which allows us to create the model layer-by-layer. The architecture consists of convolutional layers, max pooling layers, dropout layers and fully connected layers. The first layer is a convolutional layer with 32 filters each of size 3 x 3. We are also required to specify the input shape in the first layer, which is 50 x 50 x 3 in our case. We will be using the Rectified linear unit (ReLU) activation function for all the layers except the final output layer. ReLU is the most common choice for activation function in the hidden layers and has shown to work pretty well. The second layer is a pooling layer. The pooling layers are used to reduce dimension. Max Pooling with a 2x2 window only considers the maximum value in the 2x2 window. The third layer is again a convolutional layer of 64 filters each of size 3 x 3 followed by another max pooling layer of 2x2 window. Usually, the number of filters in the convolutional layer grows after each layer. The first layers with lower number of filter learns simple features of the images whereas the deeper layers learn more complex features. The next two layers are again convolutional layers with the same filter size but increasing number of filters; 128 and 256. We need to flatten the 3D feature map output from the convolutional layer to 1D feature vectors before adding in the fully connected layers. This is where the flatten layer comes in. The next layer is a dropout layer with a dropout rate of 0.5 . A dropout layer with dropout rate of 0.5 means 50% of the neurons will be turned off randomly. This helps prevent overfitting by making all the neurons learn something about the data and not rely on just a few neurons. Randomly dropping neurons during training means other neurons will have to do the work of the turned-off neurons, thus generalizing better and prevent overfitting. The value 0.5 is taken from the original paper by Hinton (2012), which has proved to be very effective. These dropout layers are added after each of the fully connected layers before the output. Dropout also reduces the training time for each epoch. The following dense layer (fully connected layer) has 128 neurons. This is followed by another dropout layer with a dropout rate of 0.5 The next layer is another dense layer with 128 neurons. The final output layer is another dense layer which has number of neurons equal to the number of classes. The activation function in this layer is sigmoid because the problem in hand is a binary classification problem. For multi-class classification problem, the activation function should be set to softmax. model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(lr=0.00001), metrics=['accuracy']) The model is compiled with binary cross entropy loss function and the Adam optimizer is used. The ‘accuracy’ metric is used to evaluate the model. Adam is an optimization algorithm which updates the network weights in an iterative manner. Although the initial learning rate for Adam can be set (we have set it to 0.00001 in our case), this is the initial learning rate and the learning rate for each parameter is adapted as training begins. This is how Adam (short for adaptive moment estimation) is different from stochastic gradient descent, which maintains a single learning rate for all weight updates. A detailed explanation of the Adam optimization algorithm can be found here The learning rate determines how fast we are adjusting the weights of our network towards the local minima. Too high of a learning rate can result in such high weight changes that it might result in overshooting the local minima. This causes the training or validation error to fluctuate drastically between consecutive epochs. Too low of a learning rate can result in taking longer time to train our network. Thus, the learning rate is one of the most important hyperparameters that needs to be tuned when building the model. datagen = ImageDataGenerator( featurewise_center=True, featurewise_std_normalization=True, rotation_range=180, horizontal_flip=True,vertical_flip = True) Generally, the more data we have, the better deep learning tends to work. Keras ImageDataGenerator generates real time images during training using data augmentation. Transformations are performed on the mini-batches on-the-fly. Data augmentation helps generalize the model by reducing the network’s capacity to overfit the training data. Rotation, vertical and horizontal flipping are some of the common data augmentation techniques used. Keras ImageDataGenerator provides a variety of data augmentation techniques. However, we will only use few of them. A histopathology slide labelled as malignant is still malignant if it is rotated 20 degrees and flipped vertically. Training the model using a GPU speeds up the training process. You will need a NVIDIA GPU to do so. I followed this tutorial to enable GPU training. We set the number of epochs to a high number , in our case 80, and use a regularization method called Early Stopping early_stopping_monitor = EarlyStopping(monitor='val_loss', patience=3, mode='min') Early stopping is a method used to avoid overfitting by stopping the training process when the parameter set to observe does not improve for a certain number of epochs. In our case, we tell EarlyStopping to monitor val_loss and if it does not improve for 3 epochs continuously, stop the training process.” The batch size is usually set to a power of 2 because it is more computationally efficient. We have set it to 256. We use another Keras callback called ModelCheckpoint model_checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', verbose=1, save_best_only=True) Model checkpoint is used to save the model. The monitor parameter allow us to set a metric which we want to keep an eye on. In our case, we only save the model when the validation loss is the minimum. We save the best model to be used later to make predictions and thus evaluate the model’s performance. Combining both these callbacks, the best model (which has the minimum validation loss) is saved and following that, if validation loss does not improve (decrease) over the next 3 epochs (set by EarlyStopping), the model training stops. training = model.fit_generator(datagen.flow(X_trainRosReshaped,Y_trainRosHot,batch_size=batch_size),steps_per_epoch=len(X_trainRosReshaped) / batch_size, epochs=epochs,validation_data=(X_testRosReshaped, Y_testRosHot), verbose=1, callbacks=[early_stopping_monitor, model_checkpoint]) Because we are using ImageDataGenerator on the fly, we use model.fit_generator to train the model. We set it to a variable ‘training’ as we will later plot the training loss and validation loss. This helps us get an idea of the variance, i.e the difference between training error and validation set error. For validation, we will use X_testRosReshaped and Y_testRosHot which we obtained after under-sampling the x_test and y_test set. Training stops after 37 epochs due to Early Stopping. Hence, the best model saved is the one during epoch 34, with a validation accuracy of 79.10% Plotting the training set and validation set loss, we find that the variance is very low. This plot ensures that our model is not overfitting. from keras.models import load_modelfrom sklearn import metricsmodel = load_model('best_model.h5')y_pred_one_hot = model.predict(X_testRosReshaped)y_pred_labels = np.argmax(y_pred_one_hot, axis = 1)y_true_labels = np.argmax(Y_testRosHot,axis=1) We load the best model saved by ModelCheckpoint and use the predict function to predict the classes of the images in the array X_testRosReshaped. The predictions are now stored in the list y_pred_labels. confusion_matrix = metrics.confusion_matrix(y_true=y_true_labels, y_pred=y_pred_labels) We use a confusion matrix to evaluate the models performance. The confusion matrix in a binary classification matrix has four quadrants; false positives, false negatives, true positives and true negatives. For our case, the four quadrants of the confusion matrix can be simplified as follows: The confusion matrix we get is: In cases such as this, having a lower false negative is better than having a lower false positive. This is because identifying a malignant tumour as benign is more dangerous than identifying a benign tumour as malignant, since the former will result in the patient receiving a different treatment due to misdiagnosis, and the latter is likely to go through further tests anyway. We can see that our model performs well with an accuracy of 79.10% on the test set. The confusion matrix only is also favourable for us and we have a model with low variance. Applying deep learning is an iterative process. You can try and improve this model further by tuning the hyperparameters such as learning rate of the optimization algorithm, changing the batch size, changing the filters of the convolutional layers, adding in more layers or using more data. Thanks for reading. If you have any questions, comment them down below. I will be writing regularly on topics such as deep learning, so follow me here on Medium. I am also available on LinkedIn! :) Happy coding.
[ { "code": null, "e": 571, "s": 171, "text": "In this blog, we will learn how to use CNN in a real world histopathology dataset. Real-world data requires a lot more preprocessing than standard datasets such as MNIST, and we will go through the process of making the data ready for classification and then use CNN to classify the images. I will also discuss the CNN architecture used and some of the hyperparameters tuned when building the model." }, { "code": null, "e": 612, "s": 571, "text": "The different sections of this blog are:" }, { "code": null, "e": 625, "s": 612, "text": "Introduction" }, { "code": null, "e": 651, "s": 625, "text": "Understanding the dataset" }, { "code": null, "e": 671, "s": 651, "text": "Loading the dataset" }, { "code": null, "e": 690, "s": 671, "text": "Data preprocessing" }, { "code": null, "e": 738, "s": 690, "text": "Tackling data imbalance by random undersampling" }, { "code": null, "e": 757, "s": 738, "text": "Model architecture" }, { "code": null, "e": 777, "s": 757, "text": "Compiling the model" }, { "code": null, "e": 795, "s": 777, "text": "Data Augmentation" }, { "code": null, "e": 814, "s": 795, "text": "Training the model" }, { "code": null, "e": 833, "s": 814, "text": "Making predictions" }, { "code": null, "e": 867, "s": 833, "text": "Evaluating the models performance" }, { "code": null, "e": 976, "s": 867, "text": "I assume that the reader knows what convolutional neural networks are and the their basic working mechanism." }, { "code": null, "e": 1137, "s": 976, "text": "In this blog, we will only discuss the code which is important in the context of deep learning, and also avoid repeated explanation of code used more than once." }, { "code": null, "e": 1280, "s": 1137, "text": "The Github repository for this post can be found here. I’d suggest you to follow along the Jupyter Notebook while going through this tutorial." }, { "code": null, "e": 1601, "s": 1280, "text": "Over the past couple of years, there has been a rise in using deep learning for medical image analysis with increasing success. Deep learning in the field of healthcare is used to identify patterns, classify and segment medical images. As with most image related tasks, convolutional neural networks are used to do this." }, { "code": null, "e": 1744, "s": 1601, "text": "The classification problem tackled here is to classify histopathology slides of Invasive Ductal Carcinoma (IDC) as either malignant or benign." }, { "code": null, "e": 1838, "s": 1744, "text": "IDC is a type of breast cancer, where the cancer has spread to the surrounding breast tissue." }, { "code": null, "e": 2082, "s": 1838, "text": "Cancer tumours can be classified into two types: malignant and benign. A benign tumor is one which does not invade its surrounding tissues whereas a malignant tumor is one which may spread to its surrounding tissues or other parts of the body." }, { "code": null, "e": 2223, "s": 2082, "text": "The dataset we will use can be downloaded here. Scroll down to the Dataset Description section of the page and download the 1.6 GB zip file." }, { "code": null, "e": 2465, "s": 2223, "text": "The dataset consists of 162 whole mount slide images of breast cancer specimens scanned at 40x. From that,277,524 patches of size 50 x 50 were extracted, out of which 198,738 are IDC negative (benign) and 78,786 are IDC positive (malignant)." }, { "code": null, "e": 2506, "s": 2465, "text": "Each patch’s file name is of the format:" }, { "code": null, "e": 2569, "s": 2506, "text": "u_xX_yY_classC.png → example 10253_idx5_x1351_y1101_class0.png" }, { "code": null, "e": 2808, "s": 2569, "text": "Where u is the patient ID (10253_idx5), X is the x-coordinate of where this patch was cropped from, Y is the y-coordinate of where this patch was cropped from, and C indicates the class where 0 is non-IDC (benign) and 1 is IDC (malignant)" }, { "code": null, "e": 3204, "s": 2808, "text": "imagePatches = glob('C:/Users/asus/Documents/Breast cancer classification/**/*.png', recursive=True)patternZero = '*class0.png'patternOne = '*class1.png'#saves the image file location of all images with file name 'class0' classZero = fnmatch.filter(imagePatches, patternZero) #saves the image file location of all images with file name 'class1'classOne = fnmatch.filter(imagePatches, patternOne)" }, { "code": null, "e": 3431, "s": 3204, "text": "The dataset consists of 279 folders, with sub-folders 0 and 1 inside each of the 279 folders. We first create two variables classZero and classOne, which saves the image locations of all class 0 and class 1 images respectively" }, { "code": null, "e": 4064, "s": 3431, "text": "def process_images(lowerIndex,upperIndex): \"\"\" Returns two arrays: x is an array of resized images y is an array of labels \"\"\" height = 50 width = 50 channels = 3 x = [] #list to store image data y = [] #list to store corresponding class for img in imagePatches[lowerIndex:upperIndex]: full_size_image = cv2.imread(img) image = (cv2.resize(full_size_image, (width,height), interpolation=cv2.INTER_CUBIC)) x.append(image) if img in classZero: y.append(0) elif img in classOne: y.append(1) else: return return x,y" }, { "code": null, "e": 4469, "s": 4064, "text": "We then create a function process_images which takes as input the starting and end index of the images. This function first reads the image using OpenCV’s cv2.imread() and also resizes the image. Resizing is done because few of the images in the dataset are not 50x50x3. The function returns two arrays: X, which is an array of the resized image data and Y, which is an array of the corresponding labels." }, { "code": null, "e": 4501, "s": 4469, "text": "X, Y = process_images(0,100000)" }, { "code": null, "e": 4674, "s": 4501, "text": "For this tutorial, we will only analyze images from index 0 to 60,000. The image data (pixel values) are now stored in a list X and their corresponding classes in a list Y." }, { "code": null, "e": 4723, "s": 4674, "text": "X = np.array(X)X = X.astype(np.float32)X /= 255." }, { "code": null, "e": 4821, "s": 4723, "text": "The list X is first converted to a numpy array and then casted to the type float32 to save space." }, { "code": null, "e": 5056, "s": 4821, "text": "The images are first normalized by dividing it by 255. This ensures that all the values are between 0 and 1. This helps us to train the model faster and also prevents us from falling into the vanishing and exploding gradients problem." }, { "code": null, "e": 5180, "s": 5056, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.15)" }, { "code": null, "e": 5380, "s": 5180, "text": "The dataset is split into training and test set, with 15% of the entire dataset reserved for testing. For a dataset of 60,000 , this means 51000 images are reserved for training and 9000 for testing." }, { "code": null, "e": 5467, "s": 5380, "text": "y_train.count(1) #counting the number of 1y_train.count(0) #counting the number of 0" }, { "code": null, "e": 5594, "s": 5467, "text": "Counting the number of 1’s and 0’s in the array Y, we find that there are 44478 images of class 0 and 15522 images of class 1." }, { "code": null, "e": 6098, "s": 5594, "text": "This problem is known as data imbalance and can cause our model to be more biased towards one particular class, usually the one which has more samples. Particularly in fields such as healthcare, classifying the minority class (malignant in this case) as majority class (benign in this case) can be very risky. We will deal with data imbalance by randomly undersampling the majority class, i.e removing samples of the majority class to make the number of samples of the majority and minority class equal." }, { "code": null, "e": 6163, "s": 6098, "text": "y_train = to_categorical(y_train)y_test = to_categorical(y_test)" }, { "code": null, "e": 6242, "s": 6163, "text": "Before that, we need to one-hot-encode the output variable y_train and y_test." }, { "code": null, "e": 6487, "s": 6242, "text": "X_trainShape = X_train.shape[1]*X_train.shape[2]*X_train.shape[3]X_testShape = X_test.shape[1]*X_test.shape[2]*X_test.shape[3]X_trainFlat = X_train.reshape(X_train.shape[0], X_trainShape)X_testFlat = X_test.reshape(X_test.shape[0], X_testShape)" }, { "code": null, "e": 6563, "s": 6487, "text": "We also need to reshape X_train and X_test to use the Random Under Sampler." }, { "code": null, "e": 6829, "s": 6563, "text": "from imblearn.under_sampling import RandomUnderSamplerrandom_under_sampler = RandomUnderSampler(ratio='majority')X_trainRos, Y_trainRos = random_under_sampler.fit_sample(X_trainFlat, y_train)X_testRos, Y_testRos = random_under_sampler.fit_sample(X_testFlat, y_test)" }, { "code": null, "e": 6928, "s": 6829, "text": "The parameter ‘ratio=majority’ states the random under sampler to under sample the majority class." }, { "code": null, "e": 7160, "s": 6928, "text": "Checking the number of samples of each class again after performing random undersampling, we find that we have equal number of samples of both the classes. The image data is then converted back to its original shape of 50 x 50 x 3." }, { "code": null, "e": 7226, "s": 7160, "text": "We use a similar architecture to the one discussed in this paper." }, { "code": null, "e": 7909, "s": 7226, "text": "batch_size = 256num_classes = 2epochs = 80model = Sequential()model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(50,50,3)))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(64, (3,3), activation='relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Conv2D(128, (3, 3), activation='relu'))model.add(Conv2D(256, (3, 3), activation='relu'))model.add(Flatten()) #this converts our 3D feature maps to 1D feature vectors for the dense layer belowmodel.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(Dense(num_classes, activation='sigmoid'))" }, { "code": null, "e": 8101, "s": 7909, "text": "The model is a sequential which allows us to create the model layer-by-layer. The architecture consists of convolutional layers, max pooling layers, dropout layers and fully connected layers." }, { "code": null, "e": 8280, "s": 8101, "text": "The first layer is a convolutional layer with 32 filters each of size 3 x 3. We are also required to specify the input shape in the first layer, which is 50 x 50 x 3 in our case." }, { "code": null, "e": 8511, "s": 8280, "text": "We will be using the Rectified linear unit (ReLU) activation function for all the layers except the final output layer. ReLU is the most common choice for activation function in the hidden layers and has shown to work pretty well." }, { "code": null, "e": 8679, "s": 8511, "text": "The second layer is a pooling layer. The pooling layers are used to reduce dimension. Max Pooling with a 2x2 window only considers the maximum value in the 2x2 window." }, { "code": null, "e": 9031, "s": 8679, "text": "The third layer is again a convolutional layer of 64 filters each of size 3 x 3 followed by another max pooling layer of 2x2 window. Usually, the number of filters in the convolutional layer grows after each layer. The first layers with lower number of filter learns simple features of the images whereas the deeper layers learn more complex features." }, { "code": null, "e": 9155, "s": 9031, "text": "The next two layers are again convolutional layers with the same filter size but increasing number of filters; 128 and 256." }, { "code": null, "e": 9338, "s": 9155, "text": "We need to flatten the 3D feature map output from the convolutional layer to 1D feature vectors before adding in the fully connected layers. This is where the flatten layer comes in." }, { "code": null, "e": 9784, "s": 9338, "text": "The next layer is a dropout layer with a dropout rate of 0.5 . A dropout layer with dropout rate of 0.5 means 50% of the neurons will be turned off randomly. This helps prevent overfitting by making all the neurons learn something about the data and not rely on just a few neurons. Randomly dropping neurons during training means other neurons will have to do the work of the turned-off neurons, thus generalizing better and prevent overfitting." }, { "code": null, "e": 10034, "s": 9784, "text": "The value 0.5 is taken from the original paper by Hinton (2012), which has proved to be very effective. These dropout layers are added after each of the fully connected layers before the output. Dropout also reduces the training time for each epoch." }, { "code": null, "e": 10170, "s": 10034, "text": "The following dense layer (fully connected layer) has 128 neurons. This is followed by another dropout layer with a dropout rate of 0.5" }, { "code": null, "e": 10226, "s": 10170, "text": "The next layer is another dense layer with 128 neurons." }, { "code": null, "e": 10535, "s": 10226, "text": "The final output layer is another dense layer which has number of neurons equal to the number of classes. The activation function in this layer is sigmoid because the problem in hand is a binary classification problem. For multi-class classification problem, the activation function should be set to softmax." }, { "code": null, "e": 10681, "s": 10535, "text": "model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(lr=0.00001), metrics=['accuracy'])" }, { "code": null, "e": 10828, "s": 10681, "text": "The model is compiled with binary cross entropy loss function and the Adam optimizer is used. The ‘accuracy’ metric is used to evaluate the model." }, { "code": null, "e": 10920, "s": 10828, "text": "Adam is an optimization algorithm which updates the network weights in an iterative manner." }, { "code": null, "e": 11364, "s": 10920, "text": "Although the initial learning rate for Adam can be set (we have set it to 0.00001 in our case), this is the initial learning rate and the learning rate for each parameter is adapted as training begins. This is how Adam (short for adaptive moment estimation) is different from stochastic gradient descent, which maintains a single learning rate for all weight updates. A detailed explanation of the Adam optimization algorithm can be found here" }, { "code": null, "e": 11891, "s": 11364, "text": "The learning rate determines how fast we are adjusting the weights of our network towards the local minima. Too high of a learning rate can result in such high weight changes that it might result in overshooting the local minima. This causes the training or validation error to fluctuate drastically between consecutive epochs. Too low of a learning rate can result in taking longer time to train our network. Thus, the learning rate is one of the most important hyperparameters that needs to be tuned when building the model." }, { "code": null, "e": 12057, "s": 11891, "text": "datagen = ImageDataGenerator( featurewise_center=True, featurewise_std_normalization=True, rotation_range=180, horizontal_flip=True,vertical_flip = True)" }, { "code": null, "e": 12497, "s": 12057, "text": "Generally, the more data we have, the better deep learning tends to work. Keras ImageDataGenerator generates real time images during training using data augmentation. Transformations are performed on the mini-batches on-the-fly. Data augmentation helps generalize the model by reducing the network’s capacity to overfit the training data. Rotation, vertical and horizontal flipping are some of the common data augmentation techniques used." }, { "code": null, "e": 12613, "s": 12497, "text": "Keras ImageDataGenerator provides a variety of data augmentation techniques. However, we will only use few of them." }, { "code": null, "e": 12729, "s": 12613, "text": "A histopathology slide labelled as malignant is still malignant if it is rotated 20 degrees and flipped vertically." }, { "code": null, "e": 12878, "s": 12729, "text": "Training the model using a GPU speeds up the training process. You will need a NVIDIA GPU to do so. I followed this tutorial to enable GPU training." }, { "code": null, "e": 12995, "s": 12878, "text": "We set the number of epochs to a high number , in our case 80, and use a regularization method called Early Stopping" }, { "code": null, "e": 13078, "s": 12995, "text": "early_stopping_monitor = EarlyStopping(monitor='val_loss', patience=3, mode='min')" }, { "code": null, "e": 13247, "s": 13078, "text": "Early stopping is a method used to avoid overfitting by stopping the training process when the parameter set to observe does not improve for a certain number of epochs." }, { "code": null, "e": 13384, "s": 13247, "text": "In our case, we tell EarlyStopping to monitor val_loss and if it does not improve for 3 epochs continuously, stop the training process.”" }, { "code": null, "e": 13499, "s": 13384, "text": "The batch size is usually set to a power of 2 because it is more computationally efficient. We have set it to 256." }, { "code": null, "e": 13552, "s": 13499, "text": "We use another Keras callback called ModelCheckpoint" }, { "code": null, "e": 13668, "s": 13552, "text": "model_checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', verbose=1, save_best_only=True)" }, { "code": null, "e": 13972, "s": 13668, "text": "Model checkpoint is used to save the model. The monitor parameter allow us to set a metric which we want to keep an eye on. In our case, we only save the model when the validation loss is the minimum. We save the best model to be used later to make predictions and thus evaluate the model’s performance." }, { "code": null, "e": 14208, "s": 13972, "text": "Combining both these callbacks, the best model (which has the minimum validation loss) is saved and following that, if validation loss does not improve (decrease) over the next 3 epochs (set by EarlyStopping), the model training stops." }, { "code": null, "e": 14492, "s": 14208, "text": "training = model.fit_generator(datagen.flow(X_trainRosReshaped,Y_trainRosHot,batch_size=batch_size),steps_per_epoch=len(X_trainRosReshaped) / batch_size, epochs=epochs,validation_data=(X_testRosReshaped, Y_testRosHot), verbose=1, callbacks=[early_stopping_monitor, model_checkpoint])" }, { "code": null, "e": 14798, "s": 14492, "text": "Because we are using ImageDataGenerator on the fly, we use model.fit_generator to train the model. We set it to a variable ‘training’ as we will later plot the training loss and validation loss. This helps us get an idea of the variance, i.e the difference between training error and validation set error." }, { "code": null, "e": 14927, "s": 14798, "text": "For validation, we will use X_testRosReshaped and Y_testRosHot which we obtained after under-sampling the x_test and y_test set." }, { "code": null, "e": 15074, "s": 14927, "text": "Training stops after 37 epochs due to Early Stopping. Hence, the best model saved is the one during epoch 34, with a validation accuracy of 79.10%" }, { "code": null, "e": 15217, "s": 15074, "text": "Plotting the training set and validation set loss, we find that the variance is very low. This plot ensures that our model is not overfitting." }, { "code": null, "e": 15461, "s": 15217, "text": "from keras.models import load_modelfrom sklearn import metricsmodel = load_model('best_model.h5')y_pred_one_hot = model.predict(X_testRosReshaped)y_pred_labels = np.argmax(y_pred_one_hot, axis = 1)y_true_labels = np.argmax(Y_testRosHot,axis=1)" }, { "code": null, "e": 15665, "s": 15461, "text": "We load the best model saved by ModelCheckpoint and use the predict function to predict the classes of the images in the array X_testRosReshaped. The predictions are now stored in the list y_pred_labels." }, { "code": null, "e": 15753, "s": 15665, "text": "confusion_matrix = metrics.confusion_matrix(y_true=y_true_labels, y_pred=y_pred_labels)" }, { "code": null, "e": 15959, "s": 15753, "text": "We use a confusion matrix to evaluate the models performance. The confusion matrix in a binary classification matrix has four quadrants; false positives, false negatives, true positives and true negatives." }, { "code": null, "e": 16046, "s": 15959, "text": "For our case, the four quadrants of the confusion matrix can be simplified as follows:" }, { "code": null, "e": 16078, "s": 16046, "text": "The confusion matrix we get is:" }, { "code": null, "e": 16457, "s": 16078, "text": "In cases such as this, having a lower false negative is better than having a lower false positive. This is because identifying a malignant tumour as benign is more dangerous than identifying a benign tumour as malignant, since the former will result in the patient receiving a different treatment due to misdiagnosis, and the latter is likely to go through further tests anyway." }, { "code": null, "e": 16632, "s": 16457, "text": "We can see that our model performs well with an accuracy of 79.10% on the test set. The confusion matrix only is also favourable for us and we have a model with low variance." }, { "code": null, "e": 16923, "s": 16632, "text": "Applying deep learning is an iterative process. You can try and improve this model further by tuning the hyperparameters such as learning rate of the optimization algorithm, changing the batch size, changing the filters of the convolutional layers, adding in more layers or using more data." } ]
Spring Boot Kafka Producer Example | Spring Boot KafkaTemplate
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see how to publish Kafka messages with Spring Boot Kafka Producer. As part of this example, we will see how to publish a simple string message to Kafka topic. Spring Boot 2.1.3 Spring Kafka Java 8 Maven Install Apache Kafka on your machine, follow below articles to install Kafka. Install Apache Kafka on Windows 10 Operating system Install Apache Kafka on Ubuntu Operating system root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties [2019-03-28 00:22:52,195] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2019-03-28 00:22:52,210] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,210] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,211] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-28 00:22:52,211] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain) root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties [2019-03-28 00:24:08,203] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$) [2019-03-28 00:24:09,146] INFO starting (kafka.server.KafkaServer) [2019-03-28 00:24:09,147] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer) [2019-03-28 00:24:09,219] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient) [2019-03-28 00:24:09,229] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper) root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic hello-topic Created topic "hello-topic". root@work:/usr/local/kafka/bin# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic hello-topic --from-beginning On the above pre-requisites session, we have started zookeeper, Kafka server and created one hello-topic and also started Kafka consumer console. Now we are going to push some messages to hello-topic through Spring boot application using KafkaTemplate and we will monitor these messages from Kafka consumer console. dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> </dependencies> Sending simple string messages to Kafka topic. package com.onlinetutorialspoint.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("producer") public class HelloController { @Autowired KafkaTemplate<String,String> template; String TOPIC_NAME = "hello-topic"; @GetMapping("/say/{msg}") public String postMessage(@PathVariable("msg") String msg){ template.send(TOPIC_NAME,msg); return "Message published successfully"; } } package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootKafkaProducerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootKafkaProducerApplication.class, args); } } $ mvn clean install $ mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE) 2019-03-28 00:32:13.814 INFO 15921 --- [ main] c.o.SpringBootKafkaProducerApplication : Starting SpringBootKafkaProducerApplication on work with PID 15921 (/home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer) ..... ..... Spring Boot Kafka KafkaTemplate Happy Learning 🙂 Spring-Boot-Kafka-Producer File size: 89 KB Downloads: 708 Spring Boot How to change the Tomcat to Jetty Server Spring Boot RabbitMQ Message Publishing Example Sending Spring Boot Kafka JSON Message to Kafka Topic Step By Step Spring Boot Docker Deployment Example Spring Boot Redis Cache Example – Redis Server SSL Spring Boot HTTPs Enabling Example Spring Boot Kafka Consume JSON Messages Example Install Apache Kafka on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials How to Send Mail Spring Boot Example How to set Spring Boot SetTimeZone How to use Spring Boot Random Port MicroServices Spring Boot Eureka Server Example Spring Boot How to change the Tomcat to Jetty Server Spring Boot RabbitMQ Message Publishing Example Sending Spring Boot Kafka JSON Message to Kafka Topic Step By Step Spring Boot Docker Deployment Example Spring Boot Redis Cache Example – Redis Server SSL Spring Boot HTTPs Enabling Example Spring Boot Kafka Consume JSON Messages Example Install Apache Kafka on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials How to Send Mail Spring Boot Example How to set Spring Boot SetTimeZone How to use Spring Boot Random Port MicroServices Spring Boot Eureka Server Example Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 499, "s": 398, "text": "In this tutorial, we are going to see how to publish Kafka messages with Spring Boot Kafka Producer." }, { "code": null, "e": 591, "s": 499, "text": "As part of this example, we will see how to publish a simple string message to Kafka topic." }, { "code": null, "e": 609, "s": 591, "text": "Spring Boot 2.1.3" }, { "code": null, "e": 622, "s": 609, "text": "Spring Kafka" }, { "code": null, "e": 629, "s": 622, "text": "Java 8" }, { "code": null, "e": 635, "s": 629, "text": "Maven" }, { "code": null, "e": 713, "s": 635, "text": "Install Apache Kafka on your machine, follow below articles to install Kafka." }, { "code": null, "e": 765, "s": 713, "text": "Install Apache Kafka on Windows 10 Operating system" }, { "code": null, "e": 813, "s": 765, "text": "Install Apache Kafka on Ubuntu Operating system" }, { "code": null, "e": 1556, "s": 813, "text": "root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties \n[2019-03-28 00:22:52,195] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2019-03-28 00:22:52,210] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,210] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,211] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-28 00:22:52,211] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)\n" }, { "code": null, "e": 2242, "s": 1556, "text": "root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties \n[2019-03-28 00:24:08,203] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)\n[2019-03-28 00:24:09,146] INFO starting (kafka.server.KafkaServer)\n[2019-03-28 00:24:09,147] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer)\n[2019-03-28 00:24:09,219] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient)\n[2019-03-28 00:24:09,229] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper)\n" }, { "code": null, "e": 2416, "s": 2242, "text": "root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic hello-topic\nCreated topic \"hello-topic\".\n" }, { "code": null, "e": 2548, "s": 2416, "text": "root@work:/usr/local/kafka/bin# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic hello-topic --from-beginning\n" }, { "code": null, "e": 2694, "s": 2548, "text": "On the above pre-requisites session, we have started zookeeper, Kafka server and created one hello-topic and also started Kafka consumer console." }, { "code": null, "e": 2864, "s": 2694, "text": "Now we are going to push some messages to hello-topic through Spring boot application using KafkaTemplate and we will monitor these messages from Kafka consumer console." }, { "code": null, "e": 3148, "s": 2864, "text": "dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka</artifactId>\n </dependency>\n</dependencies>" }, { "code": null, "e": 3195, "s": 3148, "text": "Sending simple string messages to Kafka topic." }, { "code": null, "e": 3773, "s": 3195, "text": "package com.onlinetutorialspoint.controller;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.kafka.core.KafkaTemplate;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\n@RequestMapping(\"producer\")\npublic class HelloController {\n\n @Autowired\n KafkaTemplate<String,String> template;\n String TOPIC_NAME = \"hello-topic\";\n\n @GetMapping(\"/say/{msg}\")\n public String postMessage(@PathVariable(\"msg\") String msg){\n template.send(TOPIC_NAME,msg);\n return \"Message published successfully\";\n }\n}\n" }, { "code": null, "e": 4129, "s": 3773, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootKafkaProducerApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootKafkaProducerApplication.class, args);\n }\n\n}\n" }, { "code": null, "e": 4820, "s": 4129, "text": "$ mvn clean install\n$ mvn spring-boot:run\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.3.RELEASE)\n\n2019-03-28 00:32:13.814 INFO 15921 --- [ main] c.o.SpringBootKafkaProducerApplication : Starting SpringBootKafkaProducerApplication on work with PID 15921 (/home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer)\n.....\n....." }, { "code": null, "e": 4840, "s": 4822, "text": "Spring Boot Kafka" }, { "code": null, "e": 4854, "s": 4840, "text": "KafkaTemplate" }, { "code": null, "e": 4871, "s": 4854, "text": "Happy Learning 🙂" }, { "code": null, "e": 4934, "s": 4871, "text": "\n\nSpring-Boot-Kafka-Producer\n\nFile size: 89 KB\nDownloads: 708\n" }, { "code": null, "e": 5586, "s": 4934, "text": "\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot RabbitMQ Message Publishing Example\nSending Spring Boot Kafka JSON Message to Kafka Topic\nStep By Step Spring Boot Docker Deployment Example\nSpring Boot Redis Cache Example – Redis Server\nSSL Spring Boot HTTPs Enabling Example\nSpring Boot Kafka Consume JSON Messages Example\nInstall Apache Kafka on Windows 10\nHow to install Apache Kafka on Ubuntu 18.04\nSpring Boot MongoDB + Spring Data Example\nSpring Boot MVC Example Tutorials\nHow to Send Mail Spring Boot Example\nHow to set Spring Boot SetTimeZone\nHow to use Spring Boot Random Port\nMicroServices Spring Boot Eureka Server Example\n" }, { "code": null, "e": 5639, "s": 5586, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 5687, "s": 5639, "text": "Spring Boot RabbitMQ Message Publishing Example" }, { "code": null, "e": 5741, "s": 5687, "text": "Sending Spring Boot Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 5792, "s": 5741, "text": "Step By Step Spring Boot Docker Deployment Example" }, { "code": null, "e": 5839, "s": 5792, "text": "Spring Boot Redis Cache Example – Redis Server" }, { "code": null, "e": 5878, "s": 5839, "text": "SSL Spring Boot HTTPs Enabling Example" }, { "code": null, "e": 5926, "s": 5878, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 5961, "s": 5926, "text": "Install Apache Kafka on Windows 10" }, { "code": null, "e": 6005, "s": 5961, "text": "How to install Apache Kafka on Ubuntu 18.04" }, { "code": null, "e": 6047, "s": 6005, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 6081, "s": 6047, "text": "Spring Boot MVC Example Tutorials" }, { "code": null, "e": 6118, "s": 6081, "text": "How to Send Mail Spring Boot Example" }, { "code": null, "e": 6153, "s": 6118, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 6188, "s": 6153, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 6236, "s": 6188, "text": "MicroServices Spring Boot Eureka Server Example" }, { "code": null, "e": 6242, "s": 6240, "text": "Δ" }, { "code": null, "e": 6269, "s": 6242, "text": " Spring Boot – Hello World" }, { "code": null, "e": 6296, "s": 6269, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 6330, "s": 6296, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 6371, "s": 6330, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 6416, "s": 6371, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 6454, "s": 6416, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 6488, "s": 6454, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 6519, "s": 6488, "text": " Spring Boot – Properties File" }, { "code": null, "e": 6553, "s": 6519, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 6586, "s": 6553, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 6619, "s": 6586, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 6659, "s": 6619, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 6684, "s": 6659, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 6715, "s": 6684, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 6739, "s": 6715, "text": " Spring Boot – Actuator" }, { "code": null, "e": 6785, "s": 6739, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 6808, "s": 6785, "text": " Spring Boot – Swagger" }, { "code": null, "e": 6835, "s": 6808, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 6881, "s": 6835, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 6921, "s": 6881, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 6950, "s": 6921, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 6984, "s": 6950, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 7014, "s": 6984, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 7050, "s": 7014, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 7083, "s": 7050, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 7116, "s": 7083, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 7160, "s": 7116, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 7194, "s": 7160, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 7226, "s": 7194, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 7254, "s": 7226, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 7285, "s": 7254, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 7326, "s": 7285, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 7360, "s": 7326, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 7385, "s": 7360, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 7419, "s": 7385, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 7455, "s": 7419, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 7501, "s": 7455, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 7552, "s": 7501, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 7594, "s": 7552, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 7625, "s": 7594, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 7648, "s": 7625, "text": " Spring Boot – EhCache" }, { "code": null, "e": 7678, "s": 7648, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 7708, "s": 7678, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 7757, "s": 7708, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 7791, "s": 7757, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 7824, "s": 7791, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 7853, "s": 7824, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 7885, "s": 7853, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 7922, "s": 7885, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 7951, "s": 7922, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 7980, "s": 7951, "text": " Spring Boot – MockMvc JUnit" } ]
PHP String Data Type
In PHP, a string data type is a non-numeric sequence of charaters.Any character in the ASCII set can be a part of a string. PHP doesn't support UNICODE. In PHP, literal representation of string can be done with single quotes, double quotes, with heredoc syntax and nowdoc syntax. //Literal assignment of string value to variable $var='Hello World'; //Single quotes $var3="Hello World"; //Double quotes To embed single quote character inside single quoted string prefix it with '\'. Similarly to embed backslash in single quoted string prefix it with additional backslash. Other escape sequence characters such as \n etc. do not carry any special representation. Double quoted string treats following escape sequences with their special meaning as follows: The Heredoc string starts with <<< symbol followed by any identifier of user's choice. From next line, any multiline sequence of characters that may be having any of the above escape sequences. Last line should have same heredoc identifier ending with semicolon. //Heredoc assignment of string value to variable public $var = <<< XYZ Hello World Welcome to Tutorialspoint XYZ; Nowdoc strings are similar to heredoc strings. Difference is that identifier must be enclosed in single quotes and escape sequences inside nowdoc string are not parsed and appear as it is. //Nowdoc assignment of string value to variable public $var = <<< 'XYZ' Hello World Welcome to Tutorialspoint XYZ; Use of separation symbol "_" is avilable since PHP 7.40 Following example shows single quoted string. The escape sequence \n is not parsed and appears as it is Live Demo <?php $var = 'Hello World.\n Welcome to Tutorialspoint'; echo $var; ?> This will produce following result − Hello World.\n Welcome to Tutorialspoint This Example double quoted string. The escape sequence \n is parsed and text appears in two lines Live Demo <?php $var = "Hello World.\n Welcome to Tutorialspoint"; echo $var; ?> This will produce following result − Hello World. Welcome to Tutorialspoint This example shows how to use Heredoc and Nowdoc syntax for string representation Live Demo <?php //Heredoc $var = <<< STR Hello World Welcome to Tutorialspoint STR; echo $var . "\n"; //Nowdoc $var = <<< 'STR' Hello World Welcome to Tutorialspoint STR; echo $var; ?> This will produce following result − Hello World Welcome to Tutorialspoint Hello World Welcome to Tutorialspoint This Example shows values of a variable is substiuted in heredoc string. Nowdoc string doesn't make substitution Live Demo <?php $name = "Mahesh"; $var = <<< STR Hello $name Welcome to Tutorialspoint STR; echo $var . "\n"; //Nowdoc $var = <<<'STR' Hello $name Welcome to Tutorialspoint STR; echo $var; ?> This will produce following result − Hello Mahesh Welcome to Tutorialspoint Hello $name Welcome to Tutorialspoint
[ { "code": null, "e": 1215, "s": 1062, "text": "In PHP, a string data type is a non-numeric sequence of charaters.Any character in the ASCII set can be a part of a string. PHP doesn't support UNICODE." }, { "code": null, "e": 1342, "s": 1215, "text": "In PHP, literal representation of string can be done with single quotes, double quotes, with heredoc syntax and nowdoc syntax." }, { "code": null, "e": 1464, "s": 1342, "text": "//Literal assignment of string value to variable\n$var='Hello World'; //Single quotes\n$var3=\"Hello World\"; //Double quotes" }, { "code": null, "e": 1724, "s": 1464, "text": "To embed single quote character inside single quoted string prefix it with '\\'. Similarly to embed backslash in single quoted string prefix it with additional backslash. Other escape sequence characters such as \\n etc. do not carry any special representation." }, { "code": null, "e": 1818, "s": 1724, "text": "Double quoted string treats following escape sequences with their special meaning as follows:" }, { "code": null, "e": 2081, "s": 1818, "text": "The Heredoc string starts with <<< symbol followed by any identifier of user's choice. From next line, any multiline sequence of characters that may be having any of the above escape sequences. Last line should have same heredoc identifier ending with semicolon." }, { "code": null, "e": 2195, "s": 2081, "text": "//Heredoc assignment of string value to variable\npublic $var = <<< XYZ\nHello World\nWelcome to Tutorialspoint\nXYZ;" }, { "code": null, "e": 2384, "s": 2195, "text": "Nowdoc strings are similar to heredoc strings. Difference is that identifier must be enclosed in single quotes and escape sequences inside nowdoc string are not parsed and appear as it is." }, { "code": null, "e": 2499, "s": 2384, "text": "//Nowdoc assignment of string value to variable\npublic $var = <<< 'XYZ'\nHello World\nWelcome to Tutorialspoint\nXYZ;" }, { "code": null, "e": 2555, "s": 2499, "text": "Use of separation symbol \"_\" is avilable since PHP 7.40" }, { "code": null, "e": 2659, "s": 2555, "text": "Following example shows single quoted string. The escape sequence \\n is not parsed and appears as it is" }, { "code": null, "e": 2670, "s": 2659, "text": " Live Demo" }, { "code": null, "e": 2741, "s": 2670, "text": "<?php\n$var = 'Hello World.\\n Welcome to Tutorialspoint';\necho $var;\n?>" }, { "code": null, "e": 2778, "s": 2741, "text": "This will produce following result −" }, { "code": null, "e": 2819, "s": 2778, "text": "Hello World.\\n Welcome to Tutorialspoint" }, { "code": null, "e": 2917, "s": 2819, "text": "This Example double quoted string. The escape sequence \\n is parsed and text appears in two lines" }, { "code": null, "e": 2928, "s": 2917, "text": " Live Demo" }, { "code": null, "e": 2999, "s": 2928, "text": "<?php\n$var = \"Hello World.\\n Welcome to Tutorialspoint\";\necho $var;\n?>" }, { "code": null, "e": 3036, "s": 2999, "text": "This will produce following result −" }, { "code": null, "e": 3075, "s": 3036, "text": "Hello World.\nWelcome to Tutorialspoint" }, { "code": null, "e": 3157, "s": 3075, "text": "This example shows how to use Heredoc and Nowdoc syntax for string representation" }, { "code": null, "e": 3168, "s": 3157, "text": " Live Demo" }, { "code": null, "e": 3343, "s": 3168, "text": "<?php\n//Heredoc\n$var = <<< STR\nHello World\nWelcome to Tutorialspoint\nSTR;\necho $var . \"\\n\";\n//Nowdoc\n$var = <<< 'STR'\nHello World\nWelcome to Tutorialspoint\nSTR;\necho $var;\n?>" }, { "code": null, "e": 3380, "s": 3343, "text": "This will produce following result −" }, { "code": null, "e": 3456, "s": 3380, "text": "Hello World\nWelcome to Tutorialspoint\nHello World\nWelcome to Tutorialspoint" }, { "code": null, "e": 3569, "s": 3456, "text": "This Example shows values of a variable is substiuted in heredoc string. Nowdoc string doesn't make substitution" }, { "code": null, "e": 3580, "s": 3569, "text": " Live Demo" }, { "code": null, "e": 3762, "s": 3580, "text": "<?php\n$name = \"Mahesh\";\n$var = <<< STR\nHello $name\nWelcome to Tutorialspoint\nSTR;\necho $var . \"\\n\";\n//Nowdoc\n$var = <<<'STR'\nHello $name\nWelcome to Tutorialspoint\nSTR;\necho $var;\n?>" }, { "code": null, "e": 3799, "s": 3762, "text": "This will produce following result −" }, { "code": null, "e": 3876, "s": 3799, "text": "Hello Mahesh\nWelcome to Tutorialspoint\nHello $name\nWelcome to Tutorialspoint" } ]
Get all rows in a Pandas DataFrame containing given substring - GeeksforGeeks
24 Dec, 2018 Let’s see how to get all rows in a Pandas DataFrame containing given substring with the help of different examples. Code #1: Check the values PG in column Position # importing pandas import pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5'])print(df, "\n") print("Check PG values in Position column:\n")df1 = df['Position'].str.contains("PG")print(df1) Output: But this result doesn’t seem very helpful, as it returns the bool values with the index. Let’s see if we can do something better. Code #2: Getting the rows satisfying condition # importing pandas as pdimport pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) df1 = df[df['Position'].str.contains("PG")]print(df1) Output: Code #3: Filter all rows where either Team contains ‘Boston’ or College contains ‘MIT’. # importing pandasimport pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) df1 = df[df['Team'].str.contains("Boston") | df['College'].str.contains('MIT')]print(df1) Output: Code #4: Filter rows checking Team name contains ‘Boston and Position must be PG. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df1 = df[df['Team'].str.contains('Boston') & df['Position'].str.contains('PG')]df1 Output: Code #5: Filter rows checking Position contains PG and College must contains like UC. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df1 = df[df['Position'].str.contains("PG") & df['College'].str.contains('UC')]df1 Output: pandas-dataframe-program Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe 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 Print lists in Python (4 Different Ways) How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24465, "s": 24437, "text": "\n24 Dec, 2018" }, { "code": null, "e": 24581, "s": 24465, "text": "Let’s see how to get all rows in a Pandas DataFrame containing given substring with the help of different examples." }, { "code": null, "e": 24629, "s": 24581, "text": "Code #1: Check the values PG in column Position" }, { "code": "# importing pandas import pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5'])print(df, \"\\n\") print(\"Check PG values in Position column:\\n\")df1 = df['Position'].str.contains(\"PG\")print(df1)", "e": 25452, "s": 24629, "text": null }, { "code": null, "e": 25460, "s": 25452, "text": "Output:" }, { "code": null, "e": 25591, "s": 25460, "text": "But this result doesn’t seem very helpful, as it returns the bool values with the index. Let’s see if we can do something better. " }, { "code": null, "e": 25638, "s": 25591, "text": "Code #2: Getting the rows satisfying condition" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) df1 = df[df['Position'].str.contains(\"PG\")]print(df1)", "e": 26409, "s": 25638, "text": null }, { "code": null, "e": 26417, "s": 26409, "text": "Output:" }, { "code": null, "e": 26507, "s": 26419, "text": "Code #3: Filter all rows where either Team contains ‘Boston’ or College contains ‘MIT’." }, { "code": "# importing pandasimport pandas as pd # Creating the dataframe with dict of listsdf = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'], 'Position': ['PG', 'PG', 'UG', 'PG', 'UG'], 'Number': [3, 4, 7, 11, 5], 'Age': [33, 25, 34, 35, 28], 'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'], 'Weight': [89, 79, 113, 78, 84], 'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'], 'Salary': [99999, 99994, 89999, 78889, 87779]}, index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) df1 = df[df['Team'].str.contains(\"Boston\") | df['College'].str.contains('MIT')]print(df1)", "e": 27310, "s": 26507, "text": null }, { "code": null, "e": 27400, "s": 27310, "text": "Output: Code #4: Filter rows checking Team name contains ‘Boston and Position must be PG." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df1 = df[df['Team'].str.contains('Boston') & df['Position'].str.contains('PG')]df1", "e": 27636, "s": 27400, "text": null }, { "code": null, "e": 27645, "s": 27636, "text": "Output: " }, { "code": null, "e": 27731, "s": 27645, "text": "Code #5: Filter rows checking Position contains PG and College must contains like UC." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df1 = df[df['Position'].str.contains(\"PG\") & df['College'].str.contains('UC')]df1", "e": 27966, "s": 27731, "text": null }, { "code": null, "e": 27975, "s": 27966, "text": "Output: " }, { "code": null, "e": 28000, "s": 27975, "text": "pandas-dataframe-program" }, { "code": null, "e": 28014, "s": 28000, "text": "Python-pandas" }, { "code": null, "e": 28021, "s": 28014, "text": "Python" }, { "code": null, "e": 28119, "s": 28021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28128, "s": 28119, "text": "Comments" }, { "code": null, "e": 28141, "s": 28128, "text": "Old Comments" }, { "code": null, "e": 28163, "s": 28141, "text": "Enumerate() in Python" }, { "code": null, "e": 28195, "s": 28163, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28237, "s": 28195, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28262, "s": 28237, "text": "sum() function in Python" }, { "code": null, "e": 28299, "s": 28262, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28355, "s": 28299, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28384, "s": 28355, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28417, "s": 28384, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 28458, "s": 28417, "text": "Print lists in Python (4 Different Ways)" } ]
script.aculo.us - Sorting Elements
Many times, you need to provide the user with the ability to reorder elements (such as items in a list) by dragging them. Without drag and drop, reordering can be a nightmare, but script.aculo.us provides extended reordering support out of the box through the Sortable class. The element to become Sortable is passed to the create() method in the Sortable namespace. A Sortable consists of item elements in a container element. When you create a new Sortable, it takes care of the creation of the corresponding Draggables and Droppables. To use script.aculo.us's Sortable capabilities, you'll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look like this − <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script> Here is the syntax of the create() method to create a sortable item. The create() method takes the id of a container element and sorts them out based on the passed options. Sortable.create('id_of_container',[options]); Use Sortable.destroy to completely remove all the event handlers and references to a Sortable created by Sortable.create. NOTE − A call to Sortable.create, implicitly calls on Sortable.destroy if the referenced element was already a Sortable. Here is the simple syntax to call the destroy function. Sortable.destroy( element ); You can use one or more of the following options while creating your Sortable object. tag Specifies the type of the elements within the sortable container that are to be sortable via drag and drop. Defaults to 'li'. only Specifies a CSS class name, or array of class names, that a draggable item must posses in order to be accepted by the drop target. This is similar to the accept option of Draggable. By default, no class name constraints are applied. overlap One of false, horizontal or vertical. Controls the point at which a reordering is triggered. Defaults to vertical. constraint One of false, horizontal or vertical. Constrains the movement of dragged sortable elements. Defaults to vertical. containment Enables dragging and dropping between Sortables. Takes an array of elements or element-ids. Important note: To ensure that two way dragging between containers is possible, place all Sortable.create calls after the container elements. handle Same as the Draggable option of the same name, specifying an element to be used to initiate drag operations. By default, each element is its own handle. hoverclass ghosting Similar to the Draggable option of the same name, If true, this option causes the original element of a drag operation to stay in place while a semi-transparent copy of the element is moved along with the mouse pointer. Defaults to false. This option does not work with IE. dropOnEmpty If true, it allows sortable elements to be dropped onto an empty list. Defaults to false. scroll If the sortable container possesses a scrollbar due to the setting of the CSS overflow attribute, this option enables auto-scrolling of the list beyond the visible elements. Defaults to false. scrollSensitivity When scrolling is enabled, it adjusts the point at which scrolling is triggered. Defaults to 20. scrollSpeed When scrolling is enabled, it adjusts the scroll speed. Defaults to 15. tree If true, it enables sorting with sub-elements within the sortable element. Defaults to false. treeTag If the tree option is enabled, it specifies the container element type of the sub-element whose children takes part in the sortable behavior. Defaults to 'ul'. You can provide the following callbacks in the options parameter: onChange A function that will be called upon whenever the sort order changes while dragging. When dragging from one Sortable to another, the callback is called once on each Sortable. Gets the affected element as its parameter. onUpdate A function that will be called upon the termination of a drag operation that results in a change in element order. This demo has been verified to work in IE 6.0. It also works in the latest version of Firefox. <html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create('namelist',{tag:'li'}); } </script> <style type = "text/css"> li { cursor: move; } </style> </head> <body> <p>Drag and drop list items to sort them out</p> <ul id = "namelist"> <li>Physics</li> <li>Chemistry</li> <li>Maths</li> <li>Botany</li> <li>Sociology</li> <li>English</li> <li>Hindi</li> <li>Sanskrit</li> </ul> </body> </html> Use our online compiler for a better understanding of the code with different options discussed in the above table. This will produce following result − Drag and drop list items to sort them out Physics Chemistry Maths Botany Sociology English Hindi Sanskrit Note the usage of tag:'li'. Similarly, you can sort the following list of images available in <div> − <html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create('imagelist',{tag:'div'}); } </script> <style type = "text/css"> div { cursor: move; } img { border: 1px solid red; margin:5px; } </style> </head> <body> <p>Drag and drop list images to re-arrange them</p> <div id = "imagelist"> <div><img src = "/images/wml_logo.gif" alt="WML Logo" /></div> <div><img src = "/images/javascript.gif" alt="JS" /></div> <div><img src = "/images/html.gif" alt="HTML" /></div> <div><img src = "/images/css.gif" alt="CSS" /></div> </div> </body> </html> This will produce following result − Drag and drop list images to re-arrange them The Sortable object also provides a function Sortable.serialize() to serialize the Sortable in a format suitable for HTTP GET or POST requests. This can be used to submit the order of the Sortable via an Ajax call. Sortable.serialize(element, options); You can use one or more of the following options while creating your Sortable object. tag Sets the kind of tag that will be serialized. This will be similar to what is used in Sortable.create. name Sets the name of the key that will be used to create the key/value pairs for serializing in HTTP GET/POST format. So if the name were to be xyz, the query string would look like − xyz[]=value1 & xyz[]=value2 & xyz[]=value3 Where the values are derived from the child elements in the order that they appear within the container. In this example, the output of the serialization will only give the numbers after the underscore in the list item IDs. To try, leave the lists in their original order, press the button to see the serialization of the lists. Now, re-order some elements and click the button again. <html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create('namelist',{tag:'li'}); } function serialize(container, name){ $('display').innerHTML = 'Serialization of ' + $(container).id + ' is: <br/><pre>' + Sortable.serialize( container,{ name:name} ) + '</pre>'; } </script> <style type = "text/css"> li { cursor: move; } </style> </head> <body> <p>Drag and drop list items to sort them out properly</p> <ul id = "namelist"> <li id = "list1_1">Physics</li> <li id = "list1_2">Chemistry</li> <li id = "list1_3">Maths</li> <li id = "list1_4">Botany</li> <li id = "list1_5">Sociology</li> <li id = "list1_6">English</li> </ul> <p>Click following button to see serialized list which can be passed to backend script, like PHP, AJAX or CGI</p> <button type = "button" value = "Click Me" onclick = "serialize('namelist', 'list')"> Serialize </button> <div id = "display" style = "clear:both;padding-top:32px"></div> </body> </html> This will produce following result − Drag and drop list items to sort them out properly Physics Chemistry Maths Botany Sociology English Click following button to see serialized list which can be passed to backend script, like PHP, AJAX or CGI The following example shows how to move items from one list to another list. <html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create('List1', {containment: ['List1','List2'], dropOnEmpty: true}); Sortable.create('List2', {containment: ['List1','List2'], dropOnEmpty: true}); } </script> <style type = "text/css"> li { cursor: move; } ul { width: 88px; border: 1px solid blue; padding: 3px 3px 3px 20px; } </style> </head> <body> <p>Drag and drop list items from one list to another list</p> <div style = "float:left"> <ul id = "List1"> <li>Physics</li> <li>Chemistry</li> <li>Botany</li> </ul> </div> <div style = "float:left;margin-left:32px"> <ul id = "List2"> <li>Arts</li> <li>Politics</li> <li>Economics</li> <li>History</li> <li>Sociology</li> </ul> </div> </body> </html> Note that the containment option for each container lists both the containers as containment elements. By doing so, we have enabled the child elements to be sorted within the context of their parent; It also enables them to be moved between the two containers. We set dropOnEmpty to true for both the lists. To see the effect this option has on that list, move all the elements from one list into other so that one list is empty. You will find that it is allowing to drop element on empty list. This will produce following result − Drag and drop list items from one list to another list Physics Chemistry Botany Arts Politics Economics History Sociology Of course, onUpdate is a prime candidate for triggering Ajax notifications to the server, for instance when the user reorders a to-do list or some other data set. Combining Ajax.Request and Sortable.serialize makes live persistence simple enough − <html> <head> <title>Sorting Example</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script> <script type = "text/javascript"> window.onload = function() { Sortable.create('List' , { onUpdate: function() { new Ajax.Request('file.php', { method: "post", parameters: {data:Sortable.serialize('List')} } ); } } ); } </script> <style type = "text/css"> li { cursor: move; } ul { width: 88px; border: 1px solid blue; padding: 3px 3px 3px 20px; } </style> </head> <body> <p>When you will change the order, AJAX Request will be made automatically.</p> <div style = "float:left"> <ul id = "List"> <li id = "List_1">Physics</li> <li id = "List_2">Chemistry</li> <li id = "List_3">Maths</li> <li id = "List_4">Botany</li> </ul> </div> </body> </html> Sortable.serialize creates a string like: List[] = 1 & List[] = 2 & List[] = 3 &List[] = 4, where the numbers are the identifier parts of the list element ids after the underscore. Now we need to code file.php, which will parse posted data as parse_str($_POST['data']); and you can do whatever you want to do with this sorted data. To learn more about AJAX, please go through our simple Ajax Tutorial. Print Add Notes Bookmark this page
[ { "code": null, "e": 1990, "s": 1868, "text": "Many times, you need to provide the user with the ability to reorder elements (such as items in a list) by dragging them." }, { "code": null, "e": 2235, "s": 1990, "text": "Without drag and drop, reordering can be a nightmare, but script.aculo.us provides extended reordering support out of the box through the Sortable class. The element to become Sortable is passed to the create() method in the Sortable namespace." }, { "code": null, "e": 2406, "s": 2235, "text": "A Sortable consists of item elements in a container element. When you create a new Sortable, it takes care of the creation of the corresponding Draggables and Droppables." }, { "code": null, "e": 2601, "s": 2406, "text": "To use script.aculo.us's Sortable capabilities, you'll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look like this −" }, { "code": null, "e": 2783, "s": 2601, "text": "<script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n<script type = \"text/javascript\" src = \"/javascript/scriptaculous.js?load = effects,dragdrop\"></script>\n" }, { "code": null, "e": 2956, "s": 2783, "text": "Here is the syntax of the create() method to create a sortable item. The create() method takes the id of a container element and sorts them out based on the passed options." }, { "code": null, "e": 3003, "s": 2956, "text": "Sortable.create('id_of_container',[options]);\n" }, { "code": null, "e": 3125, "s": 3003, "text": "Use Sortable.destroy to completely remove all the event handlers and references to a Sortable created by Sortable.create." }, { "code": null, "e": 3302, "s": 3125, "text": "NOTE − A call to Sortable.create, implicitly calls on Sortable.destroy if the referenced element was already a Sortable. Here is the simple syntax to call the destroy function." }, { "code": null, "e": 3332, "s": 3302, "text": "Sortable.destroy( element );\n" }, { "code": null, "e": 3418, "s": 3332, "text": "You can use one or more of the following options while creating your Sortable object." }, { "code": null, "e": 3422, "s": 3418, "text": "tag" }, { "code": null, "e": 3548, "s": 3422, "text": "Specifies the type of the elements within the sortable container that are to be sortable via drag and drop. Defaults to 'li'." }, { "code": null, "e": 3553, "s": 3548, "text": "only" }, { "code": null, "e": 3786, "s": 3553, "text": "Specifies a CSS class name, or array of class names, that a draggable item must posses in order to be accepted by the drop target. This is similar to the accept option of Draggable. By default, no class name constraints are applied." }, { "code": null, "e": 3794, "s": 3786, "text": "overlap" }, { "code": null, "e": 3909, "s": 3794, "text": "One of false, horizontal or vertical. Controls the point at which a reordering is triggered. Defaults to vertical." }, { "code": null, "e": 3920, "s": 3909, "text": "constraint" }, { "code": null, "e": 4034, "s": 3920, "text": "One of false, horizontal or vertical. Constrains the movement of dragged sortable elements. Defaults to vertical." }, { "code": null, "e": 4046, "s": 4034, "text": "containment" }, { "code": null, "e": 4280, "s": 4046, "text": "Enables dragging and dropping between Sortables. Takes an array of elements or element-ids. Important note: To ensure that two way dragging between containers is possible, place all Sortable.create calls after the container elements." }, { "code": null, "e": 4287, "s": 4280, "text": "handle" }, { "code": null, "e": 4440, "s": 4287, "text": "Same as the Draggable option of the same name, specifying an element to be used to initiate drag operations. By default, each element is its own handle." }, { "code": null, "e": 4451, "s": 4440, "text": "hoverclass" }, { "code": null, "e": 4460, "s": 4451, "text": "ghosting" }, { "code": null, "e": 4734, "s": 4460, "text": "Similar to the Draggable option of the same name, If true, this option causes the original element of a drag operation to stay in place while a semi-transparent copy of the element is moved along with the mouse pointer. Defaults to false. This option does not work with IE." }, { "code": null, "e": 4746, "s": 4734, "text": "dropOnEmpty" }, { "code": null, "e": 4836, "s": 4746, "text": "If true, it allows sortable elements to be dropped onto an empty list. Defaults to false." }, { "code": null, "e": 4843, "s": 4836, "text": "scroll" }, { "code": null, "e": 5036, "s": 4843, "text": "If the sortable container possesses a scrollbar due to the setting of the CSS overflow attribute, this option enables auto-scrolling of the list beyond the visible elements. Defaults to false." }, { "code": null, "e": 5054, "s": 5036, "text": "scrollSensitivity" }, { "code": null, "e": 5151, "s": 5054, "text": "When scrolling is enabled, it adjusts the point at which scrolling is triggered. Defaults to 20." }, { "code": null, "e": 5163, "s": 5151, "text": "scrollSpeed" }, { "code": null, "e": 5235, "s": 5163, "text": "When scrolling is enabled, it adjusts the scroll speed. Defaults to 15." }, { "code": null, "e": 5240, "s": 5235, "text": "tree" }, { "code": null, "e": 5334, "s": 5240, "text": "If true, it enables sorting with sub-elements within the sortable element. Defaults to false." }, { "code": null, "e": 5342, "s": 5334, "text": "treeTag" }, { "code": null, "e": 5502, "s": 5342, "text": "If the tree option is enabled, it specifies the container element type of the sub-element whose children takes part in the sortable behavior. Defaults to 'ul'." }, { "code": null, "e": 5568, "s": 5502, "text": "You can provide the following callbacks in the options parameter:" }, { "code": null, "e": 5577, "s": 5568, "text": "onChange" }, { "code": null, "e": 5795, "s": 5577, "text": "A function that will be called upon whenever the sort order changes while dragging. When dragging from one Sortable to another, the callback is called once on each Sortable. Gets the affected element as its parameter." }, { "code": null, "e": 5804, "s": 5795, "text": "onUpdate" }, { "code": null, "e": 5919, "s": 5804, "text": "A function that will be called upon the termination of a drag operation that results in a change in element order." }, { "code": null, "e": 6014, "s": 5919, "text": "This demo has been verified to work in IE 6.0. It also works in the latest version of Firefox." }, { "code": null, "e": 6824, "s": 6014, "text": "<html>\n <head>\n <title>Sorting Example</title>\n\t\t\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n <script type = \"text/javascript\" src = \"/javascript/scriptaculous.js\"></script>\n\t\t\n <script type = \"text/javascript\">\n window.onload = function() {\n Sortable.create('namelist',{tag:'li'});\n }\n </script>\n\n <style type = \"text/css\">\n li { cursor: move; }\n </style>\n </head>\n \n <body>\n <p>Drag and drop list items to sort them out</p>\n\n <ul id = \"namelist\">\n <li>Physics</li>\n <li>Chemistry</li>\n <li>Maths</li>\n <li>Botany</li>\n <li>Sociology</li>\n <li>English</li>\n <li>Hindi</li>\n <li>Sanskrit</li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 6940, "s": 6824, "text": "Use our online compiler for a better understanding of the code with different options discussed in the above table." }, { "code": null, "e": 6977, "s": 6940, "text": "This will produce following result −" }, { "code": null, "e": 7019, "s": 6977, "text": "Drag and drop list items to sort them out" }, { "code": null, "e": 7027, "s": 7019, "text": "Physics" }, { "code": null, "e": 7037, "s": 7027, "text": "Chemistry" }, { "code": null, "e": 7043, "s": 7037, "text": "Maths" }, { "code": null, "e": 7050, "s": 7043, "text": "Botany" }, { "code": null, "e": 7060, "s": 7050, "text": "Sociology" }, { "code": null, "e": 7068, "s": 7060, "text": "English" }, { "code": null, "e": 7074, "s": 7068, "text": "Hindi" }, { "code": null, "e": 7083, "s": 7074, "text": "Sanskrit" }, { "code": null, "e": 7185, "s": 7083, "text": "Note the usage of tag:'li'. Similarly, you can sort the following list of images available in <div> −" }, { "code": null, "e": 8111, "s": 7185, "text": "<html>\n <head>\n <title>Sorting Example</title>\n\t\t\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n <script type = \"text/javascript\" src = \"/javascript/scriptaculous.js\"></script>\n\t\t\n <script type = \"text/javascript\">\n window.onload = function() {\n Sortable.create('imagelist',{tag:'div'});\n }\n </script>\n\n <style type = \"text/css\">\n div { cursor: move; }\n img { border: 1px solid red; margin:5px; }\n </style>\n </head>\n\n <body>\n <p>Drag and drop list images to re-arrange them</p>\n\n <div id = \"imagelist\">\n <div><img src = \"/images/wml_logo.gif\" alt=\"WML Logo\" /></div>\n <div><img src = \"/images/javascript.gif\" alt=\"JS\" /></div>\n <div><img src = \"/images/html.gif\" alt=\"HTML\" /></div>\n <div><img src = \"/images/css.gif\" alt=\"CSS\" /></div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 8148, "s": 8111, "text": "This will produce following result −" }, { "code": null, "e": 8193, "s": 8148, "text": "Drag and drop list images to re-arrange them" }, { "code": null, "e": 8408, "s": 8193, "text": "The Sortable object also provides a function Sortable.serialize() to serialize the Sortable in a format suitable for HTTP GET or POST requests. This can be used to submit the order of the Sortable via an Ajax call." }, { "code": null, "e": 8447, "s": 8408, "text": "Sortable.serialize(element, options);\n" }, { "code": null, "e": 8533, "s": 8447, "text": "You can use one or more of the following options while creating your Sortable object." }, { "code": null, "e": 8537, "s": 8533, "text": "tag" }, { "code": null, "e": 8640, "s": 8537, "text": "Sets the kind of tag that will be serialized. This will be similar to what is used in Sortable.create." }, { "code": null, "e": 8645, "s": 8640, "text": "name" }, { "code": null, "e": 8825, "s": 8645, "text": "Sets the name of the key that will be used to create the key/value pairs for serializing in HTTP GET/POST format. So if the name were to be xyz, the query string would look like −" }, { "code": null, "e": 8868, "s": 8825, "text": "xyz[]=value1 & xyz[]=value2 & xyz[]=value3" }, { "code": null, "e": 8973, "s": 8868, "text": "Where the values are derived from the child elements in the order that they appear within the container." }, { "code": null, "e": 9092, "s": 8973, "text": "In this example, the output of the serialization will only give the numbers after the underscore in the list item IDs." }, { "code": null, "e": 9253, "s": 9092, "text": "To try, leave the lists in their original order, press the button to see the serialization of the lists. Now, re-order some elements and click the button again." }, { "code": null, "e": 10710, "s": 9253, "text": "<html>\n <head>\n <title>Sorting Example</title>\n\t\t\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n <script type = \"text/javascript\" src = \"/javascript/scriptaculous.js\"></script>\n\t\t\n <script type = \"text/javascript\">\n window.onload = function() {\n Sortable.create('namelist',{tag:'li'});\n }\n\n function serialize(container, name){\n $('display').innerHTML = 'Serialization of ' + \n $(container).id + \n ' is: <br/><pre>' + \n Sortable.serialize( container,{ name:name} ) + \n '</pre>';\n }\n </script>\n\n <style type = \"text/css\">\n li { cursor: move; }\n </style>\t\n </head>\n\n <body>\n <p>Drag and drop list items to sort them out properly</p>\n\n <ul id = \"namelist\">\n <li id = \"list1_1\">Physics</li>\n <li id = \"list1_2\">Chemistry</li>\n <li id = \"list1_3\">Maths</li>\n <li id = \"list1_4\">Botany</li>\n <li id = \"list1_5\">Sociology</li>\n <li id = \"list1_6\">English</li>\n </ul>\n\n <p>Click following button to see serialized list which can be\n passed to backend script, like PHP, AJAX or CGI</p>\n\t\t\t\n <button type = \"button\" value = \"Click Me\" \n onclick = \"serialize('namelist', 'list')\"> Serialize\n </button>\n\n <div id = \"display\" style = \"clear:both;padding-top:32px\"></div>\n </body>\n</html>" }, { "code": null, "e": 10747, "s": 10710, "text": "This will produce following result −" }, { "code": null, "e": 10798, "s": 10747, "text": "Drag and drop list items to sort them out properly" }, { "code": null, "e": 10806, "s": 10798, "text": "Physics" }, { "code": null, "e": 10816, "s": 10806, "text": "Chemistry" }, { "code": null, "e": 10822, "s": 10816, "text": "Maths" }, { "code": null, "e": 10829, "s": 10822, "text": "Botany" }, { "code": null, "e": 10839, "s": 10829, "text": "Sociology" }, { "code": null, "e": 10847, "s": 10839, "text": "English" }, { "code": null, "e": 10963, "s": 10847, "text": "Click following button to see serialized list which can be\n passed to backend script, like PHP, AJAX or CGI" }, { "code": null, "e": 11040, "s": 10963, "text": "The following example shows how to move items from one list to another list." }, { "code": null, "e": 12300, "s": 11040, "text": "<html>\n <head>\n <title>Sorting Example</title>\n\t\t\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n <script type = \"text/javascript\" src = \"/javascript/scriptaculous.js\"></script>\n\t\t\n <script type = \"text/javascript\">\n window.onload = function() {\n Sortable.create('List1', {containment: ['List1','List2'], dropOnEmpty: true});\n\n Sortable.create('List2', {containment: ['List1','List2'], dropOnEmpty: true});\n }\n </script>\n\n <style type = \"text/css\">\n li { cursor: move; }\n ul {\n width: 88px;\n border: 1px solid blue;\n padding: 3px 3px 3px 20px;\n }\n </style>\t\t\n </head>\n\n <body>\n <p>Drag and drop list items from one list to another list</p>\n\n <div style = \"float:left\">\n <ul id = \"List1\">\n <li>Physics</li>\n <li>Chemistry</li>\n <li>Botany</li>\n </ul>\n </div>\n\n <div style = \"float:left;margin-left:32px\">\n <ul id = \"List2\">\n <li>Arts</li>\n <li>Politics</li>\n <li>Economics</li>\n <li>History</li>\n <li>Sociology</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 12561, "s": 12300, "text": "Note that the containment option for each container lists both the containers as containment elements. By doing so, we have enabled the child elements to be sorted within the context of their parent; It also enables them to be moved between the two containers." }, { "code": null, "e": 12795, "s": 12561, "text": "We set dropOnEmpty to true for both the lists. To see the effect this option has on that list, move all the elements from one list into other so that one list is empty. You will find that it is allowing to drop element on empty list." }, { "code": null, "e": 12832, "s": 12795, "text": "This will produce following result −" }, { "code": null, "e": 12887, "s": 12832, "text": "Drag and drop list items from one list to another list" }, { "code": null, "e": 12895, "s": 12887, "text": "Physics" }, { "code": null, "e": 12905, "s": 12895, "text": "Chemistry" }, { "code": null, "e": 12912, "s": 12905, "text": "Botany" }, { "code": null, "e": 12917, "s": 12912, "text": "Arts" }, { "code": null, "e": 12926, "s": 12917, "text": "Politics" }, { "code": null, "e": 12936, "s": 12926, "text": "Economics" }, { "code": null, "e": 12944, "s": 12936, "text": "History" }, { "code": null, "e": 12954, "s": 12944, "text": "Sociology" }, { "code": null, "e": 13202, "s": 12954, "text": "Of course, onUpdate is a prime candidate for triggering Ajax notifications to the server, for instance when the user reorders a to-do list or some other data set. Combining Ajax.Request and Sortable.serialize makes live persistence simple enough −" }, { "code": null, "e": 14527, "s": 13202, "text": "<html>\n <head>\n <title>Sorting Example</title>\n\t\t\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n <script type = \"text/javascript\" src = \"/javascript/scriptaculous.js\"></script>\n \n <script type = \"text/javascript\">\n window.onload = function() {\n Sortable.create('List' ,\n {\n onUpdate: function() {\n new Ajax.Request('file.php',\n {\n method: \"post\",\n parameters: {data:Sortable.serialize('List')}\n }\n );\n }\n }\n );\n }\n </script>\n\n <style type = \"text/css\">\n li { cursor: move; }\n ul {\n width: 88px;\n border: 1px solid blue;\n padding: 3px 3px 3px 20px;\n }\n </style>\n </head>\n\n <body>\n <p>When you will change the order, AJAX Request \n will be made automatically.</p>\n\n <div style = \"float:left\">\n <ul id = \"List\">\n <li id = \"List_1\">Physics</li>\n <li id = \"List_2\">Chemistry</li>\n <li id = \"List_3\">Maths</li>\n <li id = \"List_4\">Botany</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 14708, "s": 14527, "text": "Sortable.serialize creates a string like: List[] = 1 & List[] = 2 & List[] = 3 &List[] = 4, where the numbers are the identifier parts of the list element ids after the underscore." }, { "code": null, "e": 14859, "s": 14708, "text": "Now we need to code file.php, which will parse posted data as parse_str($_POST['data']); and you can do whatever you want to do with this sorted data." }, { "code": null, "e": 14929, "s": 14859, "text": "To learn more about AJAX, please go through our simple Ajax Tutorial." }, { "code": null, "e": 14936, "s": 14929, "text": " Print" }, { "code": null, "e": 14947, "s": 14936, "text": " Add Notes" } ]
Replace 0 with null in MySQL?
You can use NULLIF() from MySQL to replace 0 with NULL. The syntax is as follows − SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table Replace0WithNULLDemo -> ( -> Id int NOT NULL auto_increment, -> Name varchar(20), -> Marks int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.53 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86); Query OK, 1 row affected (0.20 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0); Query OK, 1 row affected (0.17 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98); Query OK, 1 row affected (0.19 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0); Query OK, 1 row affected (0.17 sec) Display records from the table using select statement. The query is as follows − mysql> select *from Replace0WithNULLDemo; The following is the output − +----+-------+-------+ | Id | Name | Marks | +----+-------+-------+ | 1 | John | 76 | | 2 | Carol | 86 | | 3 | Sam | 0 | | 4 | Mike | 0 | | 5 | Larry | 98 | | 6 | Bob | 0 | +----+-------+-------+ 6 rows in set (0.00 sec) Let us now replace 0 with NULL. The query is as follows − mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo; The following is the output displaying a new column wherein new have replaced 0 with NULL − +----+-------+-------+---------------------+ | Id | Name | Marks | ReplaceZeroWithNULL | +----+-------+-------+---------------------+ | 1 | John | 76 | 76 | | 2 | Carol | 86 | 86 | | 3 | Sam | 0 | NULL | | 4 | Mike | 0 | NULL | | 5 | Larry | 98 | 98 | | 6 | Bob | 0 | NULL | +----+-------+-------+---------------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1145, "s": 1062, "text": "You can use NULLIF() from MySQL to replace 0 with NULL. The syntax is as follows −" }, { "code": null, "e": 1218, "s": 1145, "text": "SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName;" }, { "code": null, "e": 1317, "s": 1218, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1513, "s": 1317, "text": "mysql> create table Replace0WithNULLDemo\n -> (\n -> Id int NOT NULL auto_increment,\n -> Name varchar(20),\n -> Marks int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1606, "s": 1513, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2250, "s": 1606, "text": "mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2331, "s": 2250, "text": "Display records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2373, "s": 2331, "text": "mysql> select *from Replace0WithNULLDemo;" }, { "code": null, "e": 2403, "s": 2373, "text": "The following is the output −" }, { "code": null, "e": 2658, "s": 2403, "text": "+----+-------+-------+\n| Id | Name | Marks |\n+----+-------+-------+\n| 1 | John | 76 |\n| 2 | Carol | 86 |\n| 3 | Sam | 0 |\n| 4 | Mike | 0 |\n| 5 | Larry | 98 |\n| 6 | Bob | 0 |\n+----+-------+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2716, "s": 2658, "text": "Let us now replace 0 with NULL. The query is as follows −" }, { "code": null, "e": 2798, "s": 2716, "text": "mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo;" }, { "code": null, "e": 2890, "s": 2798, "text": "The following is the output displaying a new column wherein new have replaced 0 with NULL −" }, { "code": null, "e": 3365, "s": 2890, "text": "+----+-------+-------+---------------------+\n| Id | Name | Marks | ReplaceZeroWithNULL |\n+----+-------+-------+---------------------+\n| 1 | John | 76 | 76 |\n| 2 | Carol | 86 | 86 |\n| 3 | Sam | 0 | NULL |\n| 4 | Mike | 0 | NULL |\n| 5 | Larry | 98 | 98 |\n| 6 | Bob | 0 | NULL |\n+----+-------+-------+---------------------+\n6 rows in set (0.00 sec)" } ]
Creating 3D Plots in R Programming - persp() Function - GeeksforGeeks
10 Dec, 2021 3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot. The persp() function which is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane. persp() is defines as a generic function. Moreover, it can be used to superimpose additional graphical elements on the 3D plot, by lines() or points(), using the function trans3d(). Syntax: persp(x, y, z) Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z. Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t). R # To illustrate simple right circular conecone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surfacepersp(x, y, z) Output: Here in the above code, function seq() to generate a vector of equally spaced numbers. The outer() function to apply the function cone at every combination of x and y. Python3 # Adding Titles and Labeling Axes to Plotcone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surface# Adding Titles and Labeling Axes to Plotpersp(x, y, z,main="Perspective Plot of a Cone",zlab = "Height",theta = 30, phi = 15,col = "orange", shade = 0.4) Output: Here in the above code, xlab, ylab, and zlab can be used to label the three axes. Theta and phi are viewing direction. Python3 # Visualizing a simple DEM model z <- 2 * volcano # Exaggerate the reliefx <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W) # Don't draw the grid lines : border = NApar(bg = "gray")persp(x, y, z, theta = 135, phi = 30, col = "brown", scale = FALSE, ltheta = -120, shade = 0.75, border = NA, box = FALSE) Output: kumar_satyam R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n10 Dec, 2021" }, { "code": null, "e": 25293, "s": 24851, "text": "3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot. The persp() function which is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane. persp() is defines as a generic function. Moreover, it can be used to superimpose additional graphical elements on the 3D plot, by lines() or points(), using the function trans3d()." }, { "code": null, "e": 25316, "s": 25293, "text": "Syntax: persp(x, y, z)" }, { "code": null, "e": 25513, "s": 25316, "text": "Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z." }, { "code": null, "e": 25682, "s": 25513, "text": "Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t)." }, { "code": null, "e": 25684, "s": 25682, "text": "R" }, { "code": "# To illustrate simple right circular conecone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surfacepersp(x, y, z)", "e": 25882, "s": 25684, "text": null }, { "code": null, "e": 25890, "s": 25882, "text": "Output:" }, { "code": null, "e": 26058, "s": 25890, "text": "Here in the above code, function seq() to generate a vector of equally spaced numbers. The outer() function to apply the function cone at every combination of x and y." }, { "code": null, "e": 26066, "s": 26058, "text": "Python3" }, { "code": "# Adding Titles and Labeling Axes to Plotcone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surface# Adding Titles and Labeling Axes to Plotpersp(x, y, z,main=\"Perspective Plot of a Cone\",zlab = \"Height\",theta = 30, phi = 15,col = \"orange\", shade = 0.4)", "e": 26403, "s": 26066, "text": null }, { "code": null, "e": 26412, "s": 26403, "text": "Output: " }, { "code": null, "e": 26531, "s": 26412, "text": "Here in the above code, xlab, ylab, and zlab can be used to label the three axes. Theta and phi are viewing direction." }, { "code": null, "e": 26539, "s": 26531, "text": "Python3" }, { "code": "# Visualizing a simple DEM model z <- 2 * volcano # Exaggerate the reliefx <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W) # Don't draw the grid lines : border = NApar(bg = \"gray\")persp(x, y, z, theta = 135, phi = 30, col = \"brown\", scale = FALSE, ltheta = -120, shade = 0.75, border = NA, box = FALSE)", "e": 26909, "s": 26539, "text": null }, { "code": null, "e": 26918, "s": 26909, "text": "Output: " }, { "code": null, "e": 26931, "s": 26918, "text": "kumar_satyam" }, { "code": null, "e": 26939, "s": 26931, "text": "R-plots" }, { "code": null, "e": 26950, "s": 26939, "text": "R Language" }, { "code": null, "e": 27048, "s": 26950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27057, "s": 27048, "text": "Comments" }, { "code": null, "e": 27070, "s": 27057, "text": "Old Comments" }, { "code": null, "e": 27122, "s": 27070, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27160, "s": 27122, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27195, "s": 27160, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27253, "s": 27195, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27302, "s": 27253, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27345, "s": 27302, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27395, "s": 27345, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27412, "s": 27395, "text": "R - if statement" }, { "code": null, "e": 27449, "s": 27412, "text": "How to import an Excel File into R ?" } ]
SoapUI - Request & Response
Here, we will perform the conversion of the currency from INR to USD. FromCurrency – INR ToCurrency – USD Next, enter these inputs in the place of the question mark which will be sent as a request XML. After placing those values into the corresponding XML tags, click 'Submit request' button to check the response. Upon submitting a request, the web service request is processed by the web-server and sends back a response as shown in the following screenshot. By reading the response, it can be concluded that 1 unit of INR = 0.0147 units of USD. SOAP messages are transported by HTTP protocol. To view the HTTP request, click RAW at SoapUI Request window (left side). The Request is posted to the web-server. Hence, the POST method of Http is used. The SOAP Request is transported in the body of the http message, which is shown as follows. POST http://www.webservicex.com/currencyconvertor.asmx HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset = UTF-8 SOAPAction: "http://www.webserviceX.NET/ConversionRate" Content-Length: 353 Host: www.webservicex.com Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) Click the 'RAW' Tab in SOAP-UI Response Window to understand how the response is sent via HTTP. After processing the request, the http response code (200) is shown which means it is a success. The web-server has processed it successfully. The SOAP response is sent back to the client as part of the body of the HTTP message. HTTP/1.1 200 OK Cache-Control: private, max-age = 0 Content-Type: text/xml; charset = utf-8 Content-Encoding: gzip Vary: Accept-Encoding Server: Microsoft-IIS/7.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 22 Jan 2017 19:39:31 GMT Content-Length: 316 Following HTTP codes are used to send in responses by the Web-server and are very useful for debugging. 1xx: Informational − This means a request was received and there is a continuing process. 2xx: Success − The action was successfully received, understood, and accepted. 3xx: Redirection − This means further action must be taken in order to complete the request. 4xx: Client Error − This means the request contains a bad syntax or cannot be fulfilled. 5xx: Server Error − The server failed to fulfil an apparently valid request. Print Add Notes Bookmark this page
[ { "code": null, "e": 2204, "s": 2134, "text": "Here, we will perform the conversion of the currency from INR to USD." }, { "code": null, "e": 2223, "s": 2204, "text": "FromCurrency – INR" }, { "code": null, "e": 2240, "s": 2223, "text": "ToCurrency – USD" }, { "code": null, "e": 2449, "s": 2240, "text": "Next, enter these inputs in the place of the question mark which will be sent as a request XML. After placing those values into the corresponding XML tags, click 'Submit request' button to check the response." }, { "code": null, "e": 2595, "s": 2449, "text": "Upon submitting a request, the web service request is processed by the web-server and sends back a response as shown in the following screenshot." }, { "code": null, "e": 2682, "s": 2595, "text": "By reading the response, it can be concluded that 1 unit of INR = 0.0147 units of USD." }, { "code": null, "e": 2804, "s": 2682, "text": "SOAP messages are transported by HTTP protocol. To view the HTTP request, click RAW at SoapUI Request window (left side)." }, { "code": null, "e": 2885, "s": 2804, "text": "The Request is posted to the web-server. Hence, the POST method of Http is used." }, { "code": null, "e": 2977, "s": 2885, "text": "The SOAP Request is transported in the body of the http message, which is shown as follows." }, { "code": null, "e": 3291, "s": 2977, "text": "POST http://www.webservicex.com/currencyconvertor.asmx HTTP/1.1 \nAccept-Encoding: gzip,deflate \nContent-Type: text/xml;charset = UTF-8 \nSOAPAction: \"http://www.webserviceX.NET/ConversionRate\" \nContent-Length: 353 \nHost: www.webservicex.com \nConnection: Keep-Alive \nUser-Agent: Apache-HttpClient/4.1.1 (java 1.5) \n" }, { "code": null, "e": 3387, "s": 3291, "text": "Click the 'RAW' Tab in SOAP-UI Response Window to understand how the response is sent via HTTP." }, { "code": null, "e": 3530, "s": 3387, "text": "After processing the request, the http response code (200) is shown which means it is a success. The web-server has processed it successfully." }, { "code": null, "e": 3616, "s": 3530, "text": "The SOAP response is sent back to the client as part of the body of the HTTP message." }, { "code": null, "e": 3896, "s": 3616, "text": "HTTP/1.1 200 OK \nCache-Control: private, max-age = 0 \nContent-Type: text/xml; charset = utf-8 \nContent-Encoding: gzip \nVary: Accept-Encoding \nServer: Microsoft-IIS/7.0 \nX-AspNet-Version: 4.0.30319 \nX-Powered-By: ASP.NET \nDate: Sun, 22 Jan 2017 19:39:31 GMT \nContent-Length: 316 \n" }, { "code": null, "e": 4000, "s": 3896, "text": "Following HTTP codes are used to send in responses by the Web-server and are very useful for debugging." }, { "code": null, "e": 4005, "s": 4000, "text": "1xx:" }, { "code": null, "e": 4090, "s": 4005, "text": "Informational − This means a request was received and there is a continuing process." }, { "code": null, "e": 4095, "s": 4090, "text": "2xx:" }, { "code": null, "e": 4169, "s": 4095, "text": "Success − The action was successfully received, understood, and accepted." }, { "code": null, "e": 4174, "s": 4169, "text": "3xx:" }, { "code": null, "e": 4262, "s": 4174, "text": "Redirection − This means further action must be taken in order to complete the request." }, { "code": null, "e": 4267, "s": 4262, "text": "4xx:" }, { "code": null, "e": 4351, "s": 4267, "text": "Client Error − This means the request contains a bad syntax or cannot be fulfilled." }, { "code": null, "e": 4356, "s": 4351, "text": "5xx:" }, { "code": null, "e": 4428, "s": 4356, "text": "Server Error − The server failed to fulfil an apparently valid request." }, { "code": null, "e": 4435, "s": 4428, "text": " Print" }, { "code": null, "e": 4446, "s": 4435, "text": " Add Notes" } ]
C# | Math.Log() Method - GeeksforGeeks
31 Jan, 2019 In C#, Math.Log() is a Math class method. It is used to return the logarithm of a specified number. This method can be overloaded by changing the number of the arguments passed. There are total 2 methods in the overload list of the Math.Log() method as follows: Math.Log(Double) Method Math.Log(Double, Double) Method This method is used to return the natural (base e) logarithm of a specified number. Syntax: public static double Log(double val) Parameter: val: It is the specified number whose natural (base e) logarithm to be calculated and its type is System.Double. Return Value: Returns the natural logarithm of val and its type is System.Double. Note: Parameter val is always specified as a base 10 number.The return value is depend on the argument passed. Below are some cases: If the argument is positive then method will return the natural logarithm or loge(val). If the argument is zero, then the result is NegativeInfinity. If the argument is Negative(less than zero) or equal to NaN, then the result is NaN. If the argument is PositiveInfinity, then the result is PositiveInfinity. If the argument is NegativeInfinity, then the result is NaN. Example: // C# program to demonstrate working// of Math.Log(Double) methodusing System; class Geeks { // Main Method public static void Main(String[] args) { // double values whose logarithm // to be calculated double a = 4.55; double b = 0; double c = -2.45; double nan = Double.NaN; double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; // Input is positive number so output // will be logarithm of number Console.WriteLine(Math.Log(a)); // positive zero as argument, so output // will be -Infinity Console.WriteLine(Math.Log(b)); // Input is negative number so output // will be NaN Console.WriteLine(Math.Log(c)); // Input is NaN so output // will be NaN Console.WriteLine(Math.Log(nan)); // Input is PositiveInfinity so output // will be Infinity Console.WriteLine(Math.Log(positiveInfinity)); // Input is NegativeInfinity so output // will be NaN Console.WriteLine(Math.Log(negativeInfinity)); }} 1.51512723296286 -Infinity NaN NaN Infinity NaN This method is used to return the logarithm of a specified number in a specified base. Syntax: public static double Log(double val, double base) Parameter: val: It is the specified number whose logarithm to be calculated and its type is System.Double. base: It is the base of the logarithm of type System.Double. Return Value: It returns the logarithm of val and its type is System.Double. Note: The return value is always depend on the argument passed. Below table depicts the different cases: Example: // C# program to demonstrate working// of Math.Log(Double, Double) methodusing System; class Geeks { // Main Method public static void Main(String[] args) { // Here val = 1.3 and base is 0.3 then // output will be logarithm of given value Console.WriteLine(Math.Log(1.3, 0.3)); // Here val is 0.5 and base > 1 then output // will be -0.5 Console.WriteLine(Math.Log(0.5, 4)); // Here val is 0.7 and base = 1 then output // will be NaN Console.WriteLine(Math.Log(0.7, 1)); // Here val is 0.7 and base is NaN then output // will be NaN Console.WriteLine(Math.Log(0.7, Double.NaN)); }} -0.217915440884381 -0.5 NaN NaN References: https://msdn.microsoft.com/en-us/library/x80ywz41(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/hd50b6h5(v=vs.110).aspx CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | Constructors Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object Introduction to .NET Framework
[ { "code": null, "e": 24394, "s": 24366, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24656, "s": 24394, "text": "In C#, Math.Log() is a Math class method. It is used to return the logarithm of a specified number. This method can be overloaded by changing the number of the arguments passed. There are total 2 methods in the overload list of the Math.Log() method as follows:" }, { "code": null, "e": 24680, "s": 24656, "text": "Math.Log(Double) Method" }, { "code": null, "e": 24712, "s": 24680, "text": "Math.Log(Double, Double) Method" }, { "code": null, "e": 24796, "s": 24712, "text": "This method is used to return the natural (base e) logarithm of a specified number." }, { "code": null, "e": 24804, "s": 24796, "text": "Syntax:" }, { "code": null, "e": 24841, "s": 24804, "text": "public static double Log(double val)" }, { "code": null, "e": 24852, "s": 24841, "text": "Parameter:" }, { "code": null, "e": 24965, "s": 24852, "text": "val: It is the specified number whose natural (base e) logarithm to be calculated and its type is System.Double." }, { "code": null, "e": 25047, "s": 24965, "text": "Return Value: Returns the natural logarithm of val and its type is System.Double." }, { "code": null, "e": 25180, "s": 25047, "text": "Note: Parameter val is always specified as a base 10 number.The return value is depend on the argument passed. Below are some cases:" }, { "code": null, "e": 25268, "s": 25180, "text": "If the argument is positive then method will return the natural logarithm or loge(val)." }, { "code": null, "e": 25330, "s": 25268, "text": "If the argument is zero, then the result is NegativeInfinity." }, { "code": null, "e": 25415, "s": 25330, "text": "If the argument is Negative(less than zero) or equal to NaN, then the result is NaN." }, { "code": null, "e": 25489, "s": 25415, "text": "If the argument is PositiveInfinity, then the result is PositiveInfinity." }, { "code": null, "e": 25550, "s": 25489, "text": "If the argument is NegativeInfinity, then the result is NaN." }, { "code": null, "e": 25559, "s": 25550, "text": "Example:" }, { "code": "// C# program to demonstrate working// of Math.Log(Double) methodusing System; class Geeks { // Main Method public static void Main(String[] args) { // double values whose logarithm // to be calculated double a = 4.55; double b = 0; double c = -2.45; double nan = Double.NaN; double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; // Input is positive number so output // will be logarithm of number Console.WriteLine(Math.Log(a)); // positive zero as argument, so output // will be -Infinity Console.WriteLine(Math.Log(b)); // Input is negative number so output // will be NaN Console.WriteLine(Math.Log(c)); // Input is NaN so output // will be NaN Console.WriteLine(Math.Log(nan)); // Input is PositiveInfinity so output // will be Infinity Console.WriteLine(Math.Log(positiveInfinity)); // Input is NegativeInfinity so output // will be NaN Console.WriteLine(Math.Log(negativeInfinity)); }}", "e": 26721, "s": 25559, "text": null }, { "code": null, "e": 26770, "s": 26721, "text": "1.51512723296286\n-Infinity\nNaN\nNaN\nInfinity\nNaN\n" }, { "code": null, "e": 26857, "s": 26770, "text": "This method is used to return the logarithm of a specified number in a specified base." }, { "code": null, "e": 26865, "s": 26857, "text": "Syntax:" }, { "code": null, "e": 26915, "s": 26865, "text": "public static double Log(double val, double base)" }, { "code": null, "e": 26926, "s": 26915, "text": "Parameter:" }, { "code": null, "e": 27022, "s": 26926, "text": "val: It is the specified number whose logarithm to be calculated and its type is System.Double." }, { "code": null, "e": 27083, "s": 27022, "text": "base: It is the base of the logarithm of type System.Double." }, { "code": null, "e": 27160, "s": 27083, "text": "Return Value: It returns the logarithm of val and its type is System.Double." }, { "code": null, "e": 27265, "s": 27160, "text": "Note: The return value is always depend on the argument passed. Below table depicts the different cases:" }, { "code": null, "e": 27274, "s": 27265, "text": "Example:" }, { "code": "// C# program to demonstrate working// of Math.Log(Double, Double) methodusing System; class Geeks { // Main Method public static void Main(String[] args) { // Here val = 1.3 and base is 0.3 then // output will be logarithm of given value Console.WriteLine(Math.Log(1.3, 0.3)); // Here val is 0.5 and base > 1 then output // will be -0.5 Console.WriteLine(Math.Log(0.5, 4)); // Here val is 0.7 and base = 1 then output // will be NaN Console.WriteLine(Math.Log(0.7, 1)); // Here val is 0.7 and base is NaN then output // will be NaN Console.WriteLine(Math.Log(0.7, Double.NaN)); }}", "e": 27975, "s": 27274, "text": null }, { "code": null, "e": 28008, "s": 27975, "text": "-0.217915440884381\n-0.5\nNaN\nNaN\n" }, { "code": null, "e": 28020, "s": 28008, "text": "References:" }, { "code": null, "e": 28085, "s": 28020, "text": "https://msdn.microsoft.com/en-us/library/x80ywz41(v=vs.110).aspx" }, { "code": null, "e": 28150, "s": 28085, "text": "https://msdn.microsoft.com/en-us/library/hd50b6h5(v=vs.110).aspx" }, { "code": null, "e": 28162, "s": 28150, "text": "CSharp-Math" }, { "code": null, "e": 28176, "s": 28162, "text": "CSharp-method" }, { "code": null, "e": 28179, "s": 28176, "text": "C#" }, { "code": null, "e": 28277, "s": 28179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28300, "s": 28277, "text": "C# | Method Overriding" }, { "code": null, "e": 28328, "s": 28300, "text": "C# Dictionary with examples" }, { "code": null, "e": 28346, "s": 28328, "text": "Destructors in C#" }, { "code": null, "e": 28392, "s": 28346, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28407, "s": 28392, "text": "C# | Delegates" }, { "code": null, "e": 28425, "s": 28407, "text": "C# | Constructors" }, { "code": null, "e": 28448, "s": 28425, "text": "Extension Method in C#" }, { "code": null, "e": 28488, "s": 28448, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28510, "s": 28488, "text": "C# | Class and Object" } ]
MapStruct - Mapping Nested Bean
MapStruct handles nested mapping seemlessly. For example, a Student with Subject as nested bean. Now create a mapper interface which can map nested objects. @Mapper public interface StudentMapper { @Mapping(target="className", source="classVal") @Mapping(target="subject", source="subject.name") Student getModelFromEntity(StudentEntity studentEntity); @Mapping(target="classVal", source="className") @Mapping(target="subject.name", source="subject") StudentEntity getEntityFromModel(Student student); } Open project mapping as updated in Mapping Multiple Objects chapter in Eclipse. Create SubjectEntity.java with following code − SubjectEntity.java package com.tutorialspoint.entity; public class SubjectEntity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } Update StudentEntity.java with following code − StudentEntity.java package com.tutorialspoint.entity; public class StudentEntity { private int id; private String name; private String classVal; private SubjectEntity subject; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassVal() { return classVal; } public void setClassVal(String classVal) { this.classVal = classVal; } public SubjectEntity getSubject() { return subject; } public void setSubject(SubjectEntity subject) { this.subject = subject; } } Update Student.java with following code − Student.java package com.tutorialspoint.model; public class Student { private int id; private String name; private String className; private String subject; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } } Update StudentMapper.java with following code − StudentMapper.java package com.tutorialspoint.mapper; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import com.tutorialspoint.entity.StudentEntity; import com.tutorialspoint.model.Student; @Mapper public interface StudentMapper { @Mapping(target="className", source="classVal") @Mapping(target="subject", source="subject.name") Student getModelFromEntity(StudentEntity studentEntity); @Mapping(target="classVal", source="className") @Mapping(target="subject.name", source="subject") StudentEntity getEntityFromModel(Student student); } Update StudentMapperTest.java with following code − StudentMapperTest.java package com.tutorialspoint.mapping; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import com.tutorialspoint.entity.StudentEntity; import com.tutorialspoint.entity.SubjectEntity; import com.tutorialspoint.mapper.StudentMapper; import com.tutorialspoint.model.Student; public class StudentMapperTest { private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class); @Test public void testEntityToModel() { StudentEntity entity = new StudentEntity(); entity.setClassVal("X"); entity.setName("John"); entity.setId(1); SubjectEntity subject = new SubjectEntity(); subject.setName("Computer"); entity.setSubject(subject); Student model = studentMapper.getModelFromEntity(entity); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); assertEquals(entity.getSubject().getName(), model.getSubject()); } @Test public void testModelToEntity() { Student model = new Student(); model.setId(1); model.setName("John"); model.setClassName("X"); model.setSubject("Science"); StudentEntity entity = studentMapper.getEntityFromModel(model); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); assertEquals(entity.getSubject().getName(), model.getSubject()); } } Run the following command to test the mappings. mvn clean test Once command is successful. Verify the output. mvn clean test [INFO] Scanning for projects... ... [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping --- [INFO] Surefire report directory: \mvn\mapping\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.tutorialspoint.mapping.DeliveryAddressMapperTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec Running com.tutorialspoint.mapping.StudentMapperTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec Results : Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 ... Print Add Notes Bookmark this page
[ { "code": null, "e": 2357, "s": 2260, "text": "MapStruct handles nested mapping seemlessly. For example, a Student with Subject as nested bean." }, { "code": null, "e": 2417, "s": 2357, "text": "Now create a mapper interface which can map nested objects." }, { "code": null, "e": 2784, "s": 2417, "text": "@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\t\n @Mapping(target=\"classVal\", source=\"className\")\n @Mapping(target=\"subject.name\", source=\"subject\")\n StudentEntity getEntityFromModel(Student student);\n}" }, { "code": null, "e": 2864, "s": 2784, "text": "Open project mapping as updated in Mapping Multiple Objects chapter in Eclipse." }, { "code": null, "e": 2912, "s": 2864, "text": "Create SubjectEntity.java with following code −" }, { "code": null, "e": 2931, "s": 2912, "text": "SubjectEntity.java" }, { "code": null, "e": 3143, "s": 2931, "text": "package com.tutorialspoint.entity;\n\npublic class SubjectEntity {\n private String name;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\t\n}" }, { "code": null, "e": 3191, "s": 3143, "text": "Update StudentEntity.java with following code −" }, { "code": null, "e": 3210, "s": 3191, "text": "StudentEntity.java" }, { "code": null, "e": 3900, "s": 3210, "text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}" }, { "code": null, "e": 3942, "s": 3900, "text": "Update Student.java with following code −" }, { "code": null, "e": 3955, "s": 3942, "text": "Student.java" }, { "code": null, "e": 4624, "s": 3955, "text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n private String subject;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n public String getSubject() {\n return subject;\n }\n public void setSubject(String subject) {\n this.subject = subject;\n }\n}" }, { "code": null, "e": 4672, "s": 4624, "text": "Update StudentMapper.java with following code −" }, { "code": null, "e": 4691, "s": 4672, "text": "StudentMapper.java" }, { "code": null, "e": 5242, "s": 4691, "text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\n @Mapping(target=\"classVal\", source=\"className\")\n @Mapping(target=\"subject.name\", source=\"subject\")\n StudentEntity getEntityFromModel(Student student);\n}" }, { "code": null, "e": 5294, "s": 5242, "text": "Update StudentMapperTest.java with following code −" }, { "code": null, "e": 5317, "s": 5294, "text": "StudentMapperTest.java" }, { "code": null, "e": 6927, "s": 5317, "text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n\n SubjectEntity subject = new SubjectEntity();\n subject.setName(\"Computer\");\n entity.setSubject(subject);\n\n Student model = studentMapper.getModelFromEntity(entity);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject()); \n }\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n model.setSubject(\"Science\");\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n }\n}" }, { "code": null, "e": 6975, "s": 6927, "text": "Run the following command to test the mappings." }, { "code": null, "e": 6991, "s": 6975, "text": "mvn clean test\n" }, { "code": null, "e": 7038, "s": 6991, "text": "Once command is successful. Verify the output." }, { "code": null, "e": 7686, "s": 7038, "text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n" }, { "code": null, "e": 7693, "s": 7686, "text": " Print" }, { "code": null, "e": 7704, "s": 7693, "text": " Add Notes" } ]
AngularJs Custom Service Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In the previous tutorials we have discussed about what is AngularJs service, what are all AngularJs pre-defined service and how we can use them in our application. In this tutorials, we are going to learn how to create our own AngularJs custom service with an example. In AngularJs, we can create our own service by using the module object like below. var myApp = angular.module(“myApp”,[]); Here the myApp is an reference of the module object. This module object provides two different functions to create user defined services. service() factory() We can create a custom service using service() function like below. myApp.service(“serviceName”,function(){ // Declare variables or functions with this keyword. }) If we want to make use of the custom service in controller, we need to specify the service details at the time of creating the controller it self. Ex: myApp.controller(“controllerName”,function($scope,serviceName){ // Here you can access the members of service by using service name. }) In this example we are going to write a custom service to do the basic mathematical operations, for all addition, subtraction,multiplication and division. And that custom service can be called from angularjs controller. Create app.js : Create an AngularJs module. var myApp = angular.module("myApp", []); Create math_service.js myApp.service("mathService", function() { this.add = function(x, y) { return parseInt(x) + parseInt(y); } this.sub = function(x, y) { return parseInt(x) - parseInt(y); } this.mul = function(x, y) { return parseInt(x) * parseInt(y); } this.div = function(x, y) { return parseInt(x) / parseInt(y); } }) Create math_controller.js myApp.controller( "mathController", function($scope, mathService) { $scope.x = 10; $scope.y = 30; $scope.result = 0; $scope.calcAdd = function() { $scope.result = mathService.add($scope.x, $scope.y) } $scope.calcSub = function() { $scope.result = mathService.sub($scope.x, $scope.y) } $scope.calcMul = function() { $scope.result = mathService.mul($scope.x, $scope.y) } $scope.calcDiv = function() { $scope.result = mathService.div($scope.x, $scope.y) } }) Create service_example.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>AngularJs Services Example</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="app_module.js"></script> <script src="math_service.js"></script> <script src="mathController.js"></script> </head> <body ng-app="myApp"> <h1>AngularJs Services Example</h1> <div ng-controller="mathController"> <table> <tr> <td>First Value : <td> <td> <input type="text" ng-model="x" /> <td> </tr> <tr> <td>Second Value : <td> <td> <input type="text" ng-model="y" /> <td> </tr> <tr> <td>Result is : <td> <td><b>{{result}}</b></td> <td> </tr> </table> <input type="button" ng-click="calcAdd()" value="Addition" /> <input type="button" ng-click="calcSub()" value="Substraction" /> <input type="button" ng-click="calcMul()" value="Multiply" /> <input type="button" ng-click="calcDiv()" value="Division" /> <br> </div> </body> </html> Output : [advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/Angular_Custom_service.html”] Happy Learning 🙂 Angular Module Example Tutorials Angular http (AJAX) Example Tutorials Angularjs Custom Filter Example AngularJs Custom Directive Example Angularjs Services Example Tutorials AngularJs Filters Example Tutorials AngularJs lowercase Filter Example AngularJs Currency Filter Example AngularJs Orderby Filter Example AngularJs Search Filter Example AngularJs Directive Example Tutorials AngularJs Data Binding Example Using Array in AngularJs Example Array of objects in AngularJs Example Steps to Create AngularJs Controller Angular Module Example Tutorials Angular http (AJAX) Example Tutorials Angularjs Custom Filter Example AngularJs Custom Directive Example Angularjs Services Example Tutorials AngularJs Filters Example Tutorials AngularJs lowercase Filter Example AngularJs Currency Filter Example AngularJs Orderby Filter Example AngularJs Search Filter Example AngularJs Directive Example Tutorials AngularJs Data Binding Example Using Array in AngularJs Example Array of objects in AngularJs Example Steps to Create AngularJs Controller
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 562, "s": 398, "text": "In the previous tutorials we have discussed about what is AngularJs service, what are all AngularJs pre-defined service and how we can use them in our application." }, { "code": null, "e": 667, "s": 562, "text": "In this tutorials, we are going to learn how to create our own AngularJs custom service with an example." }, { "code": null, "e": 750, "s": 667, "text": "In AngularJs, we can create our own service by using the module object like below." }, { "code": null, "e": 790, "s": 750, "text": "var myApp = angular.module(“myApp”,[]);" }, { "code": null, "e": 928, "s": 790, "text": "Here the myApp is an reference of the module object. This module object provides two different functions to create user defined services." }, { "code": null, "e": 938, "s": 928, "text": "service()" }, { "code": null, "e": 948, "s": 938, "text": "factory()" }, { "code": null, "e": 1016, "s": 948, "text": "We can create a custom service using service() function like below." }, { "code": null, "e": 1056, "s": 1016, "text": "myApp.service(“serviceName”,function(){" }, { "code": null, "e": 1109, "s": 1056, "text": "// Declare variables or functions with this keyword." }, { "code": null, "e": 1112, "s": 1109, "text": "})" }, { "code": null, "e": 1259, "s": 1112, "text": "If we want to make use of the custom service in controller, we need to specify the service details at the time of creating the controller it self." }, { "code": null, "e": 1263, "s": 1259, "text": "Ex:" }, { "code": null, "e": 1327, "s": 1263, "text": "myApp.controller(“controllerName”,function($scope,serviceName){" }, { "code": null, "e": 1396, "s": 1327, "text": "// Here you can access the members of service by using service name." }, { "code": null, "e": 1399, "s": 1396, "text": "})" }, { "code": null, "e": 1620, "s": 1399, "text": "In this example we are going to write a custom service to do the basic mathematical operations, for all addition, subtraction,multiplication and division. And that custom service can be called from angularjs controller." }, { "code": null, "e": 1636, "s": 1620, "text": "Create app.js :" }, { "code": null, "e": 1664, "s": 1636, "text": "Create an AngularJs module." }, { "code": null, "e": 1705, "s": 1664, "text": "var myApp = angular.module(\"myApp\", []);" }, { "code": null, "e": 1728, "s": 1705, "text": "Create math_service.js" }, { "code": null, "e": 2093, "s": 1728, "text": "myApp.service(\"mathService\", function() {\n this.add = function(x, y) {\n return parseInt(x) + parseInt(y);\n }\n this.sub = function(x, y) {\n return parseInt(x) - parseInt(y);\n }\n this.mul = function(x, y) {\n return parseInt(x) * parseInt(y);\n }\n this.div = function(x, y) {\n return parseInt(x) / parseInt(y);\n }\n})" }, { "code": null, "e": 2119, "s": 2093, "text": "Create math_controller.js" }, { "code": null, "e": 2651, "s": 2119, "text": "myApp.controller( \"mathController\", function($scope, mathService) {\n $scope.x = 10;\n $scope.y = 30;\n $scope.result = 0;\n $scope.calcAdd = function() {\n $scope.result = mathService.add($scope.x, $scope.y)\n }\n $scope.calcSub = function() {\n $scope.result = mathService.sub($scope.x, $scope.y)\n }\n $scope.calcMul = function() {\n $scope.result = mathService.mul($scope.x, $scope.y)\n }\n $scope.calcDiv = function() {\n $scope.result = mathService.div($scope.x, $scope.y)\n }\n})" }, { "code": null, "e": 2679, "s": 2651, "text": "Create service_example.html" }, { "code": null, "e": 4088, "s": 2679, "text": "<!DOCTYPE html>\n<html>\n\n<head>\n <meta charset=\"UTF-8\">\n <title>AngularJs Services Example</title>\n <script src=\"http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src=\"app_module.js\"></script>\n <script src=\"math_service.js\"></script>\n <script src=\"mathController.js\"></script>\n</head>\n\n<body ng-app=\"myApp\">\n <h1>AngularJs Services Example</h1>\n <div ng-controller=\"mathController\">\n <table>\n <tr>\n <td>First Value :\n <td>\n <td>\n <input type=\"text\" ng-model=\"x\" />\n <td>\n </tr>\n <tr>\n <td>Second Value :\n <td>\n <td>\n <input type=\"text\" ng-model=\"y\" />\n <td>\n </tr>\n <tr>\n <td>Result is :\n <td>\n <td><b>{{result}}</b></td>\n <td>\n </tr>\n </table>\n <input type=\"button\" ng-click=\"calcAdd()\" value=\"Addition\" />\n <input type=\"button\" ng-click=\"calcSub()\" value=\"Substraction\" />\n <input type=\"button\" ng-click=\"calcMul()\" value=\"Multiply\" />\n <input type=\"button\" ng-click=\"calcDiv()\" value=\"Division\" />\n <br> </div>\n</body>\n\n</html>" }, { "code": null, "e": 4097, "s": 4088, "text": "Output :" }, { "code": null, "e": 4260, "s": 4097, "text": "[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/Angular_Custom_service.html”]" }, { "code": null, "e": 4277, "s": 4260, "text": "Happy Learning 🙂" }, { "code": null, "e": 4802, "s": 4277, "text": "\nAngular Module Example Tutorials\nAngular http (AJAX) Example Tutorials\nAngularjs Custom Filter Example\nAngularJs Custom Directive Example\nAngularjs Services Example Tutorials\nAngularJs Filters Example Tutorials\nAngularJs lowercase Filter Example\nAngularJs Currency Filter Example\nAngularJs Orderby Filter Example\nAngularJs Search Filter Example\nAngularJs Directive Example Tutorials\nAngularJs Data Binding Example\nUsing Array in AngularJs Example\nArray of objects in AngularJs Example\nSteps to Create AngularJs Controller\n" }, { "code": null, "e": 4835, "s": 4802, "text": "Angular Module Example Tutorials" }, { "code": null, "e": 4873, "s": 4835, "text": "Angular http (AJAX) Example Tutorials" }, { "code": null, "e": 4905, "s": 4873, "text": "Angularjs Custom Filter Example" }, { "code": null, "e": 4940, "s": 4905, "text": "AngularJs Custom Directive Example" }, { "code": null, "e": 4977, "s": 4940, "text": "Angularjs Services Example Tutorials" }, { "code": null, "e": 5013, "s": 4977, "text": "AngularJs Filters Example Tutorials" }, { "code": null, "e": 5048, "s": 5013, "text": "AngularJs lowercase Filter Example" }, { "code": null, "e": 5082, "s": 5048, "text": "AngularJs Currency Filter Example" }, { "code": null, "e": 5115, "s": 5082, "text": "AngularJs Orderby Filter Example" }, { "code": null, "e": 5147, "s": 5115, "text": "AngularJs Search Filter Example" }, { "code": null, "e": 5185, "s": 5147, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 5216, "s": 5185, "text": "AngularJs Data Binding Example" }, { "code": null, "e": 5249, "s": 5216, "text": "Using Array in AngularJs Example" }, { "code": null, "e": 5288, "s": 5249, "text": "Array of objects in AngularJs Example" } ]
Get week of month and year using Java Calendar
For using Calendar class, import the following package. import java.util.Calendar; Create a Calendar class object. Calendar cal = Calendar.getInstance(); Now, get the week of month and year using the following fields. Calendar.WEEK_OF_MONTH Calendar.WEEK_OF_YEAR The following is an example. Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); // current date and time System.out.println(cal.getTime().toString()); // date information System.out.println("\nDate Information.........."); System.out.println("Year = " + cal.get(Calendar.YEAR)); System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1)); System.out.println("Date = " + cal.get(Calendar.DATE)); // week System.out.println("Week of month = " + cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Week of year = " + cal.get(Calendar.WEEK_OF_YEAR)); // time information System.out.println("\nTime Information.........."); System.out.println("Hour (24 hour format) : " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Hour (12 hour format) : " + cal.get(Calendar.HOUR)); System.out.println("Minute : " + cal.get(Calendar.MINUTE)); System.out.println("Second : " + cal.get(Calendar.SECOND)); System.out.println("Millisecond : " + cal.get(Calendar.MILLISECOND)); } } Mon Nov 19 14:28:46 UTC 2018 Date Information.......... Year = 2018 Month = 11 Date = 19 Week of month = 4 Week of year = 47 Time Information.......... Hour (24 hour format) : 14 Hour (12 hour format) : 2 Minute : 28 Second : 46 Millisecond : 464
[ { "code": null, "e": 1118, "s": 1062, "text": "For using Calendar class, import the following package." }, { "code": null, "e": 1145, "s": 1118, "text": "import java.util.Calendar;" }, { "code": null, "e": 1177, "s": 1145, "text": "Create a Calendar class object." }, { "code": null, "e": 1216, "s": 1177, "text": "Calendar cal = Calendar.getInstance();" }, { "code": null, "e": 1280, "s": 1216, "text": "Now, get the week of month and year using the following fields." }, { "code": null, "e": 1325, "s": 1280, "text": "Calendar.WEEK_OF_MONTH\nCalendar.WEEK_OF_YEAR" }, { "code": null, "e": 1354, "s": 1325, "text": "The following is an example." }, { "code": null, "e": 1365, "s": 1354, "text": " Live Demo" }, { "code": null, "e": 2498, "s": 1365, "text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar cal = Calendar.getInstance();\n // current date and time\n System.out.println(cal.getTime().toString());\n // date information\n System.out.println(\"\\nDate Information..........\");\n System.out.println(\"Year = \" + cal.get(Calendar.YEAR));\n System.out.println(\"Month = \" + (cal.get(Calendar.MONTH) + 1));\n System.out.println(\"Date = \" + cal.get(Calendar.DATE));\n // week\n System.out.println(\"Week of month = \" + cal.get(Calendar.WEEK_OF_MONTH));\n System.out.println(\"Week of year = \" + cal.get(Calendar.WEEK_OF_YEAR));\n // time information\n System.out.println(\"\\nTime Information..........\");\n System.out.println(\"Hour (24 hour format) : \" + cal.get(Calendar.HOUR_OF_DAY));\n System.out.println(\"Hour (12 hour format) : \" + cal.get(Calendar.HOUR));\n System.out.println(\"Minute : \" + cal.get(Calendar.MINUTE));\n System.out.println(\"Second : \" + cal.get(Calendar.SECOND));\n System.out.println(\"Millisecond : \" + cal.get(Calendar.MILLISECOND));\n }\n}" }, { "code": null, "e": 2747, "s": 2498, "text": "Mon Nov 19 14:28:46 UTC 2018\n\nDate Information..........\nYear = 2018\nMonth = 11\nDate = 19\nWeek of month = 4\nWeek of year = 47\n\nTime Information..........\nHour (24 hour format) : 14\nHour (12 hour format) : 2\nMinute : 28\nSecond : 46\nMillisecond : 464" } ]
Different ways to declare variable as constant in C and C++ - GeeksforGeeks
21 Aug, 2019 There are many different ways to make the variable as constant Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.// C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;}It will throw as error like: error: assignment of read-only variable ‘num’ Using enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.// In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.Note: The data types of enum are of course limited as we can see in above example.Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.#include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;}Above program will throw an error i.e.,error: the value of ‘var’ is not usable in a constant expressionbecause the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword.Using Macros: We can also use Macros to define constant, but there is a catch,#define var 5 Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.// C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;}It will throw as error like: error: assignment of read-only variable ‘num’ // C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;} It will throw as error like: error: assignment of read-only variable ‘num’ Using enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.// In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.Note: The data types of enum are of course limited as we can see in above example. // In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type. Note: The data types of enum are of course limited as we can see in above example. Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.#include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;}Above program will throw an error i.e.,error: the value of ‘var’ is not usable in a constant expressionbecause the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword. #include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;} Above program will throw an error i.e., error: the value of ‘var’ is not usable in a constant expression because the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword. Using Macros: We can also use Macros to define constant, but there is a catch,#define var 5 #define var 5 Since Macros are handled by the pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences of ‘var’ with the literal 5) not by the compiler.Hence it wouldn’t be recommended because Macros doesn’t carry type checking information and also prone to error. In fact not quite constant as ‘var’ can be redefined like this, C++ C // C++ program to demonstrate the problems// in 'Macros'#include <iostream>using namespace std; #define var 5int main() { printf("%d ", var); #ifdef var #undef var // redefine var as 10 #define var 10 #endif printf("%d", var); return 0;} // C program to demonstrate the problems// in 'Macros'#include <stdio.h> #define var 5int main(){ printf("%d ", var); #ifdef var#undef var // redefine var as 10#define var 10#endif printf("%d", var); return 0;} Output: 5 10 Note: preprocessor and enum only works as a literal constant and integers constant respectively. Hence they only define the symbolic name of constant. Therefore if you need a constant variable with a specific memory address use either ‘const’ or ‘constexpr’ according to the requirement. This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. cpp-data-types C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Command line arguments in C/C++ Function Pointer in C Substring in C++ Structures 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": 24420, "s": 24392, "text": "\n21 Aug, 2019" }, { "code": null, "e": 24483, "s": 24420, "text": "There are many different ways to make the variable as constant" }, { "code": null, "e": 26010, "s": 24483, "text": "Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.// C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;}It will throw as error like:\nerror: assignment of read-only variable ‘num’\nUsing enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.// In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.Note: The data types of enum are of course limited as we can see in above example.Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.#include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;}Above program will throw an error i.e.,error: the value of ‘var’ is not usable in a constant expressionbecause the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword.Using Macros: We can also use Macros to define constant, but there is a catch,#define var 5" }, { "code": null, "e": 26370, "s": 26010, "text": "Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.// C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;}It will throw as error like:\nerror: assignment of read-only variable ‘num’\n" }, { "code": "// C program to demonstrate const specifier#include <stdio.h>int main(){ const int num = 1; num = 5; // Modifying the value return 0;}", "e": 26516, "s": 26370, "text": null }, { "code": null, "e": 26592, "s": 26516, "text": "It will throw as error like:\nerror: assignment of read-only variable ‘num’\n" }, { "code": null, "e": 27116, "s": 26592, "text": "Using enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.// In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.Note: The data types of enum are of course limited as we can see in above example." }, { "code": "// In C and C++ internally the default// type of 'var' is intenum VARS { var = 42 }; // In C++ 11 (can have any integral type):enum : type { var = 42; } // where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.", "e": 27371, "s": 27116, "text": null }, { "code": null, "e": 27454, "s": 27371, "text": "Note: The data types of enum are of course limited as we can see in above example." }, { "code": null, "e": 28008, "s": 27454, "text": "Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.#include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;}Above program will throw an error i.e.,error: the value of ‘var’ is not usable in a constant expressionbecause the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword." }, { "code": "#include <iostream> int main(){ int var = 5; constexpr int k = var; std::cout << k; return 0;}", "e": 28116, "s": 28008, "text": null }, { "code": null, "e": 28156, "s": 28116, "text": "Above program will throw an error i.e.," }, { "code": null, "e": 28221, "s": 28156, "text": "error: the value of ‘var’ is not usable in a constant expression" }, { "code": null, "e": 28373, "s": 28221, "text": "because the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword." }, { "code": null, "e": 28465, "s": 28373, "text": "Using Macros: We can also use Macros to define constant, but there is a catch,#define var 5" }, { "code": null, "e": 28479, "s": 28465, "text": "#define var 5" }, { "code": null, "e": 28837, "s": 28479, "text": "Since Macros are handled by the pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences of ‘var’ with the literal 5) not by the compiler.Hence it wouldn’t be recommended because Macros doesn’t carry type checking information and also prone to error. In fact not quite constant as ‘var’ can be redefined like this," }, { "code": null, "e": 28841, "s": 28837, "text": "C++" }, { "code": null, "e": 28843, "s": 28841, "text": "C" }, { "code": "// C++ program to demonstrate the problems// in 'Macros'#include <iostream>using namespace std; #define var 5int main() { printf(\"%d \", var); #ifdef var #undef var // redefine var as 10 #define var 10 #endif printf(\"%d\", var); return 0;}", "e": 29112, "s": 28843, "text": null }, { "code": "// C program to demonstrate the problems// in 'Macros'#include <stdio.h> #define var 5int main(){ printf(\"%d \", var); #ifdef var#undef var // redefine var as 10#define var 10#endif printf(\"%d\", var); return 0;}", "e": 29337, "s": 29112, "text": null }, { "code": null, "e": 29351, "s": 29337, "text": "Output:\n5 10\n" }, { "code": null, "e": 29639, "s": 29351, "text": "Note: preprocessor and enum only works as a literal constant and integers constant respectively. Hence they only define the symbolic name of constant. Therefore if you need a constant variable with a specific memory address use either ‘const’ or ‘constexpr’ according to the requirement." }, { "code": null, "e": 29941, "s": 29639, "text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29956, "s": 29941, "text": "cpp-data-types" }, { "code": null, "e": 29967, "s": 29956, "text": "C Language" }, { "code": null, "e": 29971, "s": 29967, "text": "C++" }, { "code": null, "e": 29975, "s": 29971, "text": "CPP" }, { "code": null, "e": 30073, "s": 29975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30085, "s": 30073, "text": "fork() in C" }, { "code": null, "e": 30117, "s": 30085, "text": "Command line arguments in C/C++" }, { "code": null, "e": 30139, "s": 30117, "text": "Function Pointer in C" }, { "code": null, "e": 30156, "s": 30139, "text": "Substring in C++" }, { "code": null, "e": 30172, "s": 30156, "text": "Structures in C" }, { "code": null, "e": 30190, "s": 30172, "text": "Vector in C++ STL" }, { "code": null, "e": 30236, "s": 30190, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30255, "s": 30236, "text": "Inheritance in C++" }, { "code": null, "e": 30298, "s": 30255, "text": "Map in C++ Standard Template Library (STL)" } ]
123 Number Flip in Python
Suppose we have an integer n, where only 1, 2, and 3 these digits are present. We can flip one digit to a 3. Then find the maximum number we can make. So, if the input is like 11332, then the output will be 31332 To solve this, we will follow these steps − li := a list by digits of n li := a list by digits of n for x in range 0 to size of li - 1, doif li[x] is not '3', thenli[x] := '3'return the number by merging digits from li for x in range 0 to size of li - 1, do if li[x] is not '3', thenli[x] := '3'return the number by merging digits from li if li[x] is not '3', then li[x] := '3' li[x] := '3' return the number by merging digits from li return the number by merging digits from li return n return n Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, n): li = list(str(n)) for x in range(len(li)): if li[x] != '3': li[x] = '3' return int(''.join(li)) return n ob = Solution() print(ob.solve(11332)) 11332 31332
[ { "code": null, "e": 1213, "s": 1062, "text": "Suppose we have an integer n, where only 1, 2, and 3 these digits are present. We can flip one digit to a 3. Then find the maximum number we can make." }, { "code": null, "e": 1275, "s": 1213, "text": "So, if the input is like 11332, then the output will be 31332" }, { "code": null, "e": 1319, "s": 1275, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1347, "s": 1319, "text": "li := a list by digits of n" }, { "code": null, "e": 1375, "s": 1347, "text": "li := a list by digits of n" }, { "code": null, "e": 1494, "s": 1375, "text": "for x in range 0 to size of li - 1, doif li[x] is not '3', thenli[x] := '3'return the number by merging digits from li" }, { "code": null, "e": 1533, "s": 1494, "text": "for x in range 0 to size of li - 1, do" }, { "code": null, "e": 1614, "s": 1533, "text": "if li[x] is not '3', thenli[x] := '3'return the number by merging digits from li" }, { "code": null, "e": 1640, "s": 1614, "text": "if li[x] is not '3', then" }, { "code": null, "e": 1653, "s": 1640, "text": "li[x] := '3'" }, { "code": null, "e": 1666, "s": 1653, "text": "li[x] := '3'" }, { "code": null, "e": 1710, "s": 1666, "text": "return the number by merging digits from li" }, { "code": null, "e": 1754, "s": 1710, "text": "return the number by merging digits from li" }, { "code": null, "e": 1763, "s": 1754, "text": "return n" }, { "code": null, "e": 1772, "s": 1763, "text": "return n" }, { "code": null, "e": 1842, "s": 1772, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1853, "s": 1842, "text": " Live Demo" }, { "code": null, "e": 2087, "s": 1853, "text": "class Solution:\n def solve(self, n):\n li = list(str(n))\n for x in range(len(li)):\n if li[x] != '3':\n li[x] = '3'\n return int(''.join(li))\n return n\nob = Solution()\nprint(ob.solve(11332))" }, { "code": null, "e": 2093, "s": 2087, "text": "11332" }, { "code": null, "e": 2099, "s": 2093, "text": "31332" } ]
How to create Python Iterable class ? - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see how to create an Iterable class in Python. An iterator is an object that can be iterated through all the values in the object. In python Lists, tuples, dictionaries, and sets are all iterable objects, these are all can be iterate over the values. The iter() is a method used to get the iterator from List, tuple, dictionary and set objects, through which the items are get iterated. By default, all python classes are not iterable so that we can not traverse/iterate the values of the python class. To make a class as iterable, you have to implement the __iter__() and __next__() methods in that class. The __iter__() method allows us to make operations on the items or initializing the items and returns an iterator object. The __next__() method allows us to do operations and it should return the next value of the sequence. To make the example as simple, I am taking a simple use-case – Creating a class that allows iterating over a range of provided dates, and it always produces one day at a time on every loop. from datetime import timedelta, date class DateIterable: def __init__(self, start_date, end_date): # initilizing the start and end dates self.start_date = start_date self.end_date = end_date self._present_day = start_date def __iter__(self): #returning __iter__ object return self def __next__(self): #comparing present_day with end_date, #if present_day greater then end_date stoping the iteration if self._present_day >= self.end_date: raise StopIteration today = self._present_day self._present_day += timedelta(days=1) return today if __name__ == '__main__': for day in DateIterable(date(2020, 1, 1), date(2020, 1, 6)): print(day) Output: 2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 The above example iterates the days between the start and end days. The for loop creates an iterator object and executes the next() method for each loop, that’s why we see them each day in a separate line. Note: StopItertion is used to prevent the iteration, usually, we prevent the iteration on a specific condition. Python Iterators How to Iterate Python Dictionary ? How to Convert Python List Of Objects to CSV File How to read JSON file in Python ? How to Create or Delete Directories in Python ? Python Set Data Structure in Depth Convert any Number to Python Binary Number Python – How to create Zip File in Python ? How to Convert Iterable to Stream Java 8 Python – Find the biggest of 2 given numbers How to Remove Spaces from String in Python How to get Words Count in Python from a File How to get Characters Count in Python from a File How to merge two lists in Python How to Read CSV File in Python What are the different ways to Sort Objects in Python ? How to Iterate Python Dictionary ? How to Convert Python List Of Objects to CSV File How to read JSON file in Python ? How to Create or Delete Directories in Python ? Python Set Data Structure in Depth Convert any Number to Python Binary Number Python – How to create Zip File in Python ? How to Convert Iterable to Stream Java 8 Python – Find the biggest of 2 given numbers How to Remove Spaces from String in Python How to get Words Count in Python from a File How to get Characters Count in Python from a File How to merge two lists in Python How to Read CSV File in Python What are the different ways to Sort Objects in Python ? Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 479, "s": 398, "text": "In this tutorial, we are going to see how to create an Iterable class in Python." }, { "code": null, "e": 683, "s": 479, "text": "An iterator is an object that can be iterated through all the values in the object. In python Lists, tuples, dictionaries, and sets are all iterable objects, these are all can be iterate over the values." }, { "code": null, "e": 819, "s": 683, "text": "The iter() is a method used to get the iterator from List, tuple, dictionary and set objects, through which the items are get iterated." }, { "code": null, "e": 1040, "s": 819, "text": "By default, all python classes are not iterable so that we can not traverse/iterate the values of the python class. To make a class as iterable, you have to implement the __iter__() and __next__() methods in that class." }, { "code": null, "e": 1162, "s": 1040, "text": "The __iter__() method allows us to make operations on the items or initializing the items and returns an iterator object." }, { "code": null, "e": 1264, "s": 1162, "text": "The __next__() method allows us to do operations and it should return the next value of the sequence." }, { "code": null, "e": 1454, "s": 1264, "text": "To make the example as simple, I am taking a simple use-case – Creating a class that allows iterating over a range of provided dates, and it always produces one day at a time on every loop." }, { "code": null, "e": 2227, "s": 1454, "text": "from datetime import timedelta, date\n\nclass DateIterable:\n\n def __init__(self, start_date, end_date):\n # initilizing the start and end dates\n self.start_date = start_date\n self.end_date = end_date\n self._present_day = start_date\n\n def __iter__(self):\n #returning __iter__ object\n return self\n\n def __next__(self):\n #comparing present_day with end_date,\n #if present_day greater then end_date stoping the iteration\n if self._present_day >= self.end_date:\n raise StopIteration\n today = self._present_day\n self._present_day += timedelta(days=1)\n return today\n\n\nif __name__ == '__main__':\n for day in DateIterable(date(2020, 1, 1), date(2020, 1, 6)):\n print(day)" }, { "code": null, "e": 2235, "s": 2227, "text": "Output:" }, { "code": null, "e": 2290, "s": 2235, "text": "2020-01-01\n2020-01-02\n2020-01-03\n2020-01-04\n2020-01-05" }, { "code": null, "e": 2496, "s": 2290, "text": "The above example iterates the days between the start and end days. The for loop creates an iterator object and executes the next() method for each loop, that’s why we see them each day in a separate line." }, { "code": null, "e": 2608, "s": 2496, "text": "Note: StopItertion is used to prevent the iteration, usually, we prevent the iteration on a specific condition." }, { "code": null, "e": 2625, "s": 2608, "text": "Python Iterators" }, { "code": null, "e": 3260, "s": 2625, "text": "\nHow to Iterate Python Dictionary ?\nHow to Convert Python List Of Objects to CSV File\nHow to read JSON file in Python ?\nHow to Create or Delete Directories in Python ?\nPython Set Data Structure in Depth\nConvert any Number to Python Binary Number\nPython – How to create Zip File in Python ?\nHow to Convert Iterable to Stream Java 8\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\nHow to merge two lists in Python\nHow to Read CSV File in Python\nWhat are the different ways to Sort Objects in Python ?\n" }, { "code": null, "e": 3295, "s": 3260, "text": "How to Iterate Python Dictionary ?" }, { "code": null, "e": 3345, "s": 3295, "text": "How to Convert Python List Of Objects to CSV File" }, { "code": null, "e": 3379, "s": 3345, "text": "How to read JSON file in Python ?" }, { "code": null, "e": 3427, "s": 3379, "text": "How to Create or Delete Directories in Python ?" }, { "code": null, "e": 3462, "s": 3427, "text": "Python Set Data Structure in Depth" }, { "code": null, "e": 3505, "s": 3462, "text": "Convert any Number to Python Binary Number" }, { "code": null, "e": 3549, "s": 3505, "text": "Python – How to create Zip File in Python ?" }, { "code": null, "e": 3590, "s": 3549, "text": "How to Convert Iterable to Stream Java 8" }, { "code": null, "e": 3635, "s": 3590, "text": "Python – Find the biggest of 2 given numbers" }, { "code": null, "e": 3678, "s": 3635, "text": "How to Remove Spaces from String in Python" }, { "code": null, "e": 3723, "s": 3678, "text": "How to get Words Count in Python from a File" }, { "code": null, "e": 3773, "s": 3723, "text": "How to get Characters Count in Python from a File" }, { "code": null, "e": 3806, "s": 3773, "text": "How to merge two lists in Python" }, { "code": null, "e": 3837, "s": 3806, "text": "How to Read CSV File in Python" }, { "code": null, "e": 3893, "s": 3837, "text": "What are the different ways to Sort Objects in Python ?" }, { "code": null, "e": 3899, "s": 3897, "text": "Δ" }, { "code": null, "e": 3922, "s": 3899, "text": " Python – Introduction" }, { "code": null, "e": 3941, "s": 3922, "text": " Python – Features" }, { "code": null, "e": 3970, "s": 3941, "text": " Python – Install on Windows" }, { "code": null, "e": 3997, "s": 3970, "text": " Python – Modes of Program" }, { "code": null, "e": 4021, "s": 3997, "text": " Python – Number System" }, { "code": null, "e": 4043, "s": 4021, "text": " Python – Identifiers" }, { "code": null, "e": 4063, "s": 4043, "text": " Python – Operators" }, { "code": null, "e": 4090, "s": 4063, "text": " Python – Ternary Operator" }, { "code": null, "e": 4123, "s": 4090, "text": " Python – Command Line Arguments" }, { "code": null, "e": 4142, "s": 4123, "text": " Python – Keywords" }, { "code": null, "e": 4163, "s": 4142, "text": " Python – Data Types" }, { "code": null, "e": 4192, "s": 4163, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 4222, "s": 4192, "text": " Python – Virtual Environment" }, { "code": null, "e": 4245, "s": 4222, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4269, "s": 4245, "text": " Python – String to Int" }, { "code": null, "e": 4302, "s": 4269, "text": " Python – Conditional Statements" }, { "code": null, "e": 4325, "s": 4302, "text": " Python – if statement" }, { "code": null, "e": 4354, "s": 4325, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4380, "s": 4354, "text": " Python – Date Formatting" }, { "code": null, "e": 4415, "s": 4380, "text": " Python – Read input from keyboard" }, { "code": null, "e": 4435, "s": 4415, "text": " Python – raw_input" }, { "code": null, "e": 4459, "s": 4435, "text": " Python – List In Depth" }, { "code": null, "e": 4488, "s": 4459, "text": " Python – List Comprehension" }, { "code": null, "e": 4511, "s": 4488, "text": " Python – Set in Depth" }, { "code": null, "e": 4541, "s": 4511, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 4566, "s": 4541, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4596, "s": 4566, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4626, "s": 4596, "text": " Python – Classes and Objects" }, { "code": null, "e": 4649, "s": 4626, "text": " Python – Constructors" }, { "code": null, "e": 4680, "s": 4649, "text": " Python – Object Introspection" }, { "code": null, "e": 4702, "s": 4680, "text": " Python – Inheritance" }, { "code": null, "e": 4723, "s": 4702, "text": " Python – Decorators" }, { "code": null, "e": 4759, "s": 4723, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4789, "s": 4759, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4823, "s": 4789, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4849, "s": 4823, "text": " Python – Multiprocessing" }, { "code": null, "e": 4887, "s": 4849, "text": " Python – Default function parameters" }, { "code": null, "e": 4915, "s": 4887, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4939, "s": 4915, "text": " Python – NumPy Library" }, { "code": null, "e": 4965, "s": 4939, "text": " Python – MySQL Connector" }, { "code": null, "e": 4997, "s": 4965, "text": " Python – MySQL Create Database" }, { "code": null, "e": 5023, "s": 4997, "text": " Python – MySQL Read Data" }, { "code": null, "e": 5051, "s": 5023, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 5082, "s": 5051, "text": " Python – MySQL Update Records" }, { "code": null, "e": 5113, "s": 5082, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 5146, "s": 5113, "text": " Python – String Case Conversion" }, { "code": null, "e": 5181, "s": 5146, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 5218, "s": 5181, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5256, "s": 5218, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5282, "s": 5256, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5307, "s": 5282, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5347, "s": 5307, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5382, "s": 5347, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5417, "s": 5382, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 5446, "s": 5417, "text": " Howto – Read Env variables" }, { "code": null, "e": 5472, "s": 5446, "text": " Howto – Read a text File" }, { "code": null, "e": 5498, "s": 5472, "text": " Howto – Read a JSON File" }, { "code": null, "e": 5530, "s": 5498, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 5558, "s": 5530, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5598, "s": 5558, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5632, "s": 5598, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5657, "s": 5632, "text": " Howto – create Zip File" }, { "code": null, "e": 5678, "s": 5657, "text": " Howto – Get OS info" }, { "code": null, "e": 5709, "s": 5678, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5746, "s": 5709, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5783, "s": 5746, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5805, "s": 5783, "text": " Howto – Sort Objects" }, { "code": null, "e": 5843, "s": 5805, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5866, "s": 5843, "text": " Howto – Read CSV File" }, { "code": null, "e": 5904, "s": 5866, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5935, "s": 5904, "text": " Howto – Access for loop index" }, { "code": null, "e": 5973, "s": 5935, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 6013, "s": 5973, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 6060, "s": 6013, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 6092, "s": 6060, "text": " Howto – Sort dictionary by key" } ]
Average numbers in array in C Programming
There are n number of elements stored in an array and this program calculates the average of those numbers. Using different methods. Input - 1 2 3 4 5 6 7 Output - 4 Explanation - Sum of elements of array 1+2+3+4+5+6+7=28 No of element in array=7 Average=28/7=4 There are two methods In this method we will find sum and divide the sum by the total number of elements. Given array arr[] and size of array n Input - 1 2 3 4 5 6 7 Output - 4 Explanation - Sum of elements of array 1+2+3+4+5+6+7=28 No of element in array=7 Average=28/7=4 #include<iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n=7; int sum = 0; for (int i=0; i<n; i++) { sum += arr[i]; } float average = sum/n; cout << average; return 0; } The idea is to pass index of element as an additional parameter and recursively compute sum. After computing sum, divide the sum by n. Given array arr[], size of array n and initial index i Input - 1 2 3 4 5 Output - 3 Explanation - Sum of elements of array 1+2+3+4+5=15 No of element in array=5 Average=15/5=3 #include <iostream> using namespace std; int avg(int arr[], int i, int n) { if (i == n-1) { return arr[i]; } if (i == 0) { return ((arr[i] + avg(arr, i+1, n))/n); } return (arr[i] + avg(arr, i+1, n)); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; cout << avg(arr,0, n) << endl; return 0; }
[ { "code": null, "e": 1195, "s": 1062, "text": "There are n number of elements stored in an array and this program calculates the average of those numbers. Using different methods." }, { "code": null, "e": 1217, "s": 1195, "text": "Input - 1 2 3 4 5 6 7" }, { "code": null, "e": 1228, "s": 1217, "text": "Output - 4" }, { "code": null, "e": 1284, "s": 1228, "text": "Explanation - Sum of elements of array 1+2+3+4+5+6+7=28" }, { "code": null, "e": 1309, "s": 1284, "text": "No of element in array=7" }, { "code": null, "e": 1324, "s": 1309, "text": "Average=28/7=4" }, { "code": null, "e": 1346, "s": 1324, "text": "There are two methods" }, { "code": null, "e": 1430, "s": 1346, "text": "In this method we will find sum and divide the sum by the total number of elements." }, { "code": null, "e": 1468, "s": 1430, "text": "Given array arr[] and size of array n" }, { "code": null, "e": 1490, "s": 1468, "text": "Input - 1 2 3 4 5 6 7" }, { "code": null, "e": 1501, "s": 1490, "text": "Output - 4" }, { "code": null, "e": 1557, "s": 1501, "text": "Explanation - Sum of elements of array 1+2+3+4+5+6+7=28" }, { "code": null, "e": 1582, "s": 1557, "text": "No of element in array=7" }, { "code": null, "e": 1597, "s": 1582, "text": "Average=28/7=4" }, { "code": null, "e": 1834, "s": 1597, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int arr[] = { 1, 2, 3, 4, 5, 6, 7 };\n int n=7;\n int sum = 0;\n for (int i=0; i<n; i++) {\n sum += arr[i];\n }\n float average = sum/n;\n cout << average;\n return 0;\n}" }, { "code": null, "e": 1969, "s": 1834, "text": "The idea is to pass index of element as an additional parameter and recursively compute sum. After computing sum, divide the sum by n." }, { "code": null, "e": 2024, "s": 1969, "text": "Given array arr[], size of array n and initial index i" }, { "code": null, "e": 2042, "s": 2024, "text": "Input - 1 2 3 4 5" }, { "code": null, "e": 2053, "s": 2042, "text": "Output - 3" }, { "code": null, "e": 2105, "s": 2053, "text": "Explanation - Sum of elements of array 1+2+3+4+5=15" }, { "code": null, "e": 2130, "s": 2105, "text": "No of element in array=5" }, { "code": null, "e": 2145, "s": 2130, "text": "Average=15/5=3" }, { "code": null, "e": 2483, "s": 2145, "text": "#include <iostream>\nusing namespace std;\nint avg(int arr[], int i, int n) {\n if (i == n-1) {\n return arr[i];\n }\n if (i == 0) {\n return ((arr[i] + avg(arr, i+1, n))/n);\n }\n return (arr[i] + avg(arr, i+1, n));\n}\nint main() {\n int arr[] = {1, 2, 3, 4, 5};\n int n = 5;\n cout << avg(arr,0, n) << endl;\n return 0;\n}" } ]
Express.js router.all() Function
09 Jul, 2020 The router.all() function is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs). It is very helpful for mapping global logic for arbitrary matches or specific path prefixes. Syntax: router.all(path, [callback, ...] callback) Parameter: The path parameter is the path of the specified URL and callback is the function passed as parameter. Return Value: It returns responses. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Setting single route router.all('/user', function (req, res) { console.log("User Page Called"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now make any request to http://localhost:3000/user like POST, PUT, DELETE or any other type of request, it will shown the following outputUser Page Called Every type of request made to http://localhost:3000/user will print the same output. The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now make any request to http://localhost:3000/user like POST, PUT, DELETE or any other type of request, it will shown the following outputUser Page Called Every type of request made to http://localhost:3000/user will print the same output. User Page Called Every type of request made to http://localhost:3000/user will print the same output. Example 2: Filename: index.js var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Setting multiple routes router.all('/user', function (req, res) { console.log("User Page Called"); res.end();}); router.all('/student', function (req, res) { console.log("Student Page Called"); res.end();}); router.all('/teacher', function (req, res) { console.log("Teacher Page Called"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now make GET request to http://localhost:3000/user, http://localhost:3000/student and http://localhost:3000/teacher it will shown the following output. User Page Called Student Page Called Teacher Page Called Reference: https://expressjs.com/en/4x/api.html#router.all Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method 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": "\n09 Jul, 2020" }, { "code": null, "e": 238, "s": 28, "text": "The router.all() function is just like the router.METHOD() methods, except that it matches all HTTP methods (verbs). It is very helpful for mapping global logic for arbitrary matches or specific path prefixes." }, { "code": null, "e": 246, "s": 238, "text": "Syntax:" }, { "code": null, "e": 289, "s": 246, "text": "router.all(path, [callback, ...] callback)" }, { "code": null, "e": 402, "s": 289, "text": "Parameter: The path parameter is the path of the specified URL and callback is the function passed as parameter." }, { "code": null, "e": 438, "s": 402, "text": "Return Value: It returns responses." }, { "code": null, "e": 470, "s": 438, "text": "Installation of express module:" }, { "code": null, "e": 865, "s": 470, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 986, "s": 865, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 1006, "s": 986, "text": "npm install express" }, { "code": null, "e": 1134, "s": 1006, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 1154, "s": 1134, "text": "npm version express" }, { "code": null, "e": 1302, "s": 1154, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1316, "s": 1302, "text": "node index.js" }, { "code": null, "e": 1346, "s": 1316, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Setting single route router.all('/user', function (req, res) { console.log(\"User Page Called\"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 1701, "s": 1346, "text": null }, { "code": null, "e": 1727, "s": 1701, "text": "Steps to run the program:" }, { "code": null, "e": 2192, "s": 1727, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make any request to http://localhost:3000/user like POST, PUT, DELETE or any other type of request, it will shown the following outputUser Page Called \nEvery type of request made to http://localhost:3000/user will print the same output." }, { "code": null, "e": 2235, "s": 2192, "text": "The project structure will look like this:" }, { "code": null, "e": 2327, "s": 2235, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 2347, "s": 2327, "text": "npm install express" }, { "code": null, "e": 2436, "s": 2347, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 2450, "s": 2436, "text": "node index.js" }, { "code": null, "e": 2458, "s": 2450, "text": "Output:" }, { "code": null, "e": 2489, "s": 2458, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 2733, "s": 2489, "text": "Now make any request to http://localhost:3000/user like POST, PUT, DELETE or any other type of request, it will shown the following outputUser Page Called \nEvery type of request made to http://localhost:3000/user will print the same output." }, { "code": null, "e": 2755, "s": 2733, "text": "User Page Called \n" }, { "code": null, "e": 2840, "s": 2755, "text": "Every type of request made to http://localhost:3000/user will print the same output." }, { "code": null, "e": 2870, "s": 2840, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express();var router = express.Router();var PORT = 3000; // Setting multiple routes router.all('/user', function (req, res) { console.log(\"User Page Called\"); res.end();}); router.all('/student', function (req, res) { console.log(\"Student Page Called\"); res.end();}); router.all('/teacher', function (req, res) { console.log(\"Teacher Page Called\"); res.end();}); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 3432, "s": 2870, "text": null }, { "code": null, "e": 3471, "s": 3432, "text": "Run index.js file using below command:" }, { "code": null, "e": 3485, "s": 3471, "text": "node index.js" }, { "code": null, "e": 3637, "s": 3485, "text": "Now make GET request to http://localhost:3000/user, http://localhost:3000/student and http://localhost:3000/teacher it will shown the following output." }, { "code": null, "e": 3701, "s": 3637, "text": "User Page Called \nStudent Page Called \nTeacher Page Called \n" }, { "code": null, "e": 3760, "s": 3701, "text": "Reference: https://expressjs.com/en/4x/api.html#router.all" }, { "code": null, "e": 3771, "s": 3760, "text": "Express.js" }, { "code": null, "e": 3779, "s": 3771, "text": "Node.js" }, { "code": null, "e": 3796, "s": 3779, "text": "Web Technologies" }, { "code": null, "e": 3894, "s": 3796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3942, "s": 3894, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3975, "s": 3942, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4008, "s": 3975, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 4065, "s": 4008, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 4095, "s": 4065, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 4128, "s": 4095, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4190, "s": 4128, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4251, "s": 4190, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4301, "s": 4251, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution)
28 Feb, 2022 Consider a situation where we have a file shared between many people. If one of the people tries editing the file, no other person should be reading or writing at the same time, otherwise changes will not be visible to him/her. However if some person is reading the file, then others may read it at the same time. Precisely in OS we call this situation as the readers-writers problem Problem parameters: One set of data is shared among a number of processes Once a writer is ready, it performs its write. Only one writer may write at a time If a process is writing, no other process can read it If at least one reader is reading, no other process can write Readers may not write and only read Solution when Reader has the Priority over Writer Here priority means, no reader should wait if the share is currently opened for reading. Three variables are used: mutex, wrt, readcnt to implement solution semaphore mutex, wrt; // semaphore mutex is used to ensure mutual exclusion when readcnt is updated i.e. when any reader enters or exit from the critical section and semaphore wrt is used by both readers and writersint readcnt; // readcnt tells the number of processes performing read in the critical section, initially 0 semaphore mutex, wrt; // semaphore mutex is used to ensure mutual exclusion when readcnt is updated i.e. when any reader enters or exit from the critical section and semaphore wrt is used by both readers and writers int readcnt; // readcnt tells the number of processes performing read in the critical section, initially 0 Functions for semaphore : – wait() : decrements the semaphore value. – signal() : increments the semaphore value. Writer process: Writer requests the entry to critical section.If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps on waiting.It exits the critical section. Writer requests the entry to critical section. If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps on waiting. It exits the critical section. do { // writer requests for critical section wait(wrt); // performs the write // leaves the critical section signal(wrt); } while(true); Reader process: Reader requests the entry to critical section.If allowed: it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside.It then, signals mutex as any other reader is allowed to enter while others are already reading.After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section.If not allowed, it keeps on waiting. Reader requests the entry to critical section. If allowed: it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside.It then, signals mutex as any other reader is allowed to enter while others are already reading.After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section. it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside. It then, signals mutex as any other reader is allowed to enter while others are already reading. After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section. If not allowed, it keeps on waiting. do { // Reader wants to enter the critical section wait(mutex); // The number of readers has now increased by 1 readcnt++; // there is atleast one reader in the critical section // this ensure no writer can enter if there is even one reader // thus we give preference to readers here if (readcnt==1) wait(wrt); // other readers can enter while this current reader is inside // the critical section signal(mutex); // current reader performs reading here wait(mutex); // a reader wants to leave readcnt--; // that is, no reader is left in the critical section, if (readcnt == 0) signal(wrt); // writers can enter signal(mutex); // reader leaves } while(true); Thus, the semaphore ‘wrt‘ is queued on both readers and writers in a manner such that preference is given to readers if writers are also there. Thus, no reader is waiting simply because a writer has requested to enter the critical section. Article contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Ankit Kumar Singh 2 simmytarika5 Process Synchronization Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Feb, 2022" }, { "code": null, "e": 126, "s": 54, "text": "Consider a situation where we have a file shared between many people. " }, { "code": null, "e": 284, "s": 126, "text": "If one of the people tries editing the file, no other person should be reading or writing at the same time, otherwise changes will not be visible to him/her." }, { "code": null, "e": 370, "s": 284, "text": "However if some person is reading the file, then others may read it at the same time." }, { "code": null, "e": 441, "s": 370, "text": "Precisely in OS we call this situation as the readers-writers problem " }, { "code": null, "e": 463, "s": 441, "text": "Problem parameters: " }, { "code": null, "e": 517, "s": 463, "text": "One set of data is shared among a number of processes" }, { "code": null, "e": 600, "s": 517, "text": "Once a writer is ready, it performs its write. Only one writer may write at a time" }, { "code": null, "e": 654, "s": 600, "text": "If a process is writing, no other process can read it" }, { "code": null, "e": 716, "s": 654, "text": "If at least one reader is reading, no other process can write" }, { "code": null, "e": 752, "s": 716, "text": "Readers may not write and only read" }, { "code": null, "e": 804, "s": 754, "text": "Solution when Reader has the Priority over Writer" }, { "code": null, "e": 894, "s": 804, "text": "Here priority means, no reader should wait if the share is currently opened for reading. " }, { "code": null, "e": 964, "s": 894, "text": "Three variables are used: mutex, wrt, readcnt to implement solution " }, { "code": null, "e": 1290, "s": 964, "text": "semaphore mutex, wrt; // semaphore mutex is used to ensure mutual exclusion when readcnt is updated i.e. when any reader enters or exit from the critical section and semaphore wrt is used by both readers and writersint readcnt; // readcnt tells the number of processes performing read in the critical section, initially 0" }, { "code": null, "e": 1506, "s": 1290, "text": "semaphore mutex, wrt; // semaphore mutex is used to ensure mutual exclusion when readcnt is updated i.e. when any reader enters or exit from the critical section and semaphore wrt is used by both readers and writers" }, { "code": null, "e": 1617, "s": 1506, "text": "int readcnt; // readcnt tells the number of processes performing read in the critical section, initially 0" }, { "code": null, "e": 1644, "s": 1617, "text": "Functions for semaphore : " }, { "code": null, "e": 1688, "s": 1644, "text": "– wait() : decrements the semaphore value. " }, { "code": null, "e": 1734, "s": 1688, "text": "– signal() : increments the semaphore value. " }, { "code": null, "e": 1752, "s": 1734, "text": "Writer process: " }, { "code": null, "e": 1942, "s": 1752, "text": "Writer requests the entry to critical section.If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps on waiting.It exits the critical section." }, { "code": null, "e": 1989, "s": 1942, "text": "Writer requests the entry to critical section." }, { "code": null, "e": 2103, "s": 1989, "text": "If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps on waiting." }, { "code": null, "e": 2134, "s": 2103, "text": "It exits the critical section." }, { "code": null, "e": 2301, "s": 2136, "text": "do {\n // writer requests for critical section\n wait(wrt); \n \n // performs the write\n\n // leaves the critical section\n signal(wrt);\n\n} while(true);" }, { "code": null, "e": 2319, "s": 2301, "text": "Reader process: " }, { "code": null, "e": 2900, "s": 2319, "text": "Reader requests the entry to critical section.If allowed: it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside.It then, signals mutex as any other reader is allowed to enter while others are already reading.After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section.If not allowed, it keeps on waiting." }, { "code": null, "e": 2947, "s": 2900, "text": "Reader requests the entry to critical section." }, { "code": null, "e": 3446, "s": 2947, "text": "If allowed: it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside.It then, signals mutex as any other reader is allowed to enter while others are already reading.After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section." }, { "code": null, "e": 3650, "s": 3446, "text": "it increments the count of number of readers inside the critical section. If this reader is the first reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside." }, { "code": null, "e": 3747, "s": 3650, "text": "It then, signals mutex as any other reader is allowed to enter while others are already reading." }, { "code": null, "e": 3935, "s": 3747, "text": "After performing reading, it exits the critical section. When exiting, it checks if no more reader is inside, it signals the semaphore “wrt” as now, writer can enter the critical section." }, { "code": null, "e": 3972, "s": 3935, "text": "If not allowed, it keeps on waiting." }, { "code": null, "e": 4791, "s": 3974, "text": "do {\n \n // Reader wants to enter the critical section\n wait(mutex);\n\n // The number of readers has now increased by 1\n readcnt++; \n\n // there is atleast one reader in the critical section\n // this ensure no writer can enter if there is even one reader\n // thus we give preference to readers here\n if (readcnt==1) \n wait(wrt); \n\n // other readers can enter while this current reader is inside \n // the critical section\n signal(mutex); \n\n // current reader performs reading here\n wait(mutex); // a reader wants to leave\n\n readcnt--;\n\n // that is, no reader is left in the critical section,\n if (readcnt == 0) \n signal(wrt); // writers can enter\n\n signal(mutex); // reader leaves\n\n} while(true);" }, { "code": null, "e": 5032, "s": 4791, "text": "Thus, the semaphore ‘wrt‘ is queued on both readers and writers in a manner such that preference is given to readers if writers are also there. Thus, no reader is waiting simply because a writer has requested to enter the critical section. " }, { "code": null, "e": 5191, "s": 5032, "text": "Article contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5211, "s": 5191, "text": "Ankit Kumar Singh 2" }, { "code": null, "e": 5224, "s": 5211, "text": "simmytarika5" }, { "code": null, "e": 5248, "s": 5224, "text": "Process Synchronization" }, { "code": null, "e": 5266, "s": 5248, "text": "Operating Systems" }, { "code": null, "e": 5284, "s": 5266, "text": "Operating Systems" } ]
Pandas Groupby and Computing Median
13 Jul, 2021 The Pandas in Python is known as the most popular and powerful tool for performing data analysis. It because of the beauty of Pandas functionality and the ability to work on sets and subsets of the large dataset. So in this article, we are going to study how pandas Group By functionality works and saves tons of effort while working on a large dataset. Also, we will solve real-world problems using Pandas Group By and Median functionalities. The groupby() method in pandas splits the dataset into subsets to make computations easier. Generally, groupby() splits the data, applies the functionalities, and then combine the result for us. Let’s take an example if we have data on alcohol consumption of different countries and we want to perform data analysis continent-wise, this problem can be minimized using groupby() method in pandas. It splits the data continent-wise and calculates median using the median() method. Syntax : DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True) Example 1: Find the median of alcohol consumption continent-wise on a given dataset. Dataset: Drinksbycountry.csv Python3 # import the packagesimport pandas as pd # read Datasetdata = pd.read_csv("drinksbycountry.csv")data.head() # perform groupby on continent and find median# of total_litres_of_pure_alcoholdata.groupby(["continent"])["total_litres_of_pure_alcohol"].median() # perform groupby on continent and find median# of wine_servingdata.groupby(["continent"])["wine_servings"].median() Output : median of total_litres_of_pure_alcohol median of wine_serving Example 2: Find the median of the total population group by age on a given dataset. Dataset: WorldPopulationByAge2020.csv Python3 # import packagesimport pandas as pd # read Datasetdata = pd.read_csv("WorldPopulationByAge2020.csv")data.head() # perform group by AgeGrp and find mediandata.groupby(["AgeGrp"])["PopTotal"].median() Output : Group by Age anikakapoor Python pandas-groupby Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jul, 2021" }, { "code": null, "e": 498, "s": 54, "text": "The Pandas in Python is known as the most popular and powerful tool for performing data analysis. It because of the beauty of Pandas functionality and the ability to work on sets and subsets of the large dataset. So in this article, we are going to study how pandas Group By functionality works and saves tons of effort while working on a large dataset. Also, we will solve real-world problems using Pandas Group By and Median functionalities." }, { "code": null, "e": 977, "s": 498, "text": "The groupby() method in pandas splits the dataset into subsets to make computations easier. Generally, groupby() splits the data, applies the functionalities, and then combine the result for us. Let’s take an example if we have data on alcohol consumption of different countries and we want to perform data analysis continent-wise, this problem can be minimized using groupby() method in pandas. It splits the data continent-wise and calculates median using the median() method." }, { "code": null, "e": 986, "s": 977, "text": "Syntax :" }, { "code": null, "e": 1132, "s": 986, "text": "DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True) " }, { "code": null, "e": 1217, "s": 1132, "text": "Example 1: Find the median of alcohol consumption continent-wise on a given dataset." }, { "code": null, "e": 1246, "s": 1217, "text": "Dataset: Drinksbycountry.csv" }, { "code": null, "e": 1254, "s": 1246, "text": "Python3" }, { "code": "# import the packagesimport pandas as pd # read Datasetdata = pd.read_csv(\"drinksbycountry.csv\")data.head() # perform groupby on continent and find median# of total_litres_of_pure_alcoholdata.groupby([\"continent\"])[\"total_litres_of_pure_alcohol\"].median() # perform groupby on continent and find median# of wine_servingdata.groupby([\"continent\"])[\"wine_servings\"].median()", "e": 1627, "s": 1254, "text": null }, { "code": null, "e": 1636, "s": 1627, "text": "Output :" }, { "code": null, "e": 1675, "s": 1636, "text": "median of total_litres_of_pure_alcohol" }, { "code": null, "e": 1698, "s": 1675, "text": "median of wine_serving" }, { "code": null, "e": 1782, "s": 1698, "text": "Example 2: Find the median of the total population group by age on a given dataset." }, { "code": null, "e": 1820, "s": 1782, "text": "Dataset: WorldPopulationByAge2020.csv" }, { "code": null, "e": 1828, "s": 1820, "text": "Python3" }, { "code": "# import packagesimport pandas as pd # read Datasetdata = pd.read_csv(\"WorldPopulationByAge2020.csv\")data.head() # perform group by AgeGrp and find mediandata.groupby([\"AgeGrp\"])[\"PopTotal\"].median()", "e": 2028, "s": 1828, "text": null }, { "code": null, "e": 2037, "s": 2028, "text": "Output :" }, { "code": null, "e": 2051, "s": 2037, "text": "Group by Age " }, { "code": null, "e": 2063, "s": 2051, "text": "anikakapoor" }, { "code": null, "e": 2085, "s": 2063, "text": "Python pandas-groupby" }, { "code": null, "e": 2099, "s": 2085, "text": "Python-pandas" }, { "code": null, "e": 2123, "s": 2099, "text": "Technical Scripter 2020" }, { "code": null, "e": 2130, "s": 2123, "text": "Python" }, { "code": null, "e": 2149, "s": 2130, "text": "Technical Scripter" }, { "code": null, "e": 2247, "s": 2149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2279, "s": 2247, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2306, "s": 2279, "text": "Python Classes and Objects" }, { "code": null, "e": 2337, "s": 2306, "text": "Python | os.path.join() method" }, { "code": null, "e": 2360, "s": 2337, "text": "Introduction To PYTHON" }, { "code": null, "e": 2381, "s": 2360, "text": "Python OOPs Concepts" }, { "code": null, "e": 2437, "s": 2381, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2479, "s": 2437, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2521, "s": 2479, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2560, "s": 2521, "text": "Python | Get unique values from a list" } ]
Python Program for Min Cost Path
08 Jun, 2022 Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.For example, in the following figure, what is the minimum cost path to (2, 2)? The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3). Python # Dynamic Programming Python implementation of Min Cost Path# problemR = 3C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m + 1][n + 1] or # dynamically allocate memory to save space. The following # line is used to keep te program simple and make it working # on all compilers. tc = [[0 for x in range(C)] for x in range(R)] tc[0][0] = cost[0][0] # Initialize first column of total cost(tc) array for i in range(1, m + 1): tc[i][0] = tc[i-1][0] + cost[i][0] # Initialize first row of tc array for j in range(1, n + 1): tc[0][j] = tc[0][j-1] + cost[0][j] # Construct rest of the tc array for i in range(1, m + 1): for j in range(1, n + 1): tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j] return tc[m][n] # Driver program to test above functionscost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]print(minCost(cost, 2, 2)) # This code is contributed by Bhavya Jain 8 Time Complexity: O(m*n) Auxiliary Space: O(m*n) Please refer complete article on Dynamic Programming | Set 6 (Min Cost Path) for more details! simmytarika5 chandramauliguptach Python DSA-exercises Dynamic Programming Python Programs Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Count number of binary strings without consecutive 1's Find if a string is interleaved of two other strings | DP-33 Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 668, "s": 28, "text": "Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.For example, in the following figure, what is the minimum cost path to (2, 2)? " }, { "code": null, "e": 830, "s": 668, "text": "The path with minimum cost is highlighted in the following figure. The path is (0, 0) –> (0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3). " }, { "code": null, "e": 837, "s": 830, "text": "Python" }, { "code": "# Dynamic Programming Python implementation of Min Cost Path# problemR = 3C = 3 def minCost(cost, m, n): # Instead of following line, we can use int tc[m + 1][n + 1] or # dynamically allocate memory to save space. The following # line is used to keep te program simple and make it working # on all compilers. tc = [[0 for x in range(C)] for x in range(R)] tc[0][0] = cost[0][0] # Initialize first column of total cost(tc) array for i in range(1, m + 1): tc[i][0] = tc[i-1][0] + cost[i][0] # Initialize first row of tc array for j in range(1, n + 1): tc[0][j] = tc[0][j-1] + cost[0][j] # Construct rest of the tc array for i in range(1, m + 1): for j in range(1, n + 1): tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j] return tc[m][n] # Driver program to test above functionscost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]print(minCost(cost, 2, 2)) # This code is contributed by Bhavya Jain", "e": 1856, "s": 837, "text": null }, { "code": null, "e": 1858, "s": 1856, "text": "8" }, { "code": null, "e": 1884, "s": 1860, "text": "Time Complexity: O(m*n)" }, { "code": null, "e": 1908, "s": 1884, "text": "Auxiliary Space: O(m*n)" }, { "code": null, "e": 2004, "s": 1908, "text": "Please refer complete article on Dynamic Programming | Set 6 (Min Cost Path) for more details! " }, { "code": null, "e": 2017, "s": 2004, "text": "simmytarika5" }, { "code": null, "e": 2037, "s": 2017, "text": "chandramauliguptach" }, { "code": null, "e": 2058, "s": 2037, "text": "Python DSA-exercises" }, { "code": null, "e": 2078, "s": 2058, "text": "Dynamic Programming" }, { "code": null, "e": 2094, "s": 2078, "text": "Python Programs" }, { "code": null, "e": 2114, "s": 2094, "text": "Dynamic Programming" }, { "code": null, "e": 2212, "s": 2114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2280, "s": 2212, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 2335, "s": 2280, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 2396, "s": 2335, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 2456, "s": 2396, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 2507, "s": 2456, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 2550, "s": 2507, "text": "Python program to convert a list to string" }, { "code": null, "e": 2572, "s": 2550, "text": "Defaultdict in Python" }, { "code": null, "e": 2611, "s": 2572, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2649, "s": 2611, "text": "Python | Convert a list to dictionary" } ]
write() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint write - write to a file descriptor #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); write() writes up to count bytes to the file referenced by the file descriptor fd from the buffer starting at buf. POSIX requires that a read() which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming. On success, the number of bytes written are returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. If count is zero and the file descriptor refers to a regular file, 0 may be returned, or an error could be detected. For a special file, the results are not portable. Other errors may occur, depending on the object connected to fd. SVr4, 4.3BSD, POSIX.1-2001. Under SVr4 a write may be interrupted and return EINTR at any point, not just before any data is written. A successful return from write() does not make any guarantee that data has been committed to disk. In fact, on some buggy implementations, it does not even guarantee that space has successfully been reserved for the data. The only way to be sure is to call fsync(2) after you are done writing all your data.
[ { "code": null, "e": 1600, "s": 1588, "text": "Unix - Home" }, { "code": null, "e": 1623, "s": 1600, "text": "Unix - Getting Started" }, { "code": null, "e": 1646, "s": 1623, "text": "Unix - File Management" }, { "code": null, "e": 1665, "s": 1646, "text": "Unix - Directories" }, { "code": null, "e": 1688, "s": 1665, "text": "Unix - File Permission" }, { "code": null, "e": 1707, "s": 1688, "text": "Unix - Environment" }, { "code": null, "e": 1730, "s": 1707, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1753, "s": 1730, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1770, "s": 1753, "text": "Unix - Processes" }, { "code": null, "e": 1791, "s": 1770, "text": "Unix - Communication" }, { "code": null, "e": 1812, "s": 1791, "text": "Unix - The vi Editor" }, { "code": null, "e": 1834, "s": 1812, "text": "Unix - What is Shell?" }, { "code": null, "e": 1857, "s": 1834, "text": "Unix - Using Variables" }, { "code": null, "e": 1882, "s": 1857, "text": "Unix - Special Variables" }, { "code": null, "e": 1902, "s": 1882, "text": "Unix - Using Arrays" }, { "code": null, "e": 1925, "s": 1902, "text": "Unix - Basic Operators" }, { "code": null, "e": 1948, "s": 1925, "text": "Unix - Decision Making" }, { "code": null, "e": 1967, "s": 1948, "text": "Unix - Shell Loops" }, { "code": null, "e": 1987, "s": 1967, "text": "Unix - Loop Control" }, { "code": null, "e": 2014, "s": 1987, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 2040, "s": 2014, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 2063, "s": 2040, "text": "Unix - IO Redirections" }, { "code": null, "e": 2086, "s": 2063, "text": "Unix - Shell Functions" }, { "code": null, "e": 2106, "s": 2086, "text": "Unix - Manpage Help" }, { "code": null, "e": 2133, "s": 2106, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2159, "s": 2133, "text": "Unix - File System Basics" }, { "code": null, "e": 2186, "s": 2159, "text": "Unix - User Administration" }, { "code": null, "e": 2212, "s": 2186, "text": "Unix - System Performance" }, { "code": null, "e": 2234, "s": 2212, "text": "Unix - System Logging" }, { "code": null, "e": 2259, "s": 2234, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2282, "s": 2259, "text": "Unix - Useful Commands" }, { "code": null, "e": 2301, "s": 2282, "text": "Unix - Quick Guide" }, { "code": null, "e": 2326, "s": 2301, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2346, "s": 2326, "text": "Unix - System Calls" }, { "code": null, "e": 2367, "s": 2346, "text": "Unix - Commands List" }, { "code": null, "e": 2389, "s": 2367, "text": "Unix Useful Resources" }, { "code": null, "e": 2407, "s": 2389, "text": "Computer Glossary" }, { "code": null, "e": 2418, "s": 2407, "text": "Who is Who" }, { "code": null, "e": 2453, "s": 2418, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2488, "s": 2453, "text": "write - write to a file descriptor" }, { "code": null, "e": 2565, "s": 2488, "text": "#include <unistd.h> \nssize_t write(int fd, const void *buf, size_t count); \n" }, { "code": null, "e": 2622, "s": 2565, "text": "\nssize_t write(int fd, const void *buf, size_t count); \n" }, { "code": null, "e": 2900, "s": 2622, "text": "write() writes up to count bytes to the file referenced by the file descriptor\nfd from the buffer starting at\nbuf. POSIX requires that a read() which can be proved to occur after a\nwrite() has returned returns the new data. Note that not all file\nsystems are POSIX conforming." }, { "code": null, "e": 3051, "s": 2900, "text": "On success, the number of bytes written are returned (zero indicates \nnothing was written). On error, -1 is returned, and errno is set\nappropriately." }, { "code": null, "e": 3218, "s": 3051, "text": "If count is zero and the file descriptor refers to\na regular file, 0 may be returned, or an error could be detected.\nFor a special file, the results are not portable." }, { "code": null, "e": 3284, "s": 3218, "text": "Other errors may occur, depending on the object connected to fd. " }, { "code": null, "e": 3419, "s": 3284, "text": "SVr4, 4.3BSD, POSIX.1-2001. Under SVr4 a write may be interrupted and return EINTR at any point,\nnot just before any data is written." } ]
Stratified Sampling in Pandas
02 Nov, 2021 Stratified Sampling is a sampling technique used to obtain samples that best represent the population. It reduces bias in selecting samples by dividing the population into homogeneous subgroups called strata, and randomly sampling data from each stratum(singular form of strata). In statistics, stratified sampling is used when the mean values of each stratum will differ. In Machine learning, stratified sampling is commonly used to create test datasets to evaluate models especially when the dataset is significantly large and unbalanced. Separating the Population into Strata: In this step, the population is divided into strata based on similar characteristics and every member of the population must belong to exactly one stratum (singular of strata). Determine the sample size: Decide how small or large the sample should be. Randomly sampling each stratum: Random samples from each stratum are selected using either Disproportionate sampling where the sample size of each stratum is equal irrespective of the population size of the stratum or Proportionate sampling where the sample size of each stratum is proportional to the population size of the stratum. In this example, we have a dummy dataset of 10 students and we will sample out 6 students based on their grades, using both disproportionate and proportionate stratified sampling. Step 1: Create the dummy dataset from a python dictionary using pandas DataFrame Python3 import pandas as pd # Create a dictionary of studentsstudents = { 'Name': ['Lisa', 'Kate', 'Ben', 'Kim', 'Josh', 'Alex', 'Evan', 'Greg', 'Sam', 'Ella'], 'ID': ['001', '002', '003', '004', '005', '006', '007', '008', '009', '010'], 'Grade': ['A', 'A', 'C', 'B', 'B', 'B', 'C', 'A', 'A', 'A'], 'Category': [2, 3, 1, 3, 2, 3, 3, 1, 2, 1]} # Create dataframe from students dictionarydf = pd.DataFrame(students) # view the dataframedf Output: Notice that there are 50% grade A students, 30% grade B students, and 20% grade C students. Step 2: Create a sample of 6 students disproportionately (equal number of students from each grade stratum) Disproportionate Sampling: Using pandas groupby, separate the students into groups based on their grade i.e A, B, C and randomly sample 2 students from each grade group using the sample function Python3 df.groupby('Grade', group_keys=False).apply(lambda x: x.sample(2)) Output: Step 3: Sample out 60% of students proportionately (create proportional samples from each stratum based on its proportion in the population) Proportionate Sampling: Using pandas groupby, separate the students into groups based on their grade i.e A, B, C, and random sample from each group based on population proportion. The total sample size is 60%(0.6) of the population Python3 df.groupby('Grade', group_keys=False).apply(lambda x: x.sample(frac=0.6)) Output: Notice that even in the sample, there are 50% grade A students, 30% grade B students, and 20% grade C students. In this example, we will be creating sample data from the train dataset. Titanic was a British passenger that sank in the North Atlantic Ocean after striking an iceberg. The dataset contains information on all passengers who boarded the Titanic, a passenger either died or survived the crash, so we will be using the Survived column as our stratifying column. Step 1: Read in the dataset from the CSV file Python3 import pandas as pd # read the dataset as csv filedata = pd.read_csv('Titanic.csv') # drop the name column as it is of no importance heredata.drop('Name', axis=1, inplace=True) # view the first 5 rows of the titanic datasetdata.head() Output: Step 2: Check the percentage of dead/survived passengers Check the proportion/percentage of passengers who died or survived this is given a number of dead or alive passengers / total number of passengers * 100 Python3 (data['Survived'].value_counts()) / len(data) * 100 Output: 0 61.616162 1 38.383838 where 0 represents passengers that died (61.6%) and 1 represents passengers that survived (38.4%) Step 3: Disproportionately sample out 8 passengers (4 who died and 4 who survived) Python3 # Disproportionate sampling:# randomly select 4 samples from each stratum data.groupby('Survived', group_keys=False).apply(lambda x: x.sample(4)) Output: Step 4: Proportionately sample out 1%(0.01) of passengers (0.6% died and 0.4% survived) Python3 data.groupby('Survived', group_keys=False).apply(lambda x: x.sample(frac=0.01)) Output: prachisoda1234 Blogathon-2021 Picked Python-pandas Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Nov, 2021" }, { "code": null, "e": 334, "s": 53, "text": "Stratified Sampling is a sampling technique used to obtain samples that best represent the population. It reduces bias in selecting samples by dividing the population into homogeneous subgroups called strata, and randomly sampling data from each stratum(singular form of strata). " }, { "code": null, "e": 597, "s": 334, "text": "In statistics, stratified sampling is used when the mean values of each stratum will differ. In Machine learning, stratified sampling is commonly used to create test datasets to evaluate models especially when the dataset is significantly large and unbalanced. " }, { "code": null, "e": 813, "s": 597, "text": "Separating the Population into Strata: In this step, the population is divided into strata based on similar characteristics and every member of the population must belong to exactly one stratum (singular of strata)." }, { "code": null, "e": 888, "s": 813, "text": "Determine the sample size: Decide how small or large the sample should be." }, { "code": null, "e": 1222, "s": 888, "text": "Randomly sampling each stratum: Random samples from each stratum are selected using either Disproportionate sampling where the sample size of each stratum is equal irrespective of the population size of the stratum or Proportionate sampling where the sample size of each stratum is proportional to the population size of the stratum." }, { "code": null, "e": 1402, "s": 1222, "text": "In this example, we have a dummy dataset of 10 students and we will sample out 6 students based on their grades, using both disproportionate and proportionate stratified sampling." }, { "code": null, "e": 1484, "s": 1402, "text": "Step 1: Create the dummy dataset from a python dictionary using pandas DataFrame " }, { "code": null, "e": 1492, "s": 1484, "text": "Python3" }, { "code": "import pandas as pd # Create a dictionary of studentsstudents = { 'Name': ['Lisa', 'Kate', 'Ben', 'Kim', 'Josh', 'Alex', 'Evan', 'Greg', 'Sam', 'Ella'], 'ID': ['001', '002', '003', '004', '005', '006', '007', '008', '009', '010'], 'Grade': ['A', 'A', 'C', 'B', 'B', 'B', 'C', 'A', 'A', 'A'], 'Category': [2, 3, 1, 3, 2, 3, 3, 1, 2, 1]} # Create dataframe from students dictionarydf = pd.DataFrame(students) # view the dataframedf", "e": 1978, "s": 1492, "text": null }, { "code": null, "e": 1986, "s": 1978, "text": "Output:" }, { "code": null, "e": 2078, "s": 1986, "text": "Notice that there are 50% grade A students, 30% grade B students, and 20% grade C students." }, { "code": null, "e": 2186, "s": 2078, "text": "Step 2: Create a sample of 6 students disproportionately (equal number of students from each grade stratum)" }, { "code": null, "e": 2381, "s": 2186, "text": "Disproportionate Sampling: Using pandas groupby, separate the students into groups based on their grade i.e A, B, C and randomly sample 2 students from each grade group using the sample function" }, { "code": null, "e": 2389, "s": 2381, "text": "Python3" }, { "code": "df.groupby('Grade', group_keys=False).apply(lambda x: x.sample(2))", "e": 2456, "s": 2389, "text": null }, { "code": null, "e": 2464, "s": 2456, "text": "Output:" }, { "code": null, "e": 2605, "s": 2464, "text": "Step 3: Sample out 60% of students proportionately (create proportional samples from each stratum based on its proportion in the population)" }, { "code": null, "e": 2837, "s": 2605, "text": "Proportionate Sampling: Using pandas groupby, separate the students into groups based on their grade i.e A, B, C, and random sample from each group based on population proportion. The total sample size is 60%(0.6) of the population" }, { "code": null, "e": 2845, "s": 2837, "text": "Python3" }, { "code": "df.groupby('Grade', group_keys=False).apply(lambda x: x.sample(frac=0.6))", "e": 2919, "s": 2845, "text": null }, { "code": null, "e": 2928, "s": 2919, "text": "Output: " }, { "code": null, "e": 3040, "s": 2928, "text": "Notice that even in the sample, there are 50% grade A students, 30% grade B students, and 20% grade C students." }, { "code": null, "e": 3400, "s": 3040, "text": "In this example, we will be creating sample data from the train dataset. Titanic was a British passenger that sank in the North Atlantic Ocean after striking an iceberg. The dataset contains information on all passengers who boarded the Titanic, a passenger either died or survived the crash, so we will be using the Survived column as our stratifying column." }, { "code": null, "e": 3446, "s": 3400, "text": "Step 1: Read in the dataset from the CSV file" }, { "code": null, "e": 3454, "s": 3446, "text": "Python3" }, { "code": "import pandas as pd # read the dataset as csv filedata = pd.read_csv('Titanic.csv') # drop the name column as it is of no importance heredata.drop('Name', axis=1, inplace=True) # view the first 5 rows of the titanic datasetdata.head()", "e": 3692, "s": 3454, "text": null }, { "code": null, "e": 3700, "s": 3692, "text": "Output:" }, { "code": null, "e": 3757, "s": 3700, "text": "Step 2: Check the percentage of dead/survived passengers" }, { "code": null, "e": 3910, "s": 3757, "text": "Check the proportion/percentage of passengers who died or survived this is given a number of dead or alive passengers / total number of passengers * 100" }, { "code": null, "e": 3918, "s": 3910, "text": "Python3" }, { "code": "(data['Survived'].value_counts()) / len(data) * 100", "e": 3970, "s": 3918, "text": null }, { "code": null, "e": 3978, "s": 3970, "text": "Output:" }, { "code": null, "e": 4008, "s": 3978, "text": "0 61.616162\n1 38.383838" }, { "code": null, "e": 4106, "s": 4008, "text": "where 0 represents passengers that died (61.6%) and 1 represents passengers that survived (38.4%)" }, { "code": null, "e": 4190, "s": 4106, "text": "Step 3: Disproportionately sample out 8 passengers (4 who died and 4 who survived)" }, { "code": null, "e": 4198, "s": 4190, "text": "Python3" }, { "code": "# Disproportionate sampling:# randomly select 4 samples from each stratum data.groupby('Survived', group_keys=False).apply(lambda x: x.sample(4))", "e": 4345, "s": 4198, "text": null }, { "code": null, "e": 4353, "s": 4345, "text": "Output:" }, { "code": null, "e": 4443, "s": 4353, "text": "Step 4: Proportionately sample out 1%(0.01) of passengers (0.6% died and 0.4% survived)" }, { "code": null, "e": 4451, "s": 4443, "text": "Python3" }, { "code": "data.groupby('Survived', group_keys=False).apply(lambda x: x.sample(frac=0.01))", "e": 4531, "s": 4451, "text": null }, { "code": null, "e": 4539, "s": 4531, "text": "Output:" }, { "code": null, "e": 4554, "s": 4539, "text": "prachisoda1234" }, { "code": null, "e": 4569, "s": 4554, "text": "Blogathon-2021" }, { "code": null, "e": 4576, "s": 4569, "text": "Picked" }, { "code": null, "e": 4590, "s": 4576, "text": "Python-pandas" }, { "code": null, "e": 4600, "s": 4590, "text": "Blogathon" }, { "code": null, "e": 4607, "s": 4600, "text": "Python" } ]
Python 3 – input() function
06 Oct, 2020 In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string. Syntax: input(prompt) Parameter: Prompt: (optional) The string that is written to standard output(usually screen) without newline. Return: String object Let’s see the examples: Example 1: Taking input from the user. Python3 # Taking input from the userstring = input() # Outputprint(string) Output: geeksforgeeks Example 2: Taking input from the user with a message. Python # Taking input from the username = input("Enter your name") # Outputprint("Hello", name) Output: Enter your name:ankit rai Hello ankit rai Example 3: By default input() function takes the user’s input in a string. So, to take the input in the form of int you need to use int() along with the input function. Python3 # Taking input from the user as integernum = int(input("Enter a number:"))add = num + 1 # Outputprint(add) Output: Enter a number:15 16 Example 4: Let’s take float input along with the input function. Python3 # Taking input from the user as float num =float(input("Enter number "))add = num + 1 # outputprint(add) Output: Enter number 5 6.0 Example 5: Let’s take list input along with the input function. Python3 # Taking input from the user as list li =list(input("Enter number ")) # outputprint(li) Output: Enter number 12345 ['1', '2', '3', '4', '5'] Example 6: Let’s take tuple input along with the input function. Python3 # Taking input from the user as tuple num =tuple(input("Enter number ")) # outputprint(num) Output: Enter number 123 ('1', '2', '3') kumar_satyam python-input-output 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Oct, 2020" }, { "code": null, "e": 272, "s": 54, "text": "In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string." }, { "code": null, "e": 294, "s": 272, "text": "Syntax: input(prompt)" }, { "code": null, "e": 305, "s": 294, "text": "Parameter:" }, { "code": null, "e": 403, "s": 305, "text": "Prompt: (optional) The string that is written to standard output(usually screen) without newline." }, { "code": null, "e": 425, "s": 403, "text": "Return: String object" }, { "code": null, "e": 449, "s": 425, "text": "Let’s see the examples:" }, { "code": null, "e": 488, "s": 449, "text": "Example 1: Taking input from the user." }, { "code": null, "e": 496, "s": 488, "text": "Python3" }, { "code": "# Taking input from the userstring = input() # Outputprint(string)", "e": 563, "s": 496, "text": null }, { "code": null, "e": 573, "s": 563, "text": " Output:" }, { "code": null, "e": 590, "s": 573, "text": "geeksforgeeks\n\n\n" }, { "code": null, "e": 646, "s": 592, "text": "Example 2: Taking input from the user with a message." }, { "code": null, "e": 653, "s": 646, "text": "Python" }, { "code": "# Taking input from the username = input(\"Enter your name\") # Outputprint(\"Hello\", name)", "e": 742, "s": 653, "text": null }, { "code": null, "e": 752, "s": 742, "text": " Output:" }, { "code": null, "e": 797, "s": 752, "text": "Enter your name:ankit rai\nHello ankit rai\n\n\n" }, { "code": null, "e": 968, "s": 799, "text": "Example 3: By default input() function takes the user’s input in a string. So, to take the input in the form of int you need to use int() along with the input function." }, { "code": null, "e": 976, "s": 968, "text": "Python3" }, { "code": "# Taking input from the user as integernum = int(input(\"Enter a number:\"))add = num + 1 # Outputprint(add)", "e": 1083, "s": 976, "text": null }, { "code": null, "e": 1091, "s": 1083, "text": "Output:" }, { "code": null, "e": 1113, "s": 1091, "text": "Enter a number:15\n16\n" }, { "code": null, "e": 1179, "s": 1113, "text": "Example 4: Let’s take float input along with the input function." }, { "code": null, "e": 1187, "s": 1179, "text": "Python3" }, { "code": "# Taking input from the user as float num =float(input(\"Enter number \"))add = num + 1 # outputprint(add)", "e": 1292, "s": 1187, "text": null }, { "code": null, "e": 1300, "s": 1292, "text": "Output:" }, { "code": null, "e": 1320, "s": 1300, "text": "Enter number 5\n6.0\n" }, { "code": null, "e": 1384, "s": 1320, "text": "Example 5: Let’s take list input along with the input function." }, { "code": null, "e": 1392, "s": 1384, "text": "Python3" }, { "code": "# Taking input from the user as list li =list(input(\"Enter number \")) # outputprint(li)", "e": 1480, "s": 1392, "text": null }, { "code": null, "e": 1488, "s": 1480, "text": "Output:" }, { "code": null, "e": 1534, "s": 1488, "text": "Enter number 12345\n['1', '2', '3', '4', '5']\n" }, { "code": null, "e": 1599, "s": 1534, "text": "Example 6: Let’s take tuple input along with the input function." }, { "code": null, "e": 1607, "s": 1599, "text": "Python3" }, { "code": "# Taking input from the user as tuple num =tuple(input(\"Enter number \")) # outputprint(num)", "e": 1699, "s": 1607, "text": null }, { "code": null, "e": 1707, "s": 1699, "text": "Output:" }, { "code": null, "e": 1741, "s": 1707, "text": "Enter number 123\n('1', '2', '3')\n" }, { "code": null, "e": 1754, "s": 1741, "text": "kumar_satyam" }, { "code": null, "e": 1774, "s": 1754, "text": "python-input-output" }, { "code": null, "e": 1781, "s": 1774, "text": "Python" }, { "code": null, "e": 1879, "s": 1781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1911, "s": 1879, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1938, "s": 1911, "text": "Python Classes and Objects" }, { "code": null, "e": 1959, "s": 1938, "text": "Python OOPs Concepts" }, { "code": null, "e": 1982, "s": 1959, "text": "Introduction To PYTHON" }, { "code": null, "e": 2038, "s": 1982, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2069, "s": 2038, "text": "Python | os.path.join() method" }, { "code": null, "e": 2111, "s": 2069, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2153, "s": 2111, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2192, "s": 2153, "text": "Python | datetime.timedelta() function" } ]
Check if a number is multiple of 9 using bitwise operators
26 May, 2022 Given a number n, write a function that returns true if n is divisible by 9, else false. The most simple way to check for n’s divisibility by 9 is to do n%9. Another method is to sum the digits of n. If sum of digits is multiple of 9, then n is multiple of 9. The above methods are not bitwise operators based methods and require use of % and /. The bitwise operators are generally faster than modulo and division operators. Following is a bitwise operator based method to check divisibility by 9. C++ Java Python3 C# PHP Javascript // C++ program to check if a number// is multiple of 9 using bitwise operators#include <bits/stdc++.h>using namespace std; // Bitwise operator based function to check divisibility by 9bool isDivBy9(int n){ // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7));} // Driver program to test above functionint main(){ // Let us print all multiples of 9 from 0 to 100 // using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) cout << i << " "; return 0;} // Java program to check if a number// is multiple of 9 using bitwise operatorsimport java.lang.*; class GFG { // Bitwise operator based function // to check divisibility by 9 static boolean isDivBy9(int n) { // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7)); } // Driver code public static void main(String arg[]) { // Let us print all multiples of 9 from // 0 to 100 using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) System.out.print(i + " "); }} // This code is contributed by Anant Agarwal. # Bitwise operator based# function to check divisibility by 9 def isDivBy9(n): # Base cases if (n == 0 or n == 9): return True if (n < 9): return False # If n is greater than 9, # then recur for [floor(n / 9) - n % 8] return isDivBy9((int)(n>>3) - (int)(n&7)) # Driver code # Let us print all multiples# of 9 from 0 to 100# using above methodfor i in range(100): if (isDivBy9(i)): print(i, " ", end ="") # This code is contributed# by Anant Agarwal. // C# program to check if a number// is multiple of 9 using bitwise operatorsusing System; class GFG { // Bitwise operator based function // to check divisibility by 9 static bool isDivBy9(int n) { // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7)); } // Driver code public static void Main() { // Let us print all multiples of 9 from // 0 to 100 using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) Console.Write(i + " "); }} // This code is contributed by nitin mittal. <?php// PHP program to check if a number// is multiple of 9 using bitwise// operators // Bitwise operator based function// to check divisibility by 9function isDivBy9($n){ // Base cases if ($n == 0 || $n == 9) return true; if ($n < 9) return false; // If n is greater than 9, // then recur for [floor(n/9) - // n%8] return isDivBy9(($n >> 3) - ($n & 7));} // Driver Code // Let us print all multiples // of 9 from 0 to 100 // using above method for ($i = 0; $i < 100; $i++) if (isDivBy9($i)) echo $i ," "; // This code is contributed by nitin mittal?> <script>// javascript program to check if a number// is multiple of 9 using bitwise operators // Bitwise operator based function// to check divisibility by 9function isDivBy9(n){ // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9(parseInt(n >> 3) - parseInt(n & 7));} // Driver code // Let us print all multiples of 9 from// 0 to 100 using above methodfor (i = 0; i < 100; i++) if (isDivBy9(i)) document.write(i + " "); // This code is contributed by Princi Singh</script> Output: 0 9 18 27 36 45 54 63 72 81 90 99 Time Complexity: O(log n) Auxiliary Space: O(logn)How does this work? n/9 can be written in terms of n/8 using the following simple formula. n/9 = n/8 - n/72 Since we need to use bitwise operators, we get the value of floor(n/8) using n>>3 and get value of n%8 using n&7. We need to write above expression in terms of floor(n/8) and n%8. n/8 is equal to “floor(n/8) + (n%8)/8”. Let us write the above expression in terms of floor(n/8) and n%8 n/9 = floor(n/8) + (n%8)/8 - [floor(n/8) + (n%8)/8]/9 n/9 = floor(n/8) - [floor(n/8) - 9(n%8)/8 + (n%8)/8]/9 n/9 = floor(n/8) - [floor(n/8) - n%8]/9 From above equation, n is a multiple of 9 only if the expression floor(n/8) – [floor(n/8) – n%8]/9 is an integer. This expression can only be an integer if the sub-expression [floor(n/8) – n%8]/9 is an integer. The subexpression can only be an integer if [floor(n/8) – n%8] is a multiple of 9. So the problem reduces to a smaller value which can be written in terms of bitwise operators.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal princi singh ankita_saini ranjanrohit840 divisibility Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator Bit Fields in C Find the element that appears once C++ bitset and its application Add two numbers without using arithmetic operators Cyclic Redundancy Check and Modulo-2 Division
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2022" }, { "code": null, "e": 552, "s": 52, "text": "Given a number n, write a function that returns true if n is divisible by 9, else false. The most simple way to check for n’s divisibility by 9 is to do n%9. Another method is to sum the digits of n. If sum of digits is multiple of 9, then n is multiple of 9. The above methods are not bitwise operators based methods and require use of % and /. The bitwise operators are generally faster than modulo and division operators. Following is a bitwise operator based method to check divisibility by 9. " }, { "code": null, "e": 556, "s": 552, "text": "C++" }, { "code": null, "e": 561, "s": 556, "text": "Java" }, { "code": null, "e": 569, "s": 561, "text": "Python3" }, { "code": null, "e": 572, "s": 569, "text": "C#" }, { "code": null, "e": 576, "s": 572, "text": "PHP" }, { "code": null, "e": 587, "s": 576, "text": "Javascript" }, { "code": "// C++ program to check if a number// is multiple of 9 using bitwise operators#include <bits/stdc++.h>using namespace std; // Bitwise operator based function to check divisibility by 9bool isDivBy9(int n){ // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7));} // Driver program to test above functionint main(){ // Let us print all multiples of 9 from 0 to 100 // using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) cout << i << \" \"; return 0;}", "e": 1235, "s": 587, "text": null }, { "code": "// Java program to check if a number// is multiple of 9 using bitwise operatorsimport java.lang.*; class GFG { // Bitwise operator based function // to check divisibility by 9 static boolean isDivBy9(int n) { // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7)); } // Driver code public static void main(String arg[]) { // Let us print all multiples of 9 from // 0 to 100 using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) System.out.print(i + \" \"); }} // This code is contributed by Anant Agarwal.", "e": 2023, "s": 1235, "text": null }, { "code": "# Bitwise operator based# function to check divisibility by 9 def isDivBy9(n): # Base cases if (n == 0 or n == 9): return True if (n < 9): return False # If n is greater than 9, # then recur for [floor(n / 9) - n % 8] return isDivBy9((int)(n>>3) - (int)(n&7)) # Driver code # Let us print all multiples# of 9 from 0 to 100# using above methodfor i in range(100): if (isDivBy9(i)): print(i, \" \", end =\"\") # This code is contributed# by Anant Agarwal.", "e": 2518, "s": 2023, "text": null }, { "code": "// C# program to check if a number// is multiple of 9 using bitwise operatorsusing System; class GFG { // Bitwise operator based function // to check divisibility by 9 static bool isDivBy9(int n) { // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9((int)(n >> 3) - (int)(n & 7)); } // Driver code public static void Main() { // Let us print all multiples of 9 from // 0 to 100 using above method for (int i = 0; i < 100; i++) if (isDivBy9(i)) Console.Write(i + \" \"); }} // This code is contributed by nitin mittal.", "e": 3277, "s": 2518, "text": null }, { "code": "<?php// PHP program to check if a number// is multiple of 9 using bitwise// operators // Bitwise operator based function// to check divisibility by 9function isDivBy9($n){ // Base cases if ($n == 0 || $n == 9) return true; if ($n < 9) return false; // If n is greater than 9, // then recur for [floor(n/9) - // n%8] return isDivBy9(($n >> 3) - ($n & 7));} // Driver Code // Let us print all multiples // of 9 from 0 to 100 // using above method for ($i = 0; $i < 100; $i++) if (isDivBy9($i)) echo $i ,\" \"; // This code is contributed by nitin mittal?>", "e": 3935, "s": 3277, "text": null }, { "code": "<script>// javascript program to check if a number// is multiple of 9 using bitwise operators // Bitwise operator based function// to check divisibility by 9function isDivBy9(n){ // Base cases if (n == 0 || n == 9) return true; if (n < 9) return false; // If n is greater than 9, then // recur for [floor(n/9) - n%8] return isDivBy9(parseInt(n >> 3) - parseInt(n & 7));} // Driver code // Let us print all multiples of 9 from// 0 to 100 using above methodfor (i = 0; i < 100; i++) if (isDivBy9(i)) document.write(i + \" \"); // This code is contributed by Princi Singh</script>", "e": 4559, "s": 3935, "text": null }, { "code": null, "e": 4568, "s": 4559, "text": "Output: " }, { "code": null, "e": 4602, "s": 4568, "text": "0 9 18 27 36 45 54 63 72 81 90 99" }, { "code": null, "e": 4628, "s": 4602, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 4744, "s": 4628, "text": "Auxiliary Space: O(logn)How does this work? n/9 can be written in terms of n/8 using the following simple formula. " }, { "code": null, "e": 4761, "s": 4744, "text": "n/9 = n/8 - n/72" }, { "code": null, "e": 5046, "s": 4761, "text": "Since we need to use bitwise operators, we get the value of floor(n/8) using n>>3 and get value of n%8 using n&7. We need to write above expression in terms of floor(n/8) and n%8. n/8 is equal to “floor(n/8) + (n%8)/8”. Let us write the above expression in terms of floor(n/8) and n%8" }, { "code": null, "e": 5195, "s": 5046, "text": "n/9 = floor(n/8) + (n%8)/8 - [floor(n/8) + (n%8)/8]/9\nn/9 = floor(n/8) - [floor(n/8) - 9(n%8)/8 + (n%8)/8]/9\nn/9 = floor(n/8) - [floor(n/8) - n%8]/9" }, { "code": null, "e": 5707, "s": 5195, "text": "From above equation, n is a multiple of 9 only if the expression floor(n/8) – [floor(n/8) – n%8]/9 is an integer. This expression can only be an integer if the sub-expression [floor(n/8) – n%8]/9 is an integer. The subexpression can only be an integer if [floor(n/8) – n%8] is a multiple of 9. So the problem reduces to a smaller value which can be written in terms of bitwise operators.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5720, "s": 5707, "text": "nitin mittal" }, { "code": null, "e": 5733, "s": 5720, "text": "princi singh" }, { "code": null, "e": 5746, "s": 5733, "text": "ankita_saini" }, { "code": null, "e": 5761, "s": 5746, "text": "ranjanrohit840" }, { "code": null, "e": 5774, "s": 5761, "text": "divisibility" }, { "code": null, "e": 5784, "s": 5774, "text": "Bit Magic" }, { "code": null, "e": 5794, "s": 5784, "text": "Bit Magic" }, { "code": null, "e": 5892, "s": 5794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5922, "s": 5892, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 5975, "s": 5922, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 6015, "s": 5975, "text": "Binary representation of a given number" }, { "code": null, "e": 6058, "s": 6015, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 6134, "s": 6058, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 6150, "s": 6134, "text": "Bit Fields in C" }, { "code": null, "e": 6185, "s": 6150, "text": "Find the element that appears once" }, { "code": null, "e": 6216, "s": 6185, "text": "C++ bitset and its application" }, { "code": null, "e": 6267, "s": 6216, "text": "Add two numbers without using arithmetic operators" } ]