title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How can I draw inline line labels in Matplotlib?
To draw inline labels in Matplotlib, we can use labelLines() method. − Set the figure size and adjust the padding between and around the subplots. Create random data points x using numpy and a list of data points, A. Iterate the list of A, and plot X and a (iterated item) with label. Label all the lines with their respective legends, for lines drawn. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt from labellines import labelLines plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True X = np.linspace(0, 1, 500) A = [1, 2, 5, 10, 20] for a in A: plt.plot(X, np.arctan(a*X), label=str(a)) labelLines(plt.gca().get_lines(), zorder=2.5) plt.show()
[ { "code": null, "e": 1133, "s": 1062, "text": "To draw inline labels in Matplotlib, we can use labelLines() method. −" }, { "code": null, "e": 1209, "s": 1133, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1279, "s": 1209, "text": "Create random data points x using numpy and a list of data points, A." }, { "code": null, "e": 1347, "s": 1279, "text": "Iterate the list of A, and plot X and a (iterated item) with label." }, { "code": null, "e": 1415, "s": 1347, "text": "Label all the lines with their respective legends, for lines drawn." }, { "code": null, "e": 1457, "s": 1415, "text": "To display the figure, use show() method." }, { "code": null, "e": 1802, "s": 1457, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom labellines import labelLines\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nX = np.linspace(0, 1, 500)\nA = [1, 2, 5, 10, 20]\n\nfor a in A:\n plt.plot(X, np.arctan(a*X), label=str(a))\n\nlabelLines(plt.gca().get_lines(), zorder=2.5)\n\nplt.show()" } ]
PandasGUI: Analyzing Pandas dataframes with a Graphical User Interface | by Parul Pandey | Towards Data Science
Today the pandas library has become the defacto tool for doing any exploratory data analysis in Python. Its versatility, flexibility, and ease of use makes it the library of choice for many data scientists today. The pandas' library also enjoys excellent community support and thus is always under active development and improvement. Due to this indispensable nature of pandas, various tools have been created from time to time to enhance its effectiveness or improve upon it. There are two specific sets of tools that I have encountered when it comes to pandas: Tools that can perform basic EDA in two or three lines of code. These libraries essentially use pandas’ functions under the hood. Examples are SweetViz and Pandas profiling library. GUI-based alternatives to pandas, for example, Bamboolib. Recently, I came across another GUI based alternative to pandas called PandasGUI. One thing that struck was that it offered capabilities of plotting as well as reframing the dataframe. Also, the user has the freedom to perform custom operations too. This article will try and explain its various features and functionalities and how you could use it for your data. PandasGUI, as the name suggests, is a graphical user interface for analyzing Pandas’ dataframes. The project is still under active development and so can be subject to breaking changes, at times. PandasGUI comes with many useful features, which we shall cover in detail later in the article. Before that, let’s see how we can install the library and get it running. There are a couple of ways by which you can install PandasGUI: # from PyPipip install pandasguior# from Githubpip install git+https://github.com/adamerose/pandasgui.git Let’s now look at the various capabilities of the PandasGUI library with an example. PandasGUI comes with some example datasets already. So we’ll use the Titanic dataset, which comes packaged with the library. Titanic is a fairly known ‘Hello World’ dataset in machine learning, where the task is to create a model that predicts which passengers survived the Titanic shipwreck. import pandas as pdfrom pandasgui import showfrom pandasgui.datasets import titanicgui = show(titanic) In case you want to import your dataset, you can do so as follows: titanic = pd.read_csv('https://github.com/adamerose/datasets/blob/master/titanic.csv')gui = show(titanic) Once you run the above commands, a separate window opens up and displays the uploaded dataframe: Let’s now look at the various offerings of this tool one by one. You can view the entire imported dataframes and then quickly sort them in ascending or descending order. Note that PandasGUI can handle multiclass datarfames also. Once you have explored the dataset, you can even filter the dataset based on some query expressions. Dataframe.query() is a method originally provided by pandas for performing filtering operations. It takes an expression in string form to filter data, makes changes to the original dataframe, and returns the filtered dataframe. For our dataset, let’s say we want to filter the entire data for passengers who are: Male Belong to Pclass 3, and Survived the shipwreck. Another great feature of this tool is that you can directly edit any entry and even copy and paste the selected data to another environment like excel or notepad. PandasGUI also provides a condensed statistical overview of the entire dataset. Data Visualisation is an essential part of any data analysis process, and PandasGUI provides several options to quickly create some cool interactive charts like: Below we have created a pie-chart, a bar chart, and even a word cloud. Since the charts are created in plotly, they are responsive as well as interactive. Sometimes, there is a need to reshape the data to get more distinct insights. PandasGUI provides two functions — pivot and melts to achieve the same. Let’s see how to pivot the data via this tool. Another cool property of the tool is that one can simply import a dataframe by dragging it on to the GUI interface, which is handy at times. If you have directly imported a dataframe onto the PandasGUI interface, you can access the same in the familiar juptyer notebook also, with just a few lines of code. From there, you can carry the data analysis process in the notebook itself, if you wish. In this article, we looked at a GUI-based tool for analyzing pandas dataframes. This tool has a number of interesting features like filtering, sorting, visualizing, and even aggregating, which we saw in detail with an example dataset. Since PandasGUI is under active development, we might see some more features in the coming days. Such libraries can be a boon for people who are not very comfortable with coding or are looking for a low code environment. Whatever the ultimate goal is, it is always good to know about another open-source tool to add to our data science toolkit.
[ { "code": null, "e": 735, "s": 172, "text": "Today the pandas library has become the defacto tool for doing any exploratory data analysis in Python. Its versatility, flexibility, and ease of use makes it the library of choice for many data scientists today. The pandas' library also enjoys excellent community support and thus is always under active development and improvement. Due to this indispensable nature of pandas, various tools have been created from time to time to enhance its effectiveness or improve upon it. There are two specific sets of tools that I have encountered when it comes to pandas:" }, { "code": null, "e": 917, "s": 735, "text": "Tools that can perform basic EDA in two or three lines of code. These libraries essentially use pandas’ functions under the hood. Examples are SweetViz and Pandas profiling library." }, { "code": null, "e": 975, "s": 917, "text": "GUI-based alternatives to pandas, for example, Bamboolib." }, { "code": null, "e": 1340, "s": 975, "text": "Recently, I came across another GUI based alternative to pandas called PandasGUI. One thing that struck was that it offered capabilities of plotting as well as reframing the dataframe. Also, the user has the freedom to perform custom operations too. This article will try and explain its various features and functionalities and how you could use it for your data." }, { "code": null, "e": 1706, "s": 1340, "text": "PandasGUI, as the name suggests, is a graphical user interface for analyzing Pandas’ dataframes. The project is still under active development and so can be subject to breaking changes, at times. PandasGUI comes with many useful features, which we shall cover in detail later in the article. Before that, let’s see how we can install the library and get it running." }, { "code": null, "e": 1769, "s": 1706, "text": "There are a couple of ways by which you can install PandasGUI:" }, { "code": null, "e": 1875, "s": 1769, "text": "# from PyPipip install pandasguior# from Githubpip install git+https://github.com/adamerose/pandasgui.git" }, { "code": null, "e": 2253, "s": 1875, "text": "Let’s now look at the various capabilities of the PandasGUI library with an example. PandasGUI comes with some example datasets already. So we’ll use the Titanic dataset, which comes packaged with the library. Titanic is a fairly known ‘Hello World’ dataset in machine learning, where the task is to create a model that predicts which passengers survived the Titanic shipwreck." }, { "code": null, "e": 2356, "s": 2253, "text": "import pandas as pdfrom pandasgui import showfrom pandasgui.datasets import titanicgui = show(titanic)" }, { "code": null, "e": 2423, "s": 2356, "text": "In case you want to import your dataset, you can do so as follows:" }, { "code": null, "e": 2529, "s": 2423, "text": "titanic = pd.read_csv('https://github.com/adamerose/datasets/blob/master/titanic.csv')gui = show(titanic)" }, { "code": null, "e": 2626, "s": 2529, "text": "Once you run the above commands, a separate window opens up and displays the uploaded dataframe:" }, { "code": null, "e": 2691, "s": 2626, "text": "Let’s now look at the various offerings of this tool one by one." }, { "code": null, "e": 2855, "s": 2691, "text": "You can view the entire imported dataframes and then quickly sort them in ascending or descending order. Note that PandasGUI can handle multiclass datarfames also." }, { "code": null, "e": 3184, "s": 2855, "text": "Once you have explored the dataset, you can even filter the dataset based on some query expressions. Dataframe.query() is a method originally provided by pandas for performing filtering operations. It takes an expression in string form to filter data, makes changes to the original dataframe, and returns the filtered dataframe." }, { "code": null, "e": 3269, "s": 3184, "text": "For our dataset, let’s say we want to filter the entire data for passengers who are:" }, { "code": null, "e": 3274, "s": 3269, "text": "Male" }, { "code": null, "e": 3298, "s": 3274, "text": "Belong to Pclass 3, and" }, { "code": null, "e": 3322, "s": 3298, "text": "Survived the shipwreck." }, { "code": null, "e": 3485, "s": 3322, "text": "Another great feature of this tool is that you can directly edit any entry and even copy and paste the selected data to another environment like excel or notepad." }, { "code": null, "e": 3565, "s": 3485, "text": "PandasGUI also provides a condensed statistical overview of the entire dataset." }, { "code": null, "e": 3727, "s": 3565, "text": "Data Visualisation is an essential part of any data analysis process, and PandasGUI provides several options to quickly create some cool interactive charts like:" }, { "code": null, "e": 3882, "s": 3727, "text": "Below we have created a pie-chart, a bar chart, and even a word cloud. Since the charts are created in plotly, they are responsive as well as interactive." }, { "code": null, "e": 4079, "s": 3882, "text": "Sometimes, there is a need to reshape the data to get more distinct insights. PandasGUI provides two functions — pivot and melts to achieve the same. Let’s see how to pivot the data via this tool." }, { "code": null, "e": 4220, "s": 4079, "text": "Another cool property of the tool is that one can simply import a dataframe by dragging it on to the GUI interface, which is handy at times." }, { "code": null, "e": 4475, "s": 4220, "text": "If you have directly imported a dataframe onto the PandasGUI interface, you can access the same in the familiar juptyer notebook also, with just a few lines of code. From there, you can carry the data analysis process in the notebook itself, if you wish." } ]
Let’s make a map! Using Geopandas, Pandas and Matplotlib to make a Choropleth map | by Ben Dexter Cooley | Towards Data Science
So you want to make a map using Python. Let’s get started! If you’ve started doing some data visualisation with Matplotlib and Pandas, but are looking for the next simple step to getting started with geographical data, I got you. I’ve been there. In fact, I spent hours trawling through online tutorials looking for the easiest package to get started with making maps (specifically choropleths). And while there are lots of options to choose from, I eventually landed on Geopandas as the lowest barrier of entry. Geopandas is great, cause it’s just like Pandas (but using geodata from things like shape files). Geopandas dataframes are a lot like Pandas dataframes, so the two usually play nicely. Best of all, Geopandas allows you to create quick, standalone choropleth maps without many other dependencies (and not too many lines of code!). Here’s a preview of what we’ll be making. As an aside, there are lots and lots of great ways to make maps out there (notably, Datawrapper just added a GeoJson wrapper to load your own custom maps). There’s no one size fits all. However, most of these services come with some kind of restriction (like not being able to download a file as svg. Also, making maps in Python give you a couple unique benefits: Reproducibility — always a strong selling point with Python, but especially for making super quick charts. This tutorial will streamline the process of creating a map as much as possible (using global variables, cleaning, etc) so that next time you want to make a map, you just need to change the csv file (assuming it’s the same geographic location). Maximum control — customise, download in whatever format you want, you make the call. Even though it can take some fiddling with the code, Matplotlib is massively powerful. Lots and lots of maps — if you need to visualise the same map with lots of variables (small multiple maps?) or maps showing change over time, wrapping this code in a for loop is a smart way to go (which I’ll cover in my next post). Chart builders with a GUI interface are great, but usually not so good at automating tasks. Python is Very Good. No design skills needed — well, almost no design skills. An eye for good data design is helpful. But no Adobe Illustrator or Photoshop skills needed. Ok, let’s do this. Here’s what you’ll need. I use a Jupyter Notebook to house all the code (which I highly recommend so you can preview rendering), but you do you. Pandas Geopandas Matplotlib That’s it! Let’s get some data into our Notebook. As I’m based in London currently, I’ll be making a map of London by local ward (borough level). The London Datastore does a great job making lots of data public and accessible, and I found this page with a bunch of shape files with different levels of detail. Nice! Click → download → Save as → Move to local directory of notebook. Nailed it. But the shapefile is only one layer of data. This will help to draw the map, but if we want to bind data to it we will need another dataset as well. Back to London Datastore: let’s download the London borough profiles dataset as a csv (which is already pre-cleaned and tidy). This csv file has lots of columns that we can use as variables to visualise. Now that both datasets are ready to go, I’m back in my Jupyter Notebook. Time to load in the .shp and .csv file. # set the filepath and load in a shapefilefp = “datasets/geo-data/gis-boundaries-london/ESRI/London_Borough_Excluding_MHW.shp”map_df = gpd.read_file(fp)# check data type so we can see that this is not a normal dataframe, but a GEOdataframemap_df.head() Now let’s preview what our map looks like with no data in it. map_df.plot() Cool, it’s London! And then let’s load in a csv file of data to join with the geodataframe. df = pd.read_csv(“datasets/london-borough-profile.csv”, header=0)df.head() Great. So now we have two dataframes ready to go. Let’s get a slice of the data that we are going to use. df = df[[‘borough’,’Happiness_score_2011–14_(out_of_10)’, ‘Anxiety_score_2011–14_(out_of_10)’, ‘Population_density_(per_hectare)_2017’, ‘Mortality_rate_from_causes_considered_preventable_2012/14’]] Those are really terrible column names. Let’s rename them to something simpler. data_for_map = df.rename(index=str, columns={“Happiness_score_2011–14_(out_of_10)”: “happiness”,“Anxiety_score_2011–14_(out_of_10)”: “anxiety”,“Population_density_(per_hectare)_2017”: “pop_density_per_hectare”,“Mortality_rate_from_causes_considered_preventable_2012/14”: ‘mortality’})# check dat dataframedata_for_map.head() Much better. Now we need to merge our geodata with our cleaned London dataset. We’ll do that using pd.join(). # join the geodataframe with the cleaned up csv dataframemerged = map_df.set_index(‘NAME’).join(data_for_map.set_index(‘borough’))merged.head() Let’s start mapping. First we need to do some prep work for Matplotlib. We’ll start by setting a variable to map, setting the range and creating the figure for the map to be drawn in. # set a variable that will call whatever column we want to visualise on the mapvariable = ‘pop_density_per_hectare’# set the range for the choroplethvmin, vmax = 120, 220# create figure and axes for Matplotlibfig, ax = plt.subplots(1, figsize=(10, 6)) The stage has been set. Map time. # create mapmerged.plot(column=variable, cmap=’Blues’, linewidth=0.8, ax=ax, edgecolor=’0.8') And there it is! Not perfect. A little bit warped, and there’s a weird axis around the whole thing that doesn’t really mean anything. But we have a choropleth. Now let’s do some prettifying to get it looking fresh. First off, that axis needs to go. # remove the axisax.axis(‘off’) Then let’s add a title to our map, and some text noting the source. Maps are usually nice to look at, but if you don’t provide context then it doesn’t mean much. # add a titleax.set_title(‘Preventable death rate in London’, fontdict={‘fontsize’: ‘25’, ‘fontweight’ : ‘3’})# create an annotation for the data sourceax.annotate(‘Source: London Datastore, 2014’,xy=(0.1, .08), xycoords=’figure fraction’, horizontalalignment=’left’, verticalalignment=’top’, fontsize=12, color=’#555555') Beautiful! Still one thing missing though. We should probably add a legend that shows the range of value for the user. This will help it to not look so squished as well. # Create colorbar as a legendsm = plt.cm.ScalarMappable(cmap=’Blues’, norm=plt.Normalize(vmin=vmin, vmax=vmax))# empty array for the data rangesm._A = []# add the colorbar to the figurecbar = fig.colorbar(sm) Map. Made. Last thing: we need to save the map so we can post a tweet with that sweet #dataviz hashtag. Matplotlib gives you lots of freedom in how you save figures. The code below will save the figure as a png, but if you want to fiddle about some more with it in Illustrator you can also save as svg. If you save as png, make sure to use a dpi of 200 or above. Otherwise the map and text will look all blurry. Nobody wants that. fig.savefig(“map_export.png”, dpi=300) And now, we have a publish-ready map waiting in our working directory! Amazing. So that’s it. You’re all setup with Geopandas (at least for choropleths). Next I’ll look at how to make multiple maps using Geopandas and turn it into a cool gif map. Stay tuned! You can view and download my Jupyter Notebook for this tutorial here on Github.
[ { "code": null, "e": 231, "s": 172, "text": "So you want to make a map using Python. Let’s get started!" }, { "code": null, "e": 685, "s": 231, "text": "If you’ve started doing some data visualisation with Matplotlib and Pandas, but are looking for the next simple step to getting started with geographical data, I got you. I’ve been there. In fact, I spent hours trawling through online tutorials looking for the easiest package to get started with making maps (specifically choropleths). And while there are lots of options to choose from, I eventually landed on Geopandas as the lowest barrier of entry." }, { "code": null, "e": 1015, "s": 685, "text": "Geopandas is great, cause it’s just like Pandas (but using geodata from things like shape files). Geopandas dataframes are a lot like Pandas dataframes, so the two usually play nicely. Best of all, Geopandas allows you to create quick, standalone choropleth maps without many other dependencies (and not too many lines of code!)." }, { "code": null, "e": 1057, "s": 1015, "text": "Here’s a preview of what we’ll be making." }, { "code": null, "e": 1421, "s": 1057, "text": "As an aside, there are lots and lots of great ways to make maps out there (notably, Datawrapper just added a GeoJson wrapper to load your own custom maps). There’s no one size fits all. However, most of these services come with some kind of restriction (like not being able to download a file as svg. Also, making maps in Python give you a couple unique benefits:" }, { "code": null, "e": 1773, "s": 1421, "text": "Reproducibility — always a strong selling point with Python, but especially for making super quick charts. This tutorial will streamline the process of creating a map as much as possible (using global variables, cleaning, etc) so that next time you want to make a map, you just need to change the csv file (assuming it’s the same geographic location)." }, { "code": null, "e": 1946, "s": 1773, "text": "Maximum control — customise, download in whatever format you want, you make the call. Even though it can take some fiddling with the code, Matplotlib is massively powerful." }, { "code": null, "e": 2291, "s": 1946, "text": "Lots and lots of maps — if you need to visualise the same map with lots of variables (small multiple maps?) or maps showing change over time, wrapping this code in a for loop is a smart way to go (which I’ll cover in my next post). Chart builders with a GUI interface are great, but usually not so good at automating tasks. Python is Very Good." }, { "code": null, "e": 2441, "s": 2291, "text": "No design skills needed — well, almost no design skills. An eye for good data design is helpful. But no Adobe Illustrator or Photoshop skills needed." }, { "code": null, "e": 2605, "s": 2441, "text": "Ok, let’s do this. Here’s what you’ll need. I use a Jupyter Notebook to house all the code (which I highly recommend so you can preview rendering), but you do you." }, { "code": null, "e": 2612, "s": 2605, "text": "Pandas" }, { "code": null, "e": 2622, "s": 2612, "text": "Geopandas" }, { "code": null, "e": 2633, "s": 2622, "text": "Matplotlib" }, { "code": null, "e": 2644, "s": 2633, "text": "That’s it!" }, { "code": null, "e": 2949, "s": 2644, "text": "Let’s get some data into our Notebook. As I’m based in London currently, I’ll be making a map of London by local ward (borough level). The London Datastore does a great job making lots of data public and accessible, and I found this page with a bunch of shape files with different levels of detail. Nice!" }, { "code": null, "e": 3026, "s": 2949, "text": "Click → download → Save as → Move to local directory of notebook. Nailed it." }, { "code": null, "e": 3379, "s": 3026, "text": "But the shapefile is only one layer of data. This will help to draw the map, but if we want to bind data to it we will need another dataset as well. Back to London Datastore: let’s download the London borough profiles dataset as a csv (which is already pre-cleaned and tidy). This csv file has lots of columns that we can use as variables to visualise." }, { "code": null, "e": 3492, "s": 3379, "text": "Now that both datasets are ready to go, I’m back in my Jupyter Notebook. Time to load in the .shp and .csv file." }, { "code": null, "e": 3745, "s": 3492, "text": "# set the filepath and load in a shapefilefp = “datasets/geo-data/gis-boundaries-london/ESRI/London_Borough_Excluding_MHW.shp”map_df = gpd.read_file(fp)# check data type so we can see that this is not a normal dataframe, but a GEOdataframemap_df.head()" }, { "code": null, "e": 3807, "s": 3745, "text": "Now let’s preview what our map looks like with no data in it." }, { "code": null, "e": 3821, "s": 3807, "text": "map_df.plot()" }, { "code": null, "e": 3840, "s": 3821, "text": "Cool, it’s London!" }, { "code": null, "e": 3913, "s": 3840, "text": "And then let’s load in a csv file of data to join with the geodataframe." }, { "code": null, "e": 3988, "s": 3913, "text": "df = pd.read_csv(“datasets/london-borough-profile.csv”, header=0)df.head()" }, { "code": null, "e": 4094, "s": 3988, "text": "Great. So now we have two dataframes ready to go. Let’s get a slice of the data that we are going to use." }, { "code": null, "e": 4292, "s": 4094, "text": "df = df[[‘borough’,’Happiness_score_2011–14_(out_of_10)’, ‘Anxiety_score_2011–14_(out_of_10)’, ‘Population_density_(per_hectare)_2017’, ‘Mortality_rate_from_causes_considered_preventable_2012/14’]]" }, { "code": null, "e": 4372, "s": 4292, "text": "Those are really terrible column names. Let’s rename them to something simpler." }, { "code": null, "e": 4697, "s": 4372, "text": "data_for_map = df.rename(index=str, columns={“Happiness_score_2011–14_(out_of_10)”: “happiness”,“Anxiety_score_2011–14_(out_of_10)”: “anxiety”,“Population_density_(per_hectare)_2017”: “pop_density_per_hectare”,“Mortality_rate_from_causes_considered_preventable_2012/14”: ‘mortality’})# check dat dataframedata_for_map.head()" }, { "code": null, "e": 4807, "s": 4697, "text": "Much better. Now we need to merge our geodata with our cleaned London dataset. We’ll do that using pd.join()." }, { "code": null, "e": 4951, "s": 4807, "text": "# join the geodataframe with the cleaned up csv dataframemerged = map_df.set_index(‘NAME’).join(data_for_map.set_index(‘borough’))merged.head()" }, { "code": null, "e": 5135, "s": 4951, "text": "Let’s start mapping. First we need to do some prep work for Matplotlib. We’ll start by setting a variable to map, setting the range and creating the figure for the map to be drawn in." }, { "code": null, "e": 5387, "s": 5135, "text": "# set a variable that will call whatever column we want to visualise on the mapvariable = ‘pop_density_per_hectare’# set the range for the choroplethvmin, vmax = 120, 220# create figure and axes for Matplotlibfig, ax = plt.subplots(1, figsize=(10, 6))" }, { "code": null, "e": 5421, "s": 5387, "text": "The stage has been set. Map time." }, { "code": null, "e": 5515, "s": 5421, "text": "# create mapmerged.plot(column=variable, cmap=’Blues’, linewidth=0.8, ax=ax, edgecolor=’0.8')" }, { "code": null, "e": 5730, "s": 5515, "text": "And there it is! Not perfect. A little bit warped, and there’s a weird axis around the whole thing that doesn’t really mean anything. But we have a choropleth. Now let’s do some prettifying to get it looking fresh." }, { "code": null, "e": 5764, "s": 5730, "text": "First off, that axis needs to go." }, { "code": null, "e": 5796, "s": 5764, "text": "# remove the axisax.axis(‘off’)" }, { "code": null, "e": 5958, "s": 5796, "text": "Then let’s add a title to our map, and some text noting the source. Maps are usually nice to look at, but if you don’t provide context then it doesn’t mean much." }, { "code": null, "e": 6282, "s": 5958, "text": "# add a titleax.set_title(‘Preventable death rate in London’, fontdict={‘fontsize’: ‘25’, ‘fontweight’ : ‘3’})# create an annotation for the data sourceax.annotate(‘Source: London Datastore, 2014’,xy=(0.1, .08), xycoords=’figure fraction’, horizontalalignment=’left’, verticalalignment=’top’, fontsize=12, color=’#555555')" }, { "code": null, "e": 6452, "s": 6282, "text": "Beautiful! Still one thing missing though. We should probably add a legend that shows the range of value for the user. This will help it to not look so squished as well." }, { "code": null, "e": 6661, "s": 6452, "text": "# Create colorbar as a legendsm = plt.cm.ScalarMappable(cmap=’Blues’, norm=plt.Normalize(vmin=vmin, vmax=vmax))# empty array for the data rangesm._A = []# add the colorbar to the figurecbar = fig.colorbar(sm)" }, { "code": null, "e": 6672, "s": 6661, "text": "Map. Made." }, { "code": null, "e": 6765, "s": 6672, "text": "Last thing: we need to save the map so we can post a tweet with that sweet #dataviz hashtag." }, { "code": null, "e": 7092, "s": 6765, "text": "Matplotlib gives you lots of freedom in how you save figures. The code below will save the figure as a png, but if you want to fiddle about some more with it in Illustrator you can also save as svg. If you save as png, make sure to use a dpi of 200 or above. Otherwise the map and text will look all blurry. Nobody wants that." }, { "code": null, "e": 7131, "s": 7092, "text": "fig.savefig(“map_export.png”, dpi=300)" }, { "code": null, "e": 7211, "s": 7131, "text": "And now, we have a publish-ready map waiting in our working directory! Amazing." }, { "code": null, "e": 7390, "s": 7211, "text": "So that’s it. You’re all setup with Geopandas (at least for choropleths). Next I’ll look at how to make multiple maps using Geopandas and turn it into a cool gif map. Stay tuned!" } ]
How to implement the IntPredicate interface using lambda and method reference in Java?
IntPredicate interface is a built-in functional interface defined in java.util.function package. This functional interface accepts one int-valued argument as input and produces a boolean value as an output. This interface is a specialization of the Predicate interface and used as an assignment target for a lambda expression or method reference. It provides only one abstract method, test (). @FunctionalInterface public interface IntPredicate { boolean test(int value); } import java.util.function.IntPredicate; public class IntPredicateLambdaTest { public static void main(String[] args) { IntPredicate intPredicate = (int input) -> { // lambda expression if(input == 100) { return true; } else return false; }; boolean result = intPredicate.test(100); System.out.println(result); } } true import java.util.function.IntPredicate; public class IntPredicateMethodReferenceTest { public static void main(String[] args) { IntPredicate intPredicate = IntPredicateMethodReferenceTest::test; // method reference boolean result = intPredicate.test(100); System.out.println(result); } static boolean test(int input) { if(input == 50) { return true; } else return false; } } false
[ { "code": null, "e": 1456, "s": 1062, "text": "IntPredicate interface is a built-in functional interface defined in java.util.function package. This functional interface accepts one int-valued argument as input and produces a boolean value as an output. This interface is a specialization of the Predicate interface and used as an assignment target for a lambda expression or method reference. It provides only one abstract method, test ()." }, { "code": null, "e": 1537, "s": 1456, "text": "@FunctionalInterface\npublic interface IntPredicate {\n boolean test(int value);\n}" }, { "code": null, "e": 1926, "s": 1537, "text": "import java.util.function.IntPredicate;\n\npublic class IntPredicateLambdaTest {\n public static void main(String[] args) {\n IntPredicate intPredicate = (int input) -> { // lambda expression\n if(input == 100) {\n return true;\n } else\n return false;\n };\n boolean result = intPredicate.test(100);\n System.out.println(result);\n }\n}" }, { "code": null, "e": 1931, "s": 1926, "text": "true" }, { "code": null, "e": 2369, "s": 1931, "text": "import java.util.function.IntPredicate;\n\npublic class IntPredicateMethodReferenceTest {\n public static void main(String[] args) {\n IntPredicate intPredicate = IntPredicateMethodReferenceTest::test; // method reference\n boolean result = intPredicate.test(100);\n System.out.println(result);\n }\n static boolean test(int input) {\n if(input == 50) {\n return true;\n } else\n return false;\n }\n}" }, { "code": null, "e": 2375, "s": 2369, "text": "false" } ]
How to create a PUT request in Postman?
A Postman PUT request is used to pass data to the server for the creation or modification of a resource. The difference between POST and PUT is that POST request is not idempotent. This means invoking the same PUT request numerous times will always yield the same output. But invoking the same POST request numerous times will create a similar resource more than one time. Before creating a PUT request, we shall first send a GET request to the server on an endpoint:http://dummy.restapiexample.com/api/v1/employees. On applying the GET method, the Response body obtained is − Now, let us update the employee_salary and employee_age for id 21 with the help of the PUT request. Step 1 − Click on the New menu from the Postman application. The Create New pop-up comes up. Then click on the Request link. Step 2 − SAVE REQUEST pop-up comes up. Enter Request name then click on Save. Step 3 − The Request name (Test1) gets reflected on the Request tab. We shall select the option PUT from the HTTP request dropdown. Then enter the URL -http://dummy.restapiexample.com/api/v1/update/21 (endpoint for updating the record of id 21) in the address bar. It must be noted that in a PUT request, we have to mention the id of the resource in the server which we want to update in the URL. For example, in the above URL, we have added the id 21. Step 4 − Move to the Body tab below the address bar and select the option raw. Step 5 − Then choose JSON from the Text dropdown. Step 6 − Copy and paste the below information in the Postman Body tab. { "name": "Jenette Caldwell","salary": "2000","age": "15"} The overall parameters to be set for a PUT request is shown below − Step 7 − Click on the Send button. Once a request has been sent, we can see the response code 200 OK populated in the Response body. This signifies a successful request and the request we have sent has been accepted by the server. Also, information on the time consumed to complete the request (673 ms) and payload size (705 B) are populated. The Response body shows the salary and age got updated to 2000 and 15 respectively for the employee having id 21.
[ { "code": null, "e": 1243, "s": 1062, "text": "A Postman PUT request is used to pass data to the server for the creation or modification of a resource. The difference between POST and PUT is that POST request is not idempotent." }, { "code": null, "e": 1435, "s": 1243, "text": "This means invoking the same PUT request numerous times will always yield the same output. But invoking the same POST request numerous times will create a similar resource more than one time." }, { "code": null, "e": 1579, "s": 1435, "text": "Before creating a PUT request, we shall first send a GET request to the server on an endpoint:http://dummy.restapiexample.com/api/v1/employees." }, { "code": null, "e": 1639, "s": 1579, "text": "On applying the GET method, the Response body obtained is −" }, { "code": null, "e": 1739, "s": 1639, "text": "Now, let us update the employee_salary and employee_age for id 21 with the help of the PUT request." }, { "code": null, "e": 1864, "s": 1739, "text": "Step 1 − Click on the New menu from the Postman application. The Create New pop-up comes up. Then click on the Request link." }, { "code": null, "e": 1942, "s": 1864, "text": "Step 2 − SAVE REQUEST pop-up comes up. Enter Request name then click on Save." }, { "code": null, "e": 2207, "s": 1942, "text": "Step 3 − The Request name (Test1) gets reflected on the Request tab. We shall select the option PUT from the HTTP request dropdown. Then enter the URL -http://dummy.restapiexample.com/api/v1/update/21 (endpoint for updating the record of id 21) in the address bar." }, { "code": null, "e": 2395, "s": 2207, "text": "It must be noted that in a PUT request, we have to mention the id of the resource in the server which we want to update in the URL. For example, in the above URL, we have added the id 21." }, { "code": null, "e": 2474, "s": 2395, "text": "Step 4 − Move to the Body tab below the address bar and select the option raw." }, { "code": null, "e": 2524, "s": 2474, "text": "Step 5 − Then choose JSON from the Text dropdown." }, { "code": null, "e": 2595, "s": 2524, "text": "Step 6 − Copy and paste the below information in the Postman Body tab." }, { "code": null, "e": 2654, "s": 2595, "text": "{ \"name\": \"Jenette Caldwell\",\"salary\": \"2000\",\"age\": \"15\"}" }, { "code": null, "e": 2722, "s": 2654, "text": "The overall parameters to be set for a PUT request is shown below −" }, { "code": null, "e": 2757, "s": 2722, "text": "Step 7 − Click on the Send button." }, { "code": null, "e": 2953, "s": 2757, "text": "Once a request has been sent, we can see the response code 200 OK populated in the Response body. This signifies a successful request and the request we have sent has been accepted by the server." }, { "code": null, "e": 3179, "s": 2953, "text": "Also, information on the time consumed to complete the request (673 ms) and payload size (705 B) are populated. The Response body shows the salary and age got updated to 2000 and 15 respectively for the employee having id 21." } ]
Redis - Pipelining
Redis is a TCP server and supports request/response protocol. In Redis, a request is accomplished with the following steps − The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response. The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response. The server processes the command and sends the response back to the client. The server processes the command and sends the response back to the client. The basic meaning of pipelining is, the client can send multiple requests to the server without waiting for the replies at all, and finally reads the replies in a single step. To check the Redis pipelining, just start the Redis instance and type the following command in the terminal. $(echo -en "PING\r\n SET tutorial redis\r\nGET tutorial\r\nINCR visitor\r\nINCR visitor\r\nINCR visitor\r\n"; sleep 10) | nc localhost 6379 +PONG +OK redis :1 :2 :3 In the above example, we will check Redis connection by using PING command. We have set a string named tutorial with value redis. Later, we get that keys value and increment the visitor number three times. In the result, we can see that all commands are submitted to Redis once, and Redis provides the output of all commands in a single step. The benefit of this technique is a drastically improved protocol performance. The speedup gained by pipelining ranges from a factor of five for connections to localhost up to a factor of at least one hundred over slower internet connections. 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2045, "text": "Redis is a TCP server and supports request/response protocol. In Redis, a request is accomplished with the following steps −" }, { "code": null, "e": 2289, "s": 2170, "text": "The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response." }, { "code": null, "e": 2408, "s": 2289, "text": "The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response." }, { "code": null, "e": 2484, "s": 2408, "text": "The server processes the command and sends the response back to the client." }, { "code": null, "e": 2560, "s": 2484, "text": "The server processes the command and sends the response back to the client." }, { "code": null, "e": 2736, "s": 2560, "text": "The basic meaning of pipelining is, the client can send multiple requests to the server without waiting for the replies at all, and finally reads the replies in a single step." }, { "code": null, "e": 2845, "s": 2736, "text": "To check the Redis pipelining, just start the Redis instance and type the following command in the terminal." }, { "code": null, "e": 3020, "s": 2845, "text": "$(echo -en \"PING\\r\\n SET tutorial redis\\r\\nGET tutorial\\r\\nINCR \nvisitor\\r\\nINCR visitor\\r\\nINCR visitor\\r\\n\"; sleep 10) | nc localhost 6379 \n+PONG \n+OK \nredis \n:1 \n:2 \n:3 \n" }, { "code": null, "e": 3363, "s": 3020, "text": "In the above example, we will check Redis connection by using PING command. We have set a string named tutorial with value redis. Later, we get that keys value and increment the visitor number three times. In the result, we can see that all commands are submitted to Redis once, and Redis provides the output of all commands in a single step." }, { "code": null, "e": 3605, "s": 3363, "text": "The benefit of this technique is a drastically improved protocol performance. The speedup gained by pipelining ranges from a factor of five for connections to localhost up to a factor of at least one hundred over slower internet connections." }, { "code": null, "e": 3637, "s": 3605, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 3657, "s": 3637, "text": " Skillbakerystudios" }, { "code": null, "e": 3664, "s": 3657, "text": " Print" }, { "code": null, "e": 3675, "s": 3664, "text": " Add Notes" } ]
What is the difference between jQuery and JavaScript?
The following is the difference between jQuery and JavaScript: jQuery is a fast and concise JavaScript library created by John Resig in 2006. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for Rapid Web Development. JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. jQuery is automatically optimized to work with a lot of browsers. But, JavaScript is still dealing with some issues such as cross-browser compatibility. This can be due to poor JavaScript implementation practices by web browser developers. jQuery needs less testing of code, and lesser code for the same goal, when compared with JavaScript. For example, to change font-size, background color, etc. Let us see an example of jQuery and JavaScript to change the background color: JavaScript function changeColor(color) { document.body.style.background = color; } Onload=”changeColor('blue’);” jQuery $ (‘body’) .css (‘background’, ‘#0000FF’); As shown above, both the code snippets are doing the same work of changing the background color. But jQuery takes less code and in this way you can work around other examples also, which shows that jQuery minimizes the code and is easier to use.
[ { "code": null, "e": 1125, "s": 1062, "text": "The following is the difference between jQuery and JavaScript:" }, { "code": null, "e": 1324, "s": 1125, "text": "jQuery is a fast and concise JavaScript library created by John Resig in 2006. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for Rapid Web Development." }, { "code": null, "e": 1598, "s": 1324, "text": "JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform." }, { "code": null, "e": 1838, "s": 1598, "text": "jQuery is automatically optimized to work with a lot of browsers. But, JavaScript is still dealing with some issues such as cross-browser compatibility. This can be due to poor JavaScript implementation practices by web browser developers." }, { "code": null, "e": 1996, "s": 1838, "text": "jQuery needs less testing of code, and lesser code for the same goal, when compared with JavaScript. For example, to change font-size, background color, etc." }, { "code": null, "e": 2075, "s": 1996, "text": "Let us see an example of jQuery and JavaScript to change the background color:" }, { "code": null, "e": 2086, "s": 2075, "text": "JavaScript" }, { "code": null, "e": 2191, "s": 2086, "text": "function changeColor(color) {\n document.body.style.background = color;\n}\nOnload=”changeColor('blue’);”" }, { "code": null, "e": 2198, "s": 2191, "text": "jQuery" }, { "code": null, "e": 2241, "s": 2198, "text": "$ (‘body’) .css (‘background’, ‘#0000FF’);" }, { "code": null, "e": 2487, "s": 2241, "text": "As shown above, both the code snippets are doing the same work of changing the background color. But jQuery takes less code and in this way you can work around other examples also, which shows that jQuery minimizes the code and is easier to use." } ]
Minimum number of operations to convert array A to array B by adding an integer into a subarray - GeeksforGeeks
01 Nov, 2021 Given two arrays A[] and B[] of length N, the task is to find the minimum number of operations in which the array A can be converted into array B where each operation consists of adding an integer K into a subarray from L to R. Examples: Input: A[] = {3, 7, 1, 4, 1, 2}, B[] = {3, 7, 3, 6, 3, 2} Output: 1 Explanation: In the above given example only one operation is required to convert from A to B: L = 3, R = 5 and K = 2 Array after the following operation: Index 0: A[0] = 3, B[0] = 3 Index 1: A[1] = 7, B[1] = 7 Index 2: A[2] = 1 + 2 = 3, B[2] = 3 Index 3: A[3] = 4 + 2 = 6, B[3] = 6 Index 4: A[4] = 1 + 2 = 3, B[4] = 3 Index 5: A[5] = 2, B[5] = 2 Input: A[] = {1, 1, 1, 1, 1}, B[] = {1, 2, 1, 3, 1} Output: 2 Explanation: In the above given example only one operation is required to convert from A to B – Operation 1: Add 1 to L = 2 to R = 2 Operation 2: Add 2 to L = 4 to R = 4 Approach: The idea is to count the consecutive elements, in array A, having an equal difference with the corresponding element in array B. Find the difference of the corresponding element from the array A and B: Difference = A[i] - B[i] If the difference of the corresponding elements is equal to 0, then continue checking for the next index. Otherwise, Increase the index until the difference between consecutive elements is not equal to the previous difference of the consecutive elements Increment the count by 1, until all the indexes are iterated having the same difference. In the end, return the count as the minimum number of operations. Below is the implementation of the above approach: C++ Java C# Python3 Javascript // C++ implementation to find the// minimum number of operations in// which the array A can be converted// to another array B #include <bits/stdc++.h>using namespace std; // Function to find the minimum// number of operations in which// array A can be converted to array Bvoid checkArray(int a[], int b[], int n){ int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required cout << operations << "\n";} // Driver Codeint main(){ int a[] = { 3, 7, 1, 4, 1, 2 }; int b[] = { 3, 7, 3, 6, 3, 2 }; int size = sizeof(a) / sizeof(a[0]); checkArray(a, b, size); return 0;} // Java implementation to find the// minimum number of operations in// which the array A can be converted// to another array Bclass GFG { // Function to find the minimum // number of operations in which // array A can be converted to array B static void checkArray(int a[], int b[], int n) { int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required System.out.println(operations); } // Driver Code public static void main (String[] args) { int a[] = { 3, 7, 1, 4, 1, 2 }; int b[] = { 3, 7, 3, 6, 3, 2 }; int size = a.length; checkArray(a, b, size); }} // This code is contributed by AnkitRai01 // C# implementation to find the// minimum number of operations in// which the array A can be converted// to another array Busing System; class GFG { // Function to find the minimum // number of operations in which // array A can be converted to array B static void checkArray(int []a, int []b, int n) { int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required Console.WriteLine(operations); } // Driver Code public static void Main (string[] args) { int []a = { 3, 7, 1, 4, 1, 2 }; int []b = { 3, 7, 3, 6, 3, 2 }; int size = a.Length; checkArray(a, b, size); }} // This code is contributed by AnkitRai01 # Python3 implementation to find the# minimum number of operations in# which the array A can be converted# to another array B # Function to find the minimum# number of operations in which# array A can be converted to array Bdef checkArray(a, b, n) : operations = 0; i = 0; # Loop to iterate over the array while (i < n) : # if both elements are equal # then move to next element if (a[i] - b[i] == 0) : i += 1; continue; # Calculate the difference # between two elements diff = a[i] - b[i]; i += 1; # loop while the next pair of # elements have same difference while (i < n and a[i] - b[i] == diff) : i += 1; # Increase the number of # operations by 1 operations += 1; # Print the number of # operations required print(operations); # Driver Codeif __name__ == "__main__" : a = [ 3, 7, 1, 4, 1, 2 ]; b = [ 3, 7, 3, 6, 3, 2 ]; size = len(a); checkArray(a, b, size); # This code is contributed by AnkitRai01 <script>// javascript implementation to find the// minimum number of operations in// which the array A can be converted// to another array B // Function to find the minimum // number of operations in which // array A can be converted to array B function checkArray(a , b , n) { var operations = 0; var i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements var diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required document.write(operations); } // Driver Code var a = [ 3, 7, 1, 4, 1, 2 ]; var b = [ 3, 7, 3, 6, 3, 2 ]; var size = a.length; checkArray(a, b, size); // This code contributed by Rajput-Ji</script> Performance Analysis: Time Complexity: As in the above approach, there is only one loop that takes O(N) time in the worst case. Hence, the Time Complexity will be O(N). Auxiliary Space Complexity: As in the above approach, there is no extra space used. Hence, the auxiliary space complexity will be O(1). ankthon Rajput-Ji ankita_saini subarray Arrays Mathematical Arrays Mathematical 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 Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25308, "s": 25280, "text": "\n01 Nov, 2021" }, { "code": null, "e": 25536, "s": 25308, "text": "Given two arrays A[] and B[] of length N, the task is to find the minimum number of operations in which the array A can be converted into array B where each operation consists of adding an integer K into a subarray from L to R." }, { "code": null, "e": 25547, "s": 25536, "text": "Examples: " }, { "code": null, "e": 25962, "s": 25547, "text": "Input: A[] = {3, 7, 1, 4, 1, 2}, B[] = {3, 7, 3, 6, 3, 2} Output: 1 Explanation: In the above given example only one operation is required to convert from A to B: L = 3, R = 5 and K = 2 Array after the following operation: Index 0: A[0] = 3, B[0] = 3 Index 1: A[1] = 7, B[1] = 7 Index 2: A[2] = 1 + 2 = 3, B[2] = 3 Index 3: A[3] = 4 + 2 = 6, B[3] = 6 Index 4: A[4] = 1 + 2 = 3, B[4] = 3 Index 5: A[5] = 2, B[5] = 2" }, { "code": null, "e": 26196, "s": 25962, "text": "Input: A[] = {1, 1, 1, 1, 1}, B[] = {1, 2, 1, 3, 1} Output: 2 Explanation: In the above given example only one operation is required to convert from A to B – Operation 1: Add 1 to L = 2 to R = 2 Operation 2: Add 2 to L = 4 to R = 4 " }, { "code": null, "e": 26335, "s": 26196, "text": "Approach: The idea is to count the consecutive elements, in array A, having an equal difference with the corresponding element in array B." }, { "code": null, "e": 26408, "s": 26335, "text": "Find the difference of the corresponding element from the array A and B:" }, { "code": null, "e": 26433, "s": 26408, "text": "Difference = A[i] - B[i]" }, { "code": null, "e": 26539, "s": 26433, "text": "If the difference of the corresponding elements is equal to 0, then continue checking for the next index." }, { "code": null, "e": 26687, "s": 26539, "text": "Otherwise, Increase the index until the difference between consecutive elements is not equal to the previous difference of the consecutive elements" }, { "code": null, "e": 26776, "s": 26687, "text": "Increment the count by 1, until all the indexes are iterated having the same difference." }, { "code": null, "e": 26842, "s": 26776, "text": "In the end, return the count as the minimum number of operations." }, { "code": null, "e": 26894, "s": 26842, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26898, "s": 26894, "text": "C++" }, { "code": null, "e": 26903, "s": 26898, "text": "Java" }, { "code": null, "e": 26906, "s": 26903, "text": "C#" }, { "code": null, "e": 26914, "s": 26906, "text": "Python3" }, { "code": null, "e": 26925, "s": 26914, "text": "Javascript" }, { "code": "// C++ implementation to find the// minimum number of operations in// which the array A can be converted// to another array B #include <bits/stdc++.h>using namespace std; // Function to find the minimum// number of operations in which// array A can be converted to array Bvoid checkArray(int a[], int b[], int n){ int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required cout << operations << \"\\n\";} // Driver Codeint main(){ int a[] = { 3, 7, 1, 4, 1, 2 }; int b[] = { 3, 7, 3, 6, 3, 2 }; int size = sizeof(a) / sizeof(a[0]); checkArray(a, b, size); return 0;}", "e": 28116, "s": 26925, "text": null }, { "code": "// Java implementation to find the// minimum number of operations in// which the array A can be converted// to another array Bclass GFG { // Function to find the minimum // number of operations in which // array A can be converted to array B static void checkArray(int a[], int b[], int n) { int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required System.out.println(operations); } // Driver Code public static void main (String[] args) { int a[] = { 3, 7, 1, 4, 1, 2 }; int b[] = { 3, 7, 3, 6, 3, 2 }; int size = a.length; checkArray(a, b, size); }} // This code is contributed by AnkitRai01", "e": 29523, "s": 28116, "text": null }, { "code": "// C# implementation to find the// minimum number of operations in// which the array A can be converted// to another array Busing System; class GFG { // Function to find the minimum // number of operations in which // array A can be converted to array B static void checkArray(int []a, int []b, int n) { int operations = 0; int i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements int diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required Console.WriteLine(operations); } // Driver Code public static void Main (string[] args) { int []a = { 3, 7, 1, 4, 1, 2 }; int []b = { 3, 7, 3, 6, 3, 2 }; int size = a.Length; checkArray(a, b, size); }} // This code is contributed by AnkitRai01", "e": 30941, "s": 29523, "text": null }, { "code": "# Python3 implementation to find the# minimum number of operations in# which the array A can be converted# to another array B # Function to find the minimum# number of operations in which# array A can be converted to array Bdef checkArray(a, b, n) : operations = 0; i = 0; # Loop to iterate over the array while (i < n) : # if both elements are equal # then move to next element if (a[i] - b[i] == 0) : i += 1; continue; # Calculate the difference # between two elements diff = a[i] - b[i]; i += 1; # loop while the next pair of # elements have same difference while (i < n and a[i] - b[i] == diff) : i += 1; # Increase the number of # operations by 1 operations += 1; # Print the number of # operations required print(operations); # Driver Codeif __name__ == \"__main__\" : a = [ 3, 7, 1, 4, 1, 2 ]; b = [ 3, 7, 3, 6, 3, 2 ]; size = len(a); checkArray(a, b, size); # This code is contributed by AnkitRai01", "e": 32028, "s": 30941, "text": null }, { "code": "<script>// javascript implementation to find the// minimum number of operations in// which the array A can be converted// to another array B // Function to find the minimum // number of operations in which // array A can be converted to array B function checkArray(a , b , n) { var operations = 0; var i = 0; // Loop to iterate over the array while (i < n) { // if both elements are equal // then move to next element if (a[i] - b[i] == 0) { i++; continue; } // Calculate the difference // between two elements var diff = a[i] - b[i]; i++; // loop while the next pair of // elements have same difference while (i < n && a[i] - b[i] == diff) { i++; } // Increase the number of // operations by 1 operations++; } // Print the number of // operations required document.write(operations); } // Driver Code var a = [ 3, 7, 1, 4, 1, 2 ]; var b = [ 3, 7, 3, 6, 3, 2 ]; var size = a.length; checkArray(a, b, size); // This code contributed by Rajput-Ji</script>", "e": 33306, "s": 32028, "text": null }, { "code": null, "e": 33329, "s": 33306, "text": "Performance Analysis: " }, { "code": null, "e": 33476, "s": 33329, "text": "Time Complexity: As in the above approach, there is only one loop that takes O(N) time in the worst case. Hence, the Time Complexity will be O(N)." }, { "code": null, "e": 33612, "s": 33476, "text": "Auxiliary Space Complexity: As in the above approach, there is no extra space used. Hence, the auxiliary space complexity will be O(1)." }, { "code": null, "e": 33622, "s": 33614, "text": "ankthon" }, { "code": null, "e": 33632, "s": 33622, "text": "Rajput-Ji" }, { "code": null, "e": 33645, "s": 33632, "text": "ankita_saini" }, { "code": null, "e": 33654, "s": 33645, "text": "subarray" }, { "code": null, "e": 33661, "s": 33654, "text": "Arrays" }, { "code": null, "e": 33674, "s": 33661, "text": "Mathematical" }, { "code": null, "e": 33681, "s": 33674, "text": "Arrays" }, { "code": null, "e": 33694, "s": 33681, "text": "Mathematical" }, { "code": null, "e": 33792, "s": 33694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33801, "s": 33792, "text": "Comments" }, { "code": null, "e": 33814, "s": 33801, "text": "Old Comments" }, { "code": null, "e": 33858, "s": 33814, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33890, "s": 33858, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33913, "s": 33890, "text": "Introduction to Arrays" }, { "code": null, "e": 33927, "s": 33913, "text": "Linear Search" }, { "code": null, "e": 33995, "s": 33927, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34025, "s": 33995, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34040, "s": 34025, "text": "C++ Data Types" }, { "code": null, "e": 34100, "s": 34040, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34143, "s": 34100, "text": "Set in C++ Standard Template Library (STL)" } ]
Circumradius of a Cyclic Quadrilateral using the length of Sides - GeeksforGeeks
21 Apr, 2021 Given integers A, B, C, and D denoting the length of sides of a Cyclic Quadrilateral, the task is to find the circumradius i.e., the radius of circumcircle of the given cyclic quadrilateral. Examples: Input: A = 3, B = 4, C = 5, D= 6Output: 3.29 Input: A = 10, B = 30, C = 50, D = 20Output: 27.78 Approach: Follow the steps below to solve the problem: Calculate the semiperimeter of the cyclic quadrilateral with sides A, B, C and D by using the equation: Now, using Parameshvara’s circumradius formula shown below, calculate the radius for the circumcircle: Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program to find circumradius of// a cyclic quadrilateral using sides#include <bits/stdc++.h>using namespace std; // Function to return the circumradius// of a cyclic quadrilateral using sidesdouble Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codeint main(){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius cout << setprecision(3) << ans; return 0;} // This code is contributed by mohit kumar 29 // Java program to find circumradius of// a cyclic quadrilateral using sidesimport java.util.*; class GFG{ // Function to return the circumradius// of a cyclic quadrilateral using sidesstatic double Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = Math.sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codepublic static void main(String[] args){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius System.out.format("%.2f", ans);}} // This code is contributed by 29AjayKumar # Program to find Circumradius of# a cyclic quadrilateral using sides import math # Function to return the Circumradius# of a cyclic quadrilateral using sidesdef Circumradius(a, b, c, d): # Find semiperimeter s = (a + b + c + d) / 2 # Calculate the radius radius = (1 / 4)*math.sqrt(((a * b)+(c * d))* ((a * c)+(b * d))*((a * d)+(b * c)) /((s-a)*(s-b)*(s-c)*(s-d))) return radius # Driver Code # Given sidesA = 3B = 4C = 5D = 6 # Function Call ans = Circumradius(A, B, C, D) # Print the radiusprint(round(ans, 2)) // C# program to find circumradius of// a cyclic quadrilateral using sidesusing System; class GFG{ // Function to return the circumradius// of a cyclic quadrilateral using sidesstatic double Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = Math.Sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codepublic static void Main(String[] args){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius Console.Write("{0:F2}", ans);}} // This code is contributed by 29AjayKumar <script> // Javascript program to find circumradius of// a cyclic quadrilateral using sides // Function to return the circumradius// of a cyclic quadrilateral using sidesfunction Circumradius(a, b, c, d){ // Find semiperimeter var s = (a + b + c + d) / 2.0; // Calculate the radius var radius = Math.sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver codevar A = 3;var B = 4;var C = 5;var D = 6; // Function callvar ans = Circumradius(A, B, C, D); // Print the radiusdocument.write(ans.toFixed(2)); // This code is contributed by Khushboogoyal499 </script> 3.29 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 29AjayKumar khushboogoyal499 Mensuration 2D Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n21 Apr, 2021" }, { "code": null, "e": 26752, "s": 26561, "text": "Given integers A, B, C, and D denoting the length of sides of a Cyclic Quadrilateral, the task is to find the circumradius i.e., the radius of circumcircle of the given cyclic quadrilateral." }, { "code": null, "e": 26762, "s": 26752, "text": "Examples:" }, { "code": null, "e": 26807, "s": 26762, "text": "Input: A = 3, B = 4, C = 5, D= 6Output: 3.29" }, { "code": null, "e": 26858, "s": 26807, "text": "Input: A = 10, B = 30, C = 50, D = 20Output: 27.78" }, { "code": null, "e": 26913, "s": 26858, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 27017, "s": 26913, "text": "Calculate the semiperimeter of the cyclic quadrilateral with sides A, B, C and D by using the equation:" }, { "code": null, "e": 27120, "s": 27017, "text": "Now, using Parameshvara’s circumradius formula shown below, calculate the radius for the circumcircle:" }, { "code": null, "e": 27171, "s": 27120, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27177, "s": 27171, "text": "C++14" }, { "code": null, "e": 27182, "s": 27177, "text": "Java" }, { "code": null, "e": 27190, "s": 27182, "text": "Python3" }, { "code": null, "e": 27193, "s": 27190, "text": "C#" }, { "code": null, "e": 27204, "s": 27193, "text": "Javascript" }, { "code": "// C++ program to find circumradius of// a cyclic quadrilateral using sides#include <bits/stdc++.h>using namespace std; // Function to return the circumradius// of a cyclic quadrilateral using sidesdouble Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codeint main(){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius cout << setprecision(3) << ans; return 0;} // This code is contributed by mohit kumar 29", "e": 28064, "s": 27204, "text": null }, { "code": "// Java program to find circumradius of// a cyclic quadrilateral using sidesimport java.util.*; class GFG{ // Function to return the circumradius// of a cyclic quadrilateral using sidesstatic double Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = Math.sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codepublic static void main(String[] args){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius System.out.format(\"%.2f\", ans);}} // This code is contributed by 29AjayKumar", "e": 28981, "s": 28064, "text": null }, { "code": "# Program to find Circumradius of# a cyclic quadrilateral using sides import math # Function to return the Circumradius# of a cyclic quadrilateral using sidesdef Circumradius(a, b, c, d): # Find semiperimeter s = (a + b + c + d) / 2 # Calculate the radius radius = (1 / 4)*math.sqrt(((a * b)+(c * d))* ((a * c)+(b * d))*((a * d)+(b * c)) /((s-a)*(s-b)*(s-c)*(s-d))) return radius # Driver Code # Given sidesA = 3B = 4C = 5D = 6 # Function Call ans = Circumradius(A, B, C, D) # Print the radiusprint(round(ans, 2))", "e": 29543, "s": 28981, "text": null }, { "code": "// C# program to find circumradius of// a cyclic quadrilateral using sidesusing System; class GFG{ // Function to return the circumradius// of a cyclic quadrilateral using sidesstatic double Circumradius(int a, int b, int c, int d){ // Find semiperimeter double s = (a + b + c + d) / 2.0; // Calculate the radius double radius = Math.Sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver Codepublic static void Main(String[] args){ int A = 3; int B = 4; int C = 5; int D = 6; // Function call double ans = Circumradius(A, B, C, D); // Print the radius Console.Write(\"{0:F2}\", ans);}} // This code is contributed by 29AjayKumar", "e": 30450, "s": 29543, "text": null }, { "code": "<script> // Javascript program to find circumradius of// a cyclic quadrilateral using sides // Function to return the circumradius// of a cyclic quadrilateral using sidesfunction Circumradius(a, b, c, d){ // Find semiperimeter var s = (a + b + c + d) / 2.0; // Calculate the radius var radius = Math.sqrt(((a * b) + (c * d)) * ((a * c) + (b * d)) * ((a * d) + (b * c)) / ((s - a) * (s - b) * (s - c) * (s - d))); return radius / 4;} // Driver codevar A = 3;var B = 4;var C = 5;var D = 6; // Function callvar ans = Circumradius(A, B, C, D); // Print the radiusdocument.write(ans.toFixed(2)); // This code is contributed by Khushboogoyal499 </script>", "e": 31225, "s": 30450, "text": null }, { "code": null, "e": 31230, "s": 31225, "text": "3.29" }, { "code": null, "e": 31274, "s": 31230, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 31289, "s": 31274, "text": "mohit kumar 29" }, { "code": null, "e": 31301, "s": 31289, "text": "29AjayKumar" }, { "code": null, "e": 31318, "s": 31301, "text": "khushboogoyal499" }, { "code": null, "e": 31333, "s": 31318, "text": "Mensuration 2D" }, { "code": null, "e": 31343, "s": 31333, "text": "Geometric" }, { "code": null, "e": 31356, "s": 31343, "text": "Mathematical" }, { "code": null, "e": 31375, "s": 31356, "text": "School Programming" }, { "code": null, "e": 31388, "s": 31375, "text": "Mathematical" }, { "code": null, "e": 31398, "s": 31388, "text": "Geometric" }, { "code": null, "e": 31496, "s": 31398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31562, "s": 31496, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 31594, "s": 31562, "text": "Program to find slope of a line" }, { "code": null, "e": 31655, "s": 31594, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 31701, "s": 31655, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 31771, "s": 31701, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 31801, "s": 31771, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31861, "s": 31801, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31876, "s": 31861, "text": "C++ Data Types" }, { "code": null, "e": 31919, "s": 31876, "text": "Set in C++ Standard Template Library (STL)" } ]
D3.js | d3.min() function - GeeksforGeeks
28 Jun, 2019 The d3.min() function in D3.js is used to returns the minimum value in the given array using natural order. If an array is empty then it returns undefined as output. Syntax: d3.min(Array) Parameters: This function accepts a parameters Array which is an array of elements whose minimum value is to be calculated. Here elements might be integers or any strings. Return Value: It returns the minimum value. Below programs illustrate the d3.min() function in D3.js. Example 1: <html> <head> <title>Getting minimum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = [10, 20, 30, 40, 50, 60]; var Array2 = [1, 2]; var Array3 = [0, 1.5, 6.8]; var Array4 = [.8, .08, .008]; // Calling to d3.min() function A = d3.min(Array1); B = d3.min(Array2); C = d3.min(Array3); D = d3.min(Array4); // Getting minimum value document.write(A + "<br>"); document.write(B + "<br>"); document.write(C + "<br>"); document.write(D + "<br>"); </script></body> </html> Output: 10 1 0 0.008 Example 2: <html> <head> <title>Getting minimum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = []; var Array2 = ["a", "b", "c"]; var Array3 = ["A", "B", "C"]; var Array4 = ["Geek", "Geeks", "GeeksforGeeks"]; // Calling to d3.min() function A = d3.min(Array1); B = d3.min(Array2); C = d3.min(Array3); D = d3.min(Array4); // Getting minimum value document.write(A + "<br>"); document.write(B + "<br>"); document.write(C + "<br>"); document.write(D + "<br>"); </script></body> </html> Output: undefined a A Geek D3.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 append HTML code to a div using 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25461, "s": 25433, "text": "\n28 Jun, 2019" }, { "code": null, "e": 25627, "s": 25461, "text": "The d3.min() function in D3.js is used to returns the minimum value in the given array using natural order. If an array is empty then it returns undefined as output." }, { "code": null, "e": 25635, "s": 25627, "text": "Syntax:" }, { "code": null, "e": 25649, "s": 25635, "text": "d3.min(Array)" }, { "code": null, "e": 25821, "s": 25649, "text": "Parameters: This function accepts a parameters Array which is an array of elements whose minimum value is to be calculated. Here elements might be integers or any strings." }, { "code": null, "e": 25865, "s": 25821, "text": "Return Value: It returns the minimum value." }, { "code": null, "e": 25923, "s": 25865, "text": "Below programs illustrate the d3.min() function in D3.js." }, { "code": null, "e": 25934, "s": 25923, "text": "Example 1:" }, { "code": "<html> <head> <title>Getting minimum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = [10, 20, 30, 40, 50, 60]; var Array2 = [1, 2]; var Array3 = [0, 1.5, 6.8]; var Array4 = [.8, .08, .008]; // Calling to d3.min() function A = d3.min(Array1); B = d3.min(Array2); C = d3.min(Array3); D = d3.min(Array4); // Getting minimum value document.write(A + \"<br>\"); document.write(B + \"<br>\"); document.write(C + \"<br>\"); document.write(D + \"<br>\"); </script></body> </html>", "e": 26620, "s": 25934, "text": null }, { "code": null, "e": 26628, "s": 26620, "text": "Output:" }, { "code": null, "e": 26641, "s": 26628, "text": "10\n1\n0\n0.008" }, { "code": null, "e": 26652, "s": 26641, "text": "Example 2:" }, { "code": "<html> <head> <title>Getting minimum value</title></head> <body> <script src='https://d3js.org/d3.v4.min.js'> </script> <script> // initialising the array of elements var Array1 = []; var Array2 = [\"a\", \"b\", \"c\"]; var Array3 = [\"A\", \"B\", \"C\"]; var Array4 = [\"Geek\", \"Geeks\", \"GeeksforGeeks\"]; // Calling to d3.min() function A = d3.min(Array1); B = d3.min(Array2); C = d3.min(Array3); D = d3.min(Array4); // Getting minimum value document.write(A + \"<br>\"); document.write(B + \"<br>\"); document.write(C + \"<br>\"); document.write(D + \"<br>\"); </script></body> </html>", "e": 27346, "s": 26652, "text": null }, { "code": null, "e": 27354, "s": 27346, "text": "Output:" }, { "code": null, "e": 27373, "s": 27354, "text": "undefined\na\nA\nGeek" }, { "code": null, "e": 27379, "s": 27373, "text": "D3.js" }, { "code": null, "e": 27390, "s": 27379, "text": "JavaScript" }, { "code": null, "e": 27407, "s": 27390, "text": "Web Technologies" }, { "code": null, "e": 27505, "s": 27407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27545, "s": 27505, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27590, "s": 27545, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27651, "s": 27590, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27723, "s": 27651, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27775, "s": 27723, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27815, "s": 27775, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27848, "s": 27815, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27893, "s": 27848, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27936, "s": 27893, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Draw Over Other Apps in Android? - GeeksforGeeks
06 Jun, 2021 Sometimes we require our app to show some content on the main screen irrespective of the app running in the foreground, this process is known as drawing over other apps. There are many apps that use this functionality to provide maximum features with minimum screen coverage. This also enables the user to do multitasking. For example, the chat bubble of Facebook Messenger, Mobile Over Usage notice of YourHour App, Voice Command of Google, and many more. We can create similar functionality using the WindowManager interface provided by Android SDK. The Android WindowManager is a system service that controls which windows are displayed and how they are arranged on the screen. When you launch or close an app or rotate the screen, it automatically executes window transitions and animations, among other things. Every activity has its own Window that displays its content on the screen. When you execute setContentView on an activity, it adds the view to the default window of the activity. Because the default window fills the screen and hides any other activities, the WindowManager will show whatever window is on top. So, in most cases, you don’t need to bother about windows; simply build activity, and Android will take care of the rest. In order to manipulate the Window, we need to interact with the window manager. Now in order to display over other apps, we need to create some kind of service, because the activity will close when some other app comes into the foreground. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the AndroidManifest.xml file In order to draw over other apps we require, android.permission.SYSTEM_ALERT_WINDOW permissions and for android with API version > 23 we need to ask for this on runtime. android.permission.SYSTEM_ALERT_WINDOW allows an app to create windows using the type WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, shown on top of all other apps. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.raghav.gfgwindowmanager"> <!-- add required permission --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.GFGWindowManager"> <!-- register the service --> <service android:name=".ForegroundService" android:enabled="true" android:exported="true"/> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Creating the popup_window.xml layout file XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" android:padding="4dp" android:background="@null"> <androidx.cardview.widget.CardView android:layout_centerInParent="true" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardCornerRadius="5dp"> <LinearLayout android:padding="10dp" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/titleText" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Displaying over other apps!" android:textSize="20sp" android:textStyle="bold" android:padding="10dp"/> <Button android:id="@+id/window_close" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Remove" /> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout> Step 5: Working with Window.java Java package com.raghav.gfgwindowmanager; import android.content.Context;import android.graphics.PixelFormat;import android.os.Build;import android.util.Log;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager; import static android.content.Context.WINDOW_SERVICE; public class Window { // declaring required variables private Context context; private View mView; private WindowManager.LayoutParams mParams; private WindowManager mWindowManager; private LayoutInflater layoutInflater; public Window(Context context){ this.context=context; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // set the layout parameters of the window mParams = new WindowManager.LayoutParams( // Shrink the window to wrap the content rather // than filling the screen WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, // Display it on top of other application windows WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // Don't let it grab the input focus WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // Make the underlying application window visible // through any transparent parts PixelFormat.TRANSLUCENT); } // getting a LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // inflating the view with the custom layout we created mView = layoutInflater.inflate(R.layout.popup_window, null); // set onClickListener on the remove button, which removes // the view from the window mView.findViewById(R.id.window_close).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { close(); } }); // Define the position of the // window within the screen mParams.gravity = Gravity.CENTER; mWindowManager = (WindowManager)context.getSystemService(WINDOW_SERVICE); } public void open() { try { // check if the view is already // inflated or present in the window if(mView.getWindowToken()==null) { if(mView.getParent()==null) { mWindowManager.addView(mView, mParams); } } } catch (Exception e) { Log.d("Error1",e.toString()); } } public void close() { try { // remove the view from the window ((WindowManager)context.getSystemService(WINDOW_SERVICE)).removeView(mView); // invalidate the view mView.invalidate(); // remove all views ((ViewGroup)mView.getParent()).removeAllViews(); // the above steps are necessary when you are adding and removing // the view simultaneously, it might give some exceptions } catch (Exception e) { Log.d("Error2",e.toString()); } }} Step 6: Creating the ForegroundService class Java import android.app.Notification;import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.Build;import android.os.IBinder; import androidx.annotation.RequiresApi;import androidx.core.app.NotificationCompat; public class ForegroundService extends Service { public ForegroundService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); // create the custom or default notification // based on the android version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startMyOwnForeground(); else startForeground(1, new Notification()); // create an instance of Window class // and display the content on screen Window window=new Window(this); window.open(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } // for android version >=O we need to create // custom notification stating // foreground service is running @RequiresApi(Build.VERSION_CODES.O) private void startMyOwnForeground() { String NOTIFICATION_CHANNEL_ID = "example.permanence"; String channelName = "Background Service"; NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle("Service running") .setContentText("Displaying over other apps") // this is important, otherwise the notification will show the way // you want i.e. it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); }} Step 7: Working with MainActivity.java Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.provider.Settings; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkOverlayPermission(); startService(); } // method for starting the service public void startService(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // check if the user has already granted // the Draw over other apps permission if(Settings.canDrawOverlays(this)) { // start the service based on the android version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(new Intent(this, ForegroundService.class)); } else { startService(new Intent(this, ForegroundService.class)); } } }else{ startService(new Intent(this, ForegroundService.class)); } } // method to ask user to grant the Overlay permission public void checkOverlayPermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { // send user to the device settings Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); startActivity(myIntent); } } } // check for permission again when user grants it from // the device settings, and start the service @Override protected void onResume() { super.onResume(); startService(); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26407, "s": 26379, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26959, "s": 26407, "text": "Sometimes we require our app to show some content on the main screen irrespective of the app running in the foreground, this process is known as drawing over other apps. There are many apps that use this functionality to provide maximum features with minimum screen coverage. This also enables the user to do multitasking. For example, the chat bubble of Facebook Messenger, Mobile Over Usage notice of YourHour App, Voice Command of Google, and many more. We can create similar functionality using the WindowManager interface provided by Android SDK." }, { "code": null, "e": 27223, "s": 26959, "text": "The Android WindowManager is a system service that controls which windows are displayed and how they are arranged on the screen. When you launch or close an app or rotate the screen, it automatically executes window transitions and animations, among other things." }, { "code": null, "e": 27895, "s": 27223, "text": "Every activity has its own Window that displays its content on the screen. When you execute setContentView on an activity, it adds the view to the default window of the activity. Because the default window fills the screen and hides any other activities, the WindowManager will show whatever window is on top. So, in most cases, you don’t need to bother about windows; simply build activity, and Android will take care of the rest. In order to manipulate the Window, we need to interact with the window manager. Now in order to display over other apps, we need to create some kind of service, because the activity will close when some other app comes into the foreground." }, { "code": null, "e": 28062, "s": 27895, "text": "A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 28091, "s": 28062, "text": "Step 1: Create a New Project" }, { "code": null, "e": 28253, "s": 28091, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 28303, "s": 28253, "text": "Step 2: Working with the AndroidManifest.xml file" }, { "code": null, "e": 28644, "s": 28303, "text": "In order to draw over other apps we require, android.permission.SYSTEM_ALERT_WINDOW permissions and for android with API version > 23 we need to ask for this on runtime. android.permission.SYSTEM_ALERT_WINDOW allows an app to create windows using the type WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, shown on top of all other apps." }, { "code": null, "e": 28648, "s": 28644, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.raghav.gfgwindowmanager\"> <!-- add required permission --> <uses-permission android:name=\"android.permission.FOREGROUND_SERVICE\"/> <uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.GFGWindowManager\"> <!-- register the service --> <service android:name=\".ForegroundService\" android:enabled=\"true\" android:exported=\"true\"/> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 29748, "s": 28648, "text": null }, { "code": null, "e": 29796, "s": 29748, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 29939, "s": 29796, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 29943, "s": 29939, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World!\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 30715, "s": 29943, "text": null }, { "code": null, "e": 30765, "s": 30715, "text": "Step 4: Creating the popup_window.xml layout file" }, { "code": null, "e": 30769, "s": 30765, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:padding=\"4dp\" android:background=\"@null\"> <androidx.cardview.widget.CardView android:layout_centerInParent=\"true\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:cardCornerRadius=\"5dp\"> <LinearLayout android:padding=\"10dp\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/titleText\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Displaying over other apps!\" android:textSize=\"20sp\" android:textStyle=\"bold\" android:padding=\"10dp\"/> <Button android:id=\"@+id/window_close\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Remove\" /> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>", "e": 32076, "s": 30769, "text": null }, { "code": null, "e": 32109, "s": 32076, "text": "Step 5: Working with Window.java" }, { "code": null, "e": 32114, "s": 32109, "text": "Java" }, { "code": "package com.raghav.gfgwindowmanager; import android.content.Context;import android.graphics.PixelFormat;import android.os.Build;import android.util.Log;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager; import static android.content.Context.WINDOW_SERVICE; public class Window { // declaring required variables private Context context; private View mView; private WindowManager.LayoutParams mParams; private WindowManager mWindowManager; private LayoutInflater layoutInflater; public Window(Context context){ this.context=context; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // set the layout parameters of the window mParams = new WindowManager.LayoutParams( // Shrink the window to wrap the content rather // than filling the screen WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, // Display it on top of other application windows WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // Don't let it grab the input focus WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // Make the underlying application window visible // through any transparent parts PixelFormat.TRANSLUCENT); } // getting a LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // inflating the view with the custom layout we created mView = layoutInflater.inflate(R.layout.popup_window, null); // set onClickListener on the remove button, which removes // the view from the window mView.findViewById(R.id.window_close).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { close(); } }); // Define the position of the // window within the screen mParams.gravity = Gravity.CENTER; mWindowManager = (WindowManager)context.getSystemService(WINDOW_SERVICE); } public void open() { try { // check if the view is already // inflated or present in the window if(mView.getWindowToken()==null) { if(mView.getParent()==null) { mWindowManager.addView(mView, mParams); } } } catch (Exception e) { Log.d(\"Error1\",e.toString()); } } public void close() { try { // remove the view from the window ((WindowManager)context.getSystemService(WINDOW_SERVICE)).removeView(mView); // invalidate the view mView.invalidate(); // remove all views ((ViewGroup)mView.getParent()).removeAllViews(); // the above steps are necessary when you are adding and removing // the view simultaneously, it might give some exceptions } catch (Exception e) { Log.d(\"Error2\",e.toString()); } }}", "e": 35374, "s": 32114, "text": null }, { "code": null, "e": 35419, "s": 35374, "text": "Step 6: Creating the ForegroundService class" }, { "code": null, "e": 35424, "s": 35419, "text": "Java" }, { "code": "import android.app.Notification;import android.app.NotificationChannel;import android.app.NotificationManager;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.Build;import android.os.IBinder; import androidx.annotation.RequiresApi;import androidx.core.app.NotificationCompat; public class ForegroundService extends Service { public ForegroundService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException(\"Not yet implemented\"); } @Override public void onCreate() { super.onCreate(); // create the custom or default notification // based on the android version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startMyOwnForeground(); else startForeground(1, new Notification()); // create an instance of Window class // and display the content on screen Window window=new Window(this); window.open(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } // for android version >=O we need to create // custom notification stating // foreground service is running @RequiresApi(Build.VERSION_CODES.O) private void startMyOwnForeground() { String NOTIFICATION_CHANNEL_ID = \"example.permanence\"; String channelName = \"Background Service\"; NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert manager != null; manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle(\"Service running\") .setContentText(\"Displaying over other apps\") // this is important, otherwise the notification will show the way // you want i.e. it will show some default notification .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); }}", "e": 37973, "s": 35424, "text": null }, { "code": null, "e": 38012, "s": 37973, "text": "Step 7: Working with MainActivity.java" }, { "code": null, "e": 38202, "s": 38012, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 38207, "s": 38202, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.provider.Settings; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkOverlayPermission(); startService(); } // method for starting the service public void startService(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // check if the user has already granted // the Draw over other apps permission if(Settings.canDrawOverlays(this)) { // start the service based on the android version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(new Intent(this, ForegroundService.class)); } else { startService(new Intent(this, ForegroundService.class)); } } }else{ startService(new Intent(this, ForegroundService.class)); } } // method to ask user to grant the Overlay permission public void checkOverlayPermission(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { // send user to the device settings Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); startActivity(myIntent); } } } // check for permission again when user grants it from // the device settings, and start the service @Override protected void onResume() { super.onResume(); startService(); }}", "e": 40009, "s": 38207, "text": null }, { "code": null, "e": 40017, "s": 40009, "text": "Output:" }, { "code": null, "e": 40025, "s": 40017, "text": "Android" }, { "code": null, "e": 40030, "s": 40025, "text": "Java" }, { "code": null, "e": 40035, "s": 40030, "text": "Java" }, { "code": null, "e": 40043, "s": 40035, "text": "Android" }, { "code": null, "e": 40141, "s": 40043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40179, "s": 40141, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 40218, "s": 40179, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 40268, "s": 40218, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 40319, "s": 40268, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 40361, "s": 40319, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 40376, "s": 40361, "text": "Arrays in Java" }, { "code": null, "e": 40420, "s": 40376, "text": "Split() String method in Java with examples" }, { "code": null, "e": 40442, "s": 40420, "text": "For-each loop in Java" }, { "code": null, "e": 40493, "s": 40442, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
HTML <br> Tag - GeeksforGeeks
17 Mar, 2022 In this article, we will know how to add line-break using HTML <br> tag. The browser does not recognize new line and paragraph formatting in the text. If you want to start a new line, you need to insert a line break with the help of the <br>. The <br> tag inserts a single carriage return or breaks in the document. This element has no end tag. Example: In this example, we use <br> tag in p tag to line break the content. HTML <!DOCTYPE html><html> <body> <h2>GeeksforGeeks</h2> <!--br tag is used in below paragraph--> <p>Hi Geeks! <br>Welcome to GeeksforGeeks</p> </body> </html> Output: HTML <br> tag Let us consider an example. Type the following HTML code does not use the <BR> tag in notepad, save the document as an HTML file, and open it in a browser. You will notice that the text shows line breaks at four instances, the browser displays the entire text as a single paragraph. Syntax: <br> Attributes: This tag accepts an attribute called clear clear: Indicates where to begin the next line after the break. Example: This example explains the use of the <br> tag to add the line-breake. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>br Tag</h2> <!-- br tag --> <p>GeeksforGeeks: <br> Computer science portal</p> </body> </html> Output: HTML <br> tag Supported Browsers: Google Chrome 1 and above Microsoft Edge 12 and above Internet Explorer Firefox 1 and above Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 ysachin2314 bhaskargeeksforgeeks HTML-Tags Picked HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to 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) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24306, "s": 24278, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24651, "s": 24306, "text": "In this article, we will know how to add line-break using HTML <br> tag. The browser does not recognize new line and paragraph formatting in the text. If you want to start a new line, you need to insert a line break with the help of the <br>. The <br> tag inserts a single carriage return or breaks in the document. This element has no end tag." }, { "code": null, "e": 24729, "s": 24651, "text": "Example: In this example, we use <br> tag in p tag to line break the content." }, { "code": null, "e": 24734, "s": 24729, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>GeeksforGeeks</h2> <!--br tag is used in below paragraph--> <p>Hi Geeks! <br>Welcome to GeeksforGeeks</p> </body> </html>", "e": 24907, "s": 24734, "text": null }, { "code": null, "e": 24915, "s": 24907, "text": "Output:" }, { "code": null, "e": 24929, "s": 24915, "text": "HTML <br> tag" }, { "code": null, "e": 25212, "s": 24929, "text": "Let us consider an example. Type the following HTML code does not use the <BR> tag in notepad, save the document as an HTML file, and open it in a browser. You will notice that the text shows line breaks at four instances, the browser displays the entire text as a single paragraph." }, { "code": null, "e": 25220, "s": 25212, "text": "Syntax:" }, { "code": null, "e": 25225, "s": 25220, "text": "<br>" }, { "code": null, "e": 25280, "s": 25225, "text": "Attributes: This tag accepts an attribute called clear" }, { "code": null, "e": 25343, "s": 25280, "text": "clear: Indicates where to begin the next line after the break." }, { "code": null, "e": 25422, "s": 25343, "text": "Example: This example explains the use of the <br> tag to add the line-breake." }, { "code": null, "e": 25427, "s": 25422, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>br Tag</h2> <!-- br tag --> <p>GeeksforGeeks: <br> Computer science portal</p> </body> </html>", "e": 25606, "s": 25427, "text": null }, { "code": null, "e": 25614, "s": 25606, "text": "Output:" }, { "code": null, "e": 25628, "s": 25614, "text": "HTML <br> tag" }, { "code": null, "e": 25649, "s": 25628, "text": "Supported Browsers: " }, { "code": null, "e": 25675, "s": 25649, "text": "Google Chrome 1 and above" }, { "code": null, "e": 25703, "s": 25675, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 25721, "s": 25703, "text": "Internet Explorer" }, { "code": null, "e": 25741, "s": 25721, "text": "Firefox 1 and above" }, { "code": null, "e": 25748, "s": 25741, "text": "Safari" }, { "code": null, "e": 25754, "s": 25748, "text": "Opera" }, { "code": null, "e": 25891, "s": 25754, "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": 25905, "s": 25891, "text": "shubhamyadav4" }, { "code": null, "e": 25917, "s": 25905, "text": "ysachin2314" }, { "code": null, "e": 25938, "s": 25917, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 25948, "s": 25938, "text": "HTML-Tags" }, { "code": null, "e": 25955, "s": 25948, "text": "Picked" }, { "code": null, "e": 25960, "s": 25955, "text": "HTML" }, { "code": null, "e": 25965, "s": 25960, "text": "HTML" }, { "code": null, "e": 26063, "s": 25965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26113, "s": 26063, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26175, "s": 26113, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26223, "s": 26175, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26283, "s": 26223, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26336, "s": 26283, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 26397, "s": 26336, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26421, "s": 26397, "text": "REST API (Introduction)" }, { "code": null, "e": 26471, "s": 26421, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26521, "s": 26471, "text": "CSS to put icon inside an input element in a form" } ]
Find all possible subarrays having product less than or equal to K - GeeksforGeeks
23 May, 2021 Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K. Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ≤ K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5}, {6}, {2}. Input: arr[] = {2, 7, 1, 4}, K = 7 Output: [[2], [7], [1], [7, 1], [4], [1, 4]] Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays from the given array and for each subarray, check if its product is less than or equal to K or not and print accordingly. Time Complexity: O(N3) Auxiliary Space: O(N) Efficient Approach: The above approach can be optimized by observing that: If the product of all the elements of a subarray is less than or equal to K, then all the subarrays possible from this subarray also has product less than or equal to K. Therefore, these subarrays need to be included in the answer as well. Follow the steps below to solve the problem: Initialize a pointer start pointing to the first index of the array.Iterate over the array and keep calculating the product of the array elements and store it in a variable, say multi.If multi exceeds K: keep dividing multi by arr[start] and keep incrementing start until multi reduces to ≤ K.If multi ≤ K: Iterate from the current index to start, and store the subarrays in an Arraylist.Finally, once all subarrays are generated, print the Arraylist which contains all the subarrays obtained. Initialize a pointer start pointing to the first index of the array. Iterate over the array and keep calculating the product of the array elements and store it in a variable, say multi. If multi exceeds K: keep dividing multi by arr[start] and keep incrementing start until multi reduces to ≤ K. If multi ≤ K: Iterate from the current index to start, and store the subarrays in an Arraylist. Finally, once all subarrays are generated, print the Arraylist which contains all the subarrays obtained. 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 return all possible// subarrays having product less// than or equal to Kvector<vector<int>> maxSubArray(int arr[], int n, int K){ // Store the required subarrays vector<vector<int>> solution; // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (n <= 1 || K < 0) { return solution; } // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements vector<int> list; // Store the subarray elements for(int j = i; j >= start; j--) { list.insert(list.begin(), arr[j]); // Add the subarrays // to the list solution.push_back(list); } } // Return the final // list of subarrays return solution;} // Driver Codeint main(){ int arr[] = { 2, 7, 1, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 7; vector<vector<int>> v = maxSubArray(arr, n, K); cout << "["; bool first = true; for(auto x : v) { if (!first) { cout << ", "; } else { first = false; } cout << "["; bool ff = true; for(int y : x) { if (!ff) { cout << ", "; } else { ff = false; } cout << y; } cout << "]"; } cout << "]"; return 0;} // This code is contributed by rutvik_56 // Java Program to implement// the above approach import java.io.*;import java.util.*; class GFG { // Function to return all possible // subarrays having product less // than or equal to K public static List<List<Integer> > maxSubArray( int[] arr, int K) { // Store the required subarrays List<List<Integer> > solution = new ArrayList<>(); // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (arr.length <= 1 || K < 0) { return new ArrayList<>(); } // Iterate over the array for (int i = 0; i < arr.length; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements List<Integer> list = new ArrayList<>(); // Store the subarray elements for (int j = i; j >= start; j--) { list.add(0, arr[j]); // Add the subarrays // to the list solution.add( new ArrayList<>(list)); } } // Return the final // list of subarrays return solution; } // Driver Code public static void main(String[] args) { int[] arr = { 2, 7, 1, 4 }; int K = 7; System.out.println(maxSubArray(arr, K)); }} # Python3 program to implement# the above approach # Function to return all possible# subarrays having product less# than or equal to Kdef maxSubArray(arr, n, K): # Store the required subarrays solution = [] # Stores the product of # current subarray multi = 1 # Stores the starting index # of the current subarray start = 0 # Check for empty array if (n <= 1 or K < 0): return solution # Iterate over the array for i in range(n): # Calculate product multi = multi * arr[i] # If product exceeds K while (multi > K): # Reduce product multi = multi // arr[start] # Increase starting index # of current subarray start += 1 # Stores the subarray elements li = [] j = i # Store the subarray elements while(j >= start): li.insert(0, arr[j]) # Add the subarrays # to the li solution.append(list(li)) j -= 1 # Return the final # li of subarrays return solution # Driver Codeif __name__=='__main__': arr = [ 2, 7, 1, 4 ] n = len(arr) K = 7 v = maxSubArray(arr, n, K) print(v) # This code is contributed by pratham76 // C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return all possible// subarrays having product less// than or equal to Kpublic static List<List<int>> maxSubArray(int[] arr, int K){ // Store the required subarrays List<List<int> > solution = new List<List<int>>(); // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (arr.Length <= 1 || K < 0) { return new List<List<int>>(); } // Iterate over the array for (int i = 0; i < arr.Length; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements List<int> list = new List<int>(); // Store the subarray elements for (int j = i; j >= start; j--) { list.Insert(0, arr[j]); // Add the subarrays // to the list solution.Add(new List<int>(list)); } } // Return the final // list of subarrays return solution;} // Driver Codepublic static void Main(String[] args){ int[] arr = {2, 7, 1, 4}; int K = 7; List<List<int> > list = maxSubArray(arr, K); foreach(List<int> i in list) { Console.Write("["); foreach(int j in i) { Console.Write(j); if(i.Count > 1) Console.Write(","); } Console.Write("]"); }}} // This code is contributed by 29AjayKumar <script>// js program to implement// the above approach // Function to return all possible// subarrays having product less// than or equal to Kfunction maxSubArray(arr, n, K){ // Store the required subarrays let solution = []; // Stores the product of // current subarray let multi = 1; // Stores the starting index // of the current subarray let start = 0; // Check for empty array if (n <= 1 || K < 0) { return solution; } // Iterate over the array for(let i = 0; i < n; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi =Math.floor( multi / arr[start]); // Increase starting index // of current subarray start++; } // Stores the subarray elements let list = []; // Store the subarray elements for(let j = i; j >= start; j--) { list.unshift(arr[j]); // Add the subarrays // to the list solution.push(list); } } // Return the final // list of subarrays return solution;} // Driver Code let arr = [ 2, 7, 1, 4 ]; let n = arr.length; let K = 7; let v = maxSubArray(arr, n, K); document.write( "["); let first = true; for(let x=0;x< v.length;x++) { if (!first) { document.write(", "); } else { first = false; } document.write( "["); let ff = true; for(let y =0;y<v[x].length;y++) { if (!ff) { document.write(", "); } else { ff = false; } document.write(v[x][y]); } document.write("]"); } document.write( "]"); </script> [[2], [7], [1], [7, 1], [4], [1, 4]] Time Complexity: O(N2)Auxiliary Space: O(1) 29AjayKumar rutvik_56 pratham76 rohitsingh07052 Java-ArrayList subarray Arrays Mathematical Searching Arrays Searching Mathematical 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 Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n23 May, 2021" }, { "code": null, "e": 26165, "s": 26041, "text": "Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K." }, { "code": null, "e": 26402, "s": 26165, "text": "Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ≤ K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5}, {6}, {2}." }, { "code": null, "e": 26482, "s": 26402, "text": "Input: arr[] = {2, 7, 1, 4}, K = 7 Output: [[2], [7], [1], [7, 1], [4], [1, 4]]" }, { "code": null, "e": 26702, "s": 26482, "text": "Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays from the given array and for each subarray, check if its product is less than or equal to K or not and print accordingly. " }, { "code": null, "e": 26749, "s": 26702, "text": "Time Complexity: O(N3) Auxiliary Space: O(N) " }, { "code": null, "e": 26825, "s": 26749, "text": "Efficient Approach: The above approach can be optimized by observing that: " }, { "code": null, "e": 27065, "s": 26825, "text": "If the product of all the elements of a subarray is less than or equal to K, then all the subarrays possible from this subarray also has product less than or equal to K. Therefore, these subarrays need to be included in the answer as well." }, { "code": null, "e": 27112, "s": 27065, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 27606, "s": 27112, "text": "Initialize a pointer start pointing to the first index of the array.Iterate over the array and keep calculating the product of the array elements and store it in a variable, say multi.If multi exceeds K: keep dividing multi by arr[start] and keep incrementing start until multi reduces to ≤ K.If multi ≤ K: Iterate from the current index to start, and store the subarrays in an Arraylist.Finally, once all subarrays are generated, print the Arraylist which contains all the subarrays obtained." }, { "code": null, "e": 27675, "s": 27606, "text": "Initialize a pointer start pointing to the first index of the array." }, { "code": null, "e": 27792, "s": 27675, "text": "Iterate over the array and keep calculating the product of the array elements and store it in a variable, say multi." }, { "code": null, "e": 27902, "s": 27792, "text": "If multi exceeds K: keep dividing multi by arr[start] and keep incrementing start until multi reduces to ≤ K." }, { "code": null, "e": 27998, "s": 27902, "text": "If multi ≤ K: Iterate from the current index to start, and store the subarrays in an Arraylist." }, { "code": null, "e": 28104, "s": 27998, "text": "Finally, once all subarrays are generated, print the Arraylist which contains all the subarrays obtained." }, { "code": null, "e": 28156, "s": 28104, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28160, "s": 28156, "text": "C++" }, { "code": null, "e": 28165, "s": 28160, "text": "Java" }, { "code": null, "e": 28173, "s": 28165, "text": "Python3" }, { "code": null, "e": 28176, "s": 28173, "text": "C#" }, { "code": null, "e": 28187, "s": 28176, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to return all possible// subarrays having product less// than or equal to Kvector<vector<int>> maxSubArray(int arr[], int n, int K){ // Store the required subarrays vector<vector<int>> solution; // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (n <= 1 || K < 0) { return solution; } // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements vector<int> list; // Store the subarray elements for(int j = i; j >= start; j--) { list.insert(list.begin(), arr[j]); // Add the subarrays // to the list solution.push_back(list); } } // Return the final // list of subarrays return solution;} // Driver Codeint main(){ int arr[] = { 2, 7, 1, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 7; vector<vector<int>> v = maxSubArray(arr, n, K); cout << \"[\"; bool first = true; for(auto x : v) { if (!first) { cout << \", \"; } else { first = false; } cout << \"[\"; bool ff = true; for(int y : x) { if (!ff) { cout << \", \"; } else { ff = false; } cout << y; } cout << \"]\"; } cout << \"]\"; return 0;} // This code is contributed by rutvik_56", "e": 30277, "s": 28187, "text": null }, { "code": "// Java Program to implement// the above approach import java.io.*;import java.util.*; class GFG { // Function to return all possible // subarrays having product less // than or equal to K public static List<List<Integer> > maxSubArray( int[] arr, int K) { // Store the required subarrays List<List<Integer> > solution = new ArrayList<>(); // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (arr.length <= 1 || K < 0) { return new ArrayList<>(); } // Iterate over the array for (int i = 0; i < arr.length; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements List<Integer> list = new ArrayList<>(); // Store the subarray elements for (int j = i; j >= start; j--) { list.add(0, arr[j]); // Add the subarrays // to the list solution.add( new ArrayList<>(list)); } } // Return the final // list of subarrays return solution; } // Driver Code public static void main(String[] args) { int[] arr = { 2, 7, 1, 4 }; int K = 7; System.out.println(maxSubArray(arr, K)); }}", "e": 32025, "s": 30277, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to return all possible# subarrays having product less# than or equal to Kdef maxSubArray(arr, n, K): # Store the required subarrays solution = [] # Stores the product of # current subarray multi = 1 # Stores the starting index # of the current subarray start = 0 # Check for empty array if (n <= 1 or K < 0): return solution # Iterate over the array for i in range(n): # Calculate product multi = multi * arr[i] # If product exceeds K while (multi > K): # Reduce product multi = multi // arr[start] # Increase starting index # of current subarray start += 1 # Stores the subarray elements li = [] j = i # Store the subarray elements while(j >= start): li.insert(0, arr[j]) # Add the subarrays # to the li solution.append(list(li)) j -= 1 # Return the final # li of subarrays return solution # Driver Codeif __name__=='__main__': arr = [ 2, 7, 1, 4 ] n = len(arr) K = 7 v = maxSubArray(arr, n, K) print(v) # This code is contributed by pratham76", "e": 33404, "s": 32025, "text": null }, { "code": "// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return all possible// subarrays having product less// than or equal to Kpublic static List<List<int>> maxSubArray(int[] arr, int K){ // Store the required subarrays List<List<int> > solution = new List<List<int>>(); // Stores the product of // current subarray int multi = 1; // Stores the starting index // of the current subarray int start = 0; // Check for empty array if (arr.Length <= 1 || K < 0) { return new List<List<int>>(); } // Iterate over the array for (int i = 0; i < arr.Length; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi = multi / arr[start]; // Increase starting index // of current subarray start++; } // Stores the subarray elements List<int> list = new List<int>(); // Store the subarray elements for (int j = i; j >= start; j--) { list.Insert(0, arr[j]); // Add the subarrays // to the list solution.Add(new List<int>(list)); } } // Return the final // list of subarrays return solution;} // Driver Codepublic static void Main(String[] args){ int[] arr = {2, 7, 1, 4}; int K = 7; List<List<int> > list = maxSubArray(arr, K); foreach(List<int> i in list) { Console.Write(\"[\"); foreach(int j in i) { Console.Write(j); if(i.Count > 1) Console.Write(\",\"); } Console.Write(\"]\"); }}} // This code is contributed by 29AjayKumar", "e": 35034, "s": 33404, "text": null }, { "code": "<script>// js program to implement// the above approach // Function to return all possible// subarrays having product less// than or equal to Kfunction maxSubArray(arr, n, K){ // Store the required subarrays let solution = []; // Stores the product of // current subarray let multi = 1; // Stores the starting index // of the current subarray let start = 0; // Check for empty array if (n <= 1 || K < 0) { return solution; } // Iterate over the array for(let i = 0; i < n; i++) { // Calculate product multi = multi * arr[i]; // If product exceeds K while (multi > K) { // Reduce product multi =Math.floor( multi / arr[start]); // Increase starting index // of current subarray start++; } // Stores the subarray elements let list = []; // Store the subarray elements for(let j = i; j >= start; j--) { list.unshift(arr[j]); // Add the subarrays // to the list solution.push(list); } } // Return the final // list of subarrays return solution;} // Driver Code let arr = [ 2, 7, 1, 4 ]; let n = arr.length; let K = 7; let v = maxSubArray(arr, n, K); document.write( \"[\"); let first = true; for(let x=0;x< v.length;x++) { if (!first) { document.write(\", \"); } else { first = false; } document.write( \"[\"); let ff = true; for(let y =0;y<v[x].length;y++) { if (!ff) { document.write(\", \"); } else { ff = false; } document.write(v[x][y]); } document.write(\"]\"); } document.write( \"]\"); </script>", "e": 37010, "s": 35034, "text": null }, { "code": null, "e": 37047, "s": 37010, "text": "[[2], [7], [1], [7, 1], [4], [1, 4]]" }, { "code": null, "e": 37093, "s": 37049, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 37107, "s": 37095, "text": "29AjayKumar" }, { "code": null, "e": 37117, "s": 37107, "text": "rutvik_56" }, { "code": null, "e": 37127, "s": 37117, "text": "pratham76" }, { "code": null, "e": 37143, "s": 37127, "text": "rohitsingh07052" }, { "code": null, "e": 37158, "s": 37143, "text": "Java-ArrayList" }, { "code": null, "e": 37167, "s": 37158, "text": "subarray" }, { "code": null, "e": 37174, "s": 37167, "text": "Arrays" }, { "code": null, "e": 37187, "s": 37174, "text": "Mathematical" }, { "code": null, "e": 37197, "s": 37187, "text": "Searching" }, { "code": null, "e": 37204, "s": 37197, "text": "Arrays" }, { "code": null, "e": 37214, "s": 37204, "text": "Searching" }, { "code": null, "e": 37227, "s": 37214, "text": "Mathematical" }, { "code": null, "e": 37325, "s": 37227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37352, "s": 37325, "text": "Count pairs with given sum" }, { "code": null, "e": 37383, "s": 37352, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 37408, "s": 37383, "text": "Window Sliding Technique" }, { "code": null, "e": 37446, "s": 37408, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 37467, "s": 37446, "text": "Next Greater Element" }, { "code": null, "e": 37497, "s": 37467, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37557, "s": 37497, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37572, "s": 37557, "text": "C++ Data Types" }, { "code": null, "e": 37615, "s": 37572, "text": "Set in C++ Standard Template Library (STL)" } ]
HTTP headers | expires - GeeksforGeeks
19 Nov, 2019 The HTTP Expires header is a response-type header, the fundamental way of controlling the caches present. The expire header contains the date and time which denotes the period where the object can stay alive. Once the period expires, the object becomes stale. Almost every client support expire headers. The expire headers are usually ignored if a cache-control header is present with a max-age directive. The users need not press the reload button in order to get a live object. Once the time expires the caches take control over the pages. Web servers allow clients to set the expire headers in multiple ways. The two most common ways may include: Last access time: It sets the expire time-based on the final time the client accessed the object. Last modification time: It denotes the last time the document was changed on the server. Syntax: Expires: <http-date> Directives: The HTTP Expires header accepts a single directive mentioned above and described below: <http-date>: This directive contains the date time information of the retirement. Below example will illustrate the HTTP Expires header: Example: In this example, the object is set with an expiry date and time. It will enable the caches to know when to get a fresh copy of the object. The users need not press the reload button in order to get a live object. Once the time expires the caches take control over the pages. Expires: Mon,11 Nov 2019 08:36:00 GMT To check this Expires in action go to Inspect Element -> Network check the response header for Expires like below, Expires is highlighted you can see.Note: The time denoted in HTTP date should always hold Greenwich Meridian Time(GMT) and not local time. Supported Browsers: The browsers are compatible with HTTP Expires header are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked 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 How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method File uploading in React.js How to apply style to parent if it has child with CSS? How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 25943, "s": 25915, "text": "\n19 Nov, 2019" }, { "code": null, "e": 26593, "s": 25943, "text": "The HTTP Expires header is a response-type header, the fundamental way of controlling the caches present. The expire header contains the date and time which denotes the period where the object can stay alive. Once the period expires, the object becomes stale. Almost every client support expire headers. The expire headers are usually ignored if a cache-control header is present with a max-age directive. The users need not press the reload button in order to get a live object. Once the time expires the caches take control over the pages. Web servers allow clients to set the expire headers in multiple ways. The two most common ways may include:" }, { "code": null, "e": 26691, "s": 26593, "text": "Last access time: It sets the expire time-based on the final time the client accessed the object." }, { "code": null, "e": 26780, "s": 26691, "text": "Last modification time: It denotes the last time the document was changed on the server." }, { "code": null, "e": 26788, "s": 26780, "text": "Syntax:" }, { "code": null, "e": 26809, "s": 26788, "text": "Expires: <http-date>" }, { "code": null, "e": 26909, "s": 26809, "text": "Directives: The HTTP Expires header accepts a single directive mentioned above and described below:" }, { "code": null, "e": 26991, "s": 26909, "text": "<http-date>: This directive contains the date time information of the retirement." }, { "code": null, "e": 27046, "s": 26991, "text": "Below example will illustrate the HTTP Expires header:" }, { "code": null, "e": 27330, "s": 27046, "text": "Example: In this example, the object is set with an expiry date and time. It will enable the caches to know when to get a fresh copy of the object. The users need not press the reload button in order to get a live object. Once the time expires the caches take control over the pages." }, { "code": null, "e": 27368, "s": 27330, "text": "Expires: Mon,11 Nov 2019 08:36:00 GMT" }, { "code": null, "e": 27622, "s": 27368, "text": "To check this Expires in action go to Inspect Element -> Network check the response header for Expires like below, Expires is highlighted you can see.Note: The time denoted in HTTP date should always hold Greenwich Meridian Time(GMT) and not local time." }, { "code": null, "e": 27713, "s": 27622, "text": "Supported Browsers: The browsers are compatible with HTTP Expires header are listed below:" }, { "code": null, "e": 27727, "s": 27713, "text": "Google Chrome" }, { "code": null, "e": 27745, "s": 27727, "text": "Internet Explorer" }, { "code": null, "e": 27753, "s": 27745, "text": "Firefox" }, { "code": null, "e": 27760, "s": 27753, "text": "Safari" }, { "code": null, "e": 27766, "s": 27760, "text": "Opera" }, { "code": null, "e": 27779, "s": 27766, "text": "HTTP-headers" }, { "code": null, "e": 27786, "s": 27779, "text": "Picked" }, { "code": null, "e": 27803, "s": 27786, "text": "Web Technologies" }, { "code": null, "e": 27901, "s": 27803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27941, "s": 27901, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27986, "s": 27941, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28029, "s": 27986, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28090, "s": 28029, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28148, "s": 28090, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28220, "s": 28148, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28253, "s": 28220, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28280, "s": 28253, "text": "File uploading in React.js" }, { "code": null, "e": 28335, "s": 28280, "text": "How to apply style to parent if it has child with CSS?" } ]
str() vs repr() in Python - GeeksforGeeks
25 Nov, 2020 str() and repr() both are used to get a string representation of object. Example of str():s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0))Output:Hello, Geeks. 0.181818181818.Example of repr():s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0))Output:'Hello, Geeks.' 0.18181818181818182 Example of str():s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0))Output:Hello, Geeks. 0.181818181818. s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0)) Output: Hello, Geeks. 0.181818181818 . Example of repr():s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0))Output:'Hello, Geeks.' 0.18181818181818182 s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0)) Output: 'Hello, Geeks.' 0.18181818181818182 From above output, we can see if we print string using repr() function then it prints with a pair of quotes and if we calculate a value we get more precise value than str() function. Following are differences: str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not. repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object). The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object. Let understand this by an example:- import datetimetoday = datetime.datetime.now() # Prints readable format for date-time objectprint (str(today)) # prints the official format of date-time objectprint (repr(today)) Output: 2016-02-22 19:32:04.078030 datetime.datetime(2016, 2, 22, 19, 32, 4, 78030) str() displays today’s date in a way that the user can understand the date and time. repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object). How to make them work for our own defined classes?A user defined class should also have a __repr__ if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__ function. # Python program to demonstrate writing of __repr__ and# __str__ for user defined classes # A user defined class to represent Complex numbersclass Complex: # Constructor def __init__(self, real, imag): self.real = real self.imag = imag # For call to repr(). Prints object's information def __repr__(self): return 'Rational(%s, %s)' % (self.real, self.imag) # For call to str(). Prints readable form def __str__(self): return '%s + i%s' % (self.real, self.imag) # Driver program to test abovet = Complex(10, 20) # Same as "print t"print (str(t)) print (repr(t)) Output: 10 + i20 Rational(10, 20) This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rajivsarkar67 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25465, "s": 25437, "text": "\n25 Nov, 2020" }, { "code": null, "e": 25538, "s": 25465, "text": "str() and repr() both are used to get a string representation of object." }, { "code": null, "e": 25762, "s": 25538, "text": "Example of str():s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0))Output:Hello, Geeks.\n0.181818181818.Example of repr():s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0))Output:'Hello, Geeks.'\n0.18181818181818182" }, { "code": null, "e": 25870, "s": 25762, "text": "Example of str():s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0))Output:Hello, Geeks.\n0.181818181818." }, { "code": "s = 'Hello, Geeks.'print (str(s))print (str(2.0/11.0))", "e": 25925, "s": 25870, "text": null }, { "code": null, "e": 25933, "s": 25925, "text": "Output:" }, { "code": null, "e": 25962, "s": 25933, "text": "Hello, Geeks.\n0.181818181818" }, { "code": null, "e": 25964, "s": 25962, "text": "." }, { "code": null, "e": 26081, "s": 25964, "text": "Example of repr():s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0))Output:'Hello, Geeks.'\n0.18181818181818182" }, { "code": "s = 'Hello, Geeks.'print (repr(s))print (repr(2.0/11.0))", "e": 26138, "s": 26081, "text": null }, { "code": null, "e": 26146, "s": 26138, "text": "Output:" }, { "code": null, "e": 26182, "s": 26146, "text": "'Hello, Geeks.'\n0.18181818181818182" }, { "code": null, "e": 26365, "s": 26182, "text": "From above output, we can see if we print string using repr() function then it prints with a pair of quotes and if we calculate a value we get more precise value than str() function." }, { "code": null, "e": 26392, "s": 26365, "text": "Following are differences:" }, { "code": null, "e": 26660, "s": 26392, "text": "str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not." }, { "code": null, "e": 26924, "s": 26660, "text": "repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object)." }, { "code": null, "e": 27108, "s": 26924, "text": "The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object." }, { "code": null, "e": 27144, "s": 27108, "text": "Let understand this by an example:-" }, { "code": "import datetimetoday = datetime.datetime.now() # Prints readable format for date-time objectprint (str(today)) # prints the official format of date-time objectprint (repr(today)) ", "e": 27330, "s": 27144, "text": null }, { "code": null, "e": 27338, "s": 27330, "text": "Output:" }, { "code": null, "e": 27415, "s": 27338, "text": "2016-02-22 19:32:04.078030\ndatetime.datetime(2016, 2, 22, 19, 32, 4, 78030)\n" }, { "code": null, "e": 27500, "s": 27415, "text": "str() displays today’s date in a way that the user can understand the date and time." }, { "code": null, "e": 27644, "s": 27500, "text": "repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object)." }, { "code": null, "e": 27891, "s": 27644, "text": "How to make them work for our own defined classes?A user defined class should also have a __repr__ if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__ function." }, { "code": "# Python program to demonstrate writing of __repr__ and# __str__ for user defined classes # A user defined class to represent Complex numbersclass Complex: # Constructor def __init__(self, real, imag): self.real = real self.imag = imag # For call to repr(). Prints object's information def __repr__(self): return 'Rational(%s, %s)' % (self.real, self.imag) # For call to str(). Prints readable form def __str__(self): return '%s + i%s' % (self.real, self.imag) # Driver program to test abovet = Complex(10, 20) # Same as \"print t\"print (str(t)) print (repr(t))", "e": 28514, "s": 27891, "text": null }, { "code": null, "e": 28522, "s": 28514, "text": "Output:" }, { "code": null, "e": 28548, "s": 28522, "text": "10 + i20\nRational(10, 20)" }, { "code": null, "e": 28815, "s": 28548, "text": "This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28939, "s": 28815, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 28953, "s": 28939, "text": "rajivsarkar67" }, { "code": null, "e": 28960, "s": 28953, "text": "Python" }, { "code": null, "e": 29058, "s": 28960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29076, "s": 29058, "text": "Python Dictionary" }, { "code": null, "e": 29111, "s": 29076, "text": "Read a file line by line in Python" }, { "code": null, "e": 29143, "s": 29111, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29165, "s": 29143, "text": "Enumerate() in Python" }, { "code": null, "e": 29207, "s": 29165, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29237, "s": 29207, "text": "Iterate over a list in Python" }, { "code": null, "e": 29263, "s": 29237, "text": "Python String | replace()" }, { "code": null, "e": 29292, "s": 29263, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29336, "s": 29292, "text": "Reading and Writing to text files in Python" } ]
Append digits to the end of duplicate strings to make all strings in an array unique - GeeksforGeeks
04 Aug, 2021 Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending ay number such that all the strings in the array are unique. Examples: Input: S = {“aa”, “bb”, “cc”, “bb”, “aa”, “aa”, “aa”}Output: {“aa”, “bb”, “cc”, “bb1”, “aa1”, “aa2”, “aa3”}Explanation:The output of the second occurrence of “bb” is “bb1” The output of the second occurrence of “aa” is “aa1” The output of the third occurrence of “aa” is “aa2” The output of the fourth occurrence of “aa” is “aa3” Input: S = {“aa”, “bb”, “cc”, “aa”}Output: {“aa”, “bb”, “cc”, “aa1”} Approach: The idea is to traverse the array and store the frequency of each string in arr[] in a Hashmap. While storing the frequency, if the string has no previous occurrences, then leave the string unchanged. Otherwise, append its frequency at the end. Finally, print all the unique strings present in the array arr[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquevoid replaceDuplicates( vector<string>& names){ // Store the frequency of strings unordered_map<string, int> hash; // Iterate over the array for (int i = 0; i < names.size(); i++) { // For the first occurrence, // update the frequency count if (hash.count(names[i]) == 0) hash[names[i]]++; // Otherwise else { int count = hash[names[i]]++; // Append frequency count // to end of the string names[i] += to_string(count); } } // Print the modified array for (int i = 0; i < names.size(); i++) { cout << names[i] << " "; }} // Driver Codeint main(){ vector<string> str = { "aa", "bb", "cc", "bb", "aa", "aa", "aa" }; // Function Call replaceDuplicates(str); return 0;} // Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(String[] names){ // Store the frequency of strings HashMap<String, Integer> hash = new HashMap<>(); // Iterate over the array for(int i = 0; i < names.length; i++) { // For the first occurrence, // update the frequency count if (!hash.containsKey(names[i])) hash.put(names[i], 1); // Otherwise else { int count = hash.get(names[i]); hash.put(names[i], hash.get(names[i]) + 1); // Append frequency count // to end of the string names[i] += Integer.toString(count); } } // Print the modified array for(int i = 0; i < names.length; i++) { System.out.print(names[i] + ' '); }} // Driver Codepublic static void main(String[] args){ String[] str = { "aa", "bb", "cc", "bb", "aa", "aa", "aa" }; // Function Call replaceDuplicates(str);}} // This code is contributed by akhilsaini # Python3 program for the above approach # Function to replace duplicate strings# by alphanumeric strings to make all# strings in the array uniquedef replaceDuplicates(names): # Store the frequency of strings hash = {} # Iterate over the array for i in range(0, len(names)): # For the first occurrence, # update the frequency count if names[i] not in hash: hash[names[i]] = 1 # Otherwise else: count = hash[names[i]] hash[names[i]] += 1 # Append frequency count # to end of the string names[i] += str(count) # Print the modified array for i in range(0, len(names)): print(names[i], end = ' ') # Driver Codeif __name__ == '__main__': str1 = [ "aa", "bb", "cc", "bb", "aa", "aa", "aa" ] # Function Call replaceDuplicates(str1) # This code is contributed by akhilsaini // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(string[] names){ // Store the frequency of strings Dictionary<string, int> hash = new Dictionary<string, int>(); // Iterate over the array for(int i = 0; i < names.Length; i++) { // For the first occurrence, // update the frequency count if (!hash.ContainsKey(names[i])) hash[names[i]] = 1; // Otherwise else { int count = hash[names[i]]; hash[names[i]] += 1; // Append frequency count // to end of the string names[i] += count.ToString(); } } // Print the modified array for(int i = 0; i < names.Length; i++) { Console.Write(names[i] + ' '); }} // Driver Codepublic static void Main(){ string[] str = { "aa", "bb", "cc", "bb", "aa", "aa", "aa" }; // Function Call replaceDuplicates(str);}} // This code is contributed by akhilsaini <script> // Javascript program for the above approach // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquefunction replaceDuplicates( names){ // Store the frequency of strings var hash = new Map(); // Iterate over the array for (var i = 0; i < names.length; i++) { // For the first occurrence, // update the frequency count if (!hash.has(names[i])) hash.set(names[i],1); // Otherwise else { var count = hash.get(names[i]); hash.set(names[i],hash.get(names[i])+1); // Append frequency count // to end of the string names[i] += count.toString(); } } // Print the modified array for (var i = 0; i < names.length; i++) { document.write( names[i] + " "); }} // Driver Codevar str = [ "aa", "bb", "cc", "bb", "aa", "aa", "aa" ];// Function CallreplaceDuplicates(str); </script> aa bb cc bb1 aa1 aa2 aa3 Time Complexity: O(N)Auxiliary Space: O(N) akhilsaini rrrtnx simmytarika5 arorakashish0911 cpp-unordered_map frequency-counting HashTable Technical Scripter 2020 Arrays Hash Searching Strings Technical Scripter Arrays Searching Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26033, "s": 26005, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26220, "s": 26033, "text": "Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending ay number such that all the strings in the array are unique." }, { "code": null, "e": 26230, "s": 26220, "text": "Examples:" }, { "code": null, "e": 26560, "s": 26230, "text": "Input: S = {“aa”, “bb”, “cc”, “bb”, “aa”, “aa”, “aa”}Output: {“aa”, “bb”, “cc”, “bb1”, “aa1”, “aa2”, “aa3”}Explanation:The output of the second occurrence of “bb” is “bb1” The output of the second occurrence of “aa” is “aa1” The output of the third occurrence of “aa” is “aa2” The output of the fourth occurrence of “aa” is “aa3”" }, { "code": null, "e": 26629, "s": 26560, "text": "Input: S = {“aa”, “bb”, “cc”, “aa”}Output: {“aa”, “bb”, “cc”, “aa1”}" }, { "code": null, "e": 26950, "s": 26629, "text": "Approach: The idea is to traverse the array and store the frequency of each string in arr[] in a Hashmap. While storing the frequency, if the string has no previous occurrences, then leave the string unchanged. Otherwise, append its frequency at the end. Finally, print all the unique strings present in the array arr[]." }, { "code": null, "e": 27001, "s": 26950, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27005, "s": 27001, "text": "C++" }, { "code": null, "e": 27010, "s": 27005, "text": "Java" }, { "code": null, "e": 27018, "s": 27010, "text": "Python3" }, { "code": null, "e": 27021, "s": 27018, "text": "C#" }, { "code": null, "e": 27032, "s": 27021, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquevoid replaceDuplicates( vector<string>& names){ // Store the frequency of strings unordered_map<string, int> hash; // Iterate over the array for (int i = 0; i < names.size(); i++) { // For the first occurrence, // update the frequency count if (hash.count(names[i]) == 0) hash[names[i]]++; // Otherwise else { int count = hash[names[i]]++; // Append frequency count // to end of the string names[i] += to_string(count); } } // Print the modified array for (int i = 0; i < names.size(); i++) { cout << names[i] << \" \"; }} // Driver Codeint main(){ vector<string> str = { \"aa\", \"bb\", \"cc\", \"bb\", \"aa\", \"aa\", \"aa\" }; // Function Call replaceDuplicates(str); return 0;}", "e": 28073, "s": 27032, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(String[] names){ // Store the frequency of strings HashMap<String, Integer> hash = new HashMap<>(); // Iterate over the array for(int i = 0; i < names.length; i++) { // For the first occurrence, // update the frequency count if (!hash.containsKey(names[i])) hash.put(names[i], 1); // Otherwise else { int count = hash.get(names[i]); hash.put(names[i], hash.get(names[i]) + 1); // Append frequency count // to end of the string names[i] += Integer.toString(count); } } // Print the modified array for(int i = 0; i < names.length; i++) { System.out.print(names[i] + ' '); }} // Driver Codepublic static void main(String[] args){ String[] str = { \"aa\", \"bb\", \"cc\", \"bb\", \"aa\", \"aa\", \"aa\" }; // Function Call replaceDuplicates(str);}} // This code is contributed by akhilsaini", "e": 29270, "s": 28073, "text": null }, { "code": "# Python3 program for the above approach # Function to replace duplicate strings# by alphanumeric strings to make all# strings in the array uniquedef replaceDuplicates(names): # Store the frequency of strings hash = {} # Iterate over the array for i in range(0, len(names)): # For the first occurrence, # update the frequency count if names[i] not in hash: hash[names[i]] = 1 # Otherwise else: count = hash[names[i]] hash[names[i]] += 1 # Append frequency count # to end of the string names[i] += str(count) # Print the modified array for i in range(0, len(names)): print(names[i], end = ' ') # Driver Codeif __name__ == '__main__': str1 = [ \"aa\", \"bb\", \"cc\", \"bb\", \"aa\", \"aa\", \"aa\" ] # Function Call replaceDuplicates(str1) # This code is contributed by akhilsaini", "e": 30207, "s": 29270, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(string[] names){ // Store the frequency of strings Dictionary<string, int> hash = new Dictionary<string, int>(); // Iterate over the array for(int i = 0; i < names.Length; i++) { // For the first occurrence, // update the frequency count if (!hash.ContainsKey(names[i])) hash[names[i]] = 1; // Otherwise else { int count = hash[names[i]]; hash[names[i]] += 1; // Append frequency count // to end of the string names[i] += count.ToString(); } } // Print the modified array for(int i = 0; i < names.Length; i++) { Console.Write(names[i] + ' '); }} // Driver Codepublic static void Main(){ string[] str = { \"aa\", \"bb\", \"cc\", \"bb\", \"aa\", \"aa\", \"aa\" }; // Function Call replaceDuplicates(str);}} // This code is contributed by akhilsaini", "e": 31469, "s": 30207, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquefunction replaceDuplicates( names){ // Store the frequency of strings var hash = new Map(); // Iterate over the array for (var i = 0; i < names.length; i++) { // For the first occurrence, // update the frequency count if (!hash.has(names[i])) hash.set(names[i],1); // Otherwise else { var count = hash.get(names[i]); hash.set(names[i],hash.get(names[i])+1); // Append frequency count // to end of the string names[i] += count.toString(); } } // Print the modified array for (var i = 0; i < names.length; i++) { document.write( names[i] + \" \"); }} // Driver Codevar str = [ \"aa\", \"bb\", \"cc\", \"bb\", \"aa\", \"aa\", \"aa\" ];// Function CallreplaceDuplicates(str); </script>", "e": 32467, "s": 31469, "text": null }, { "code": null, "e": 32492, "s": 32467, "text": "aa bb cc bb1 aa1 aa2 aa3" }, { "code": null, "e": 32537, "s": 32494, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 32548, "s": 32537, "text": "akhilsaini" }, { "code": null, "e": 32555, "s": 32548, "text": "rrrtnx" }, { "code": null, "e": 32568, "s": 32555, "text": "simmytarika5" }, { "code": null, "e": 32585, "s": 32568, "text": "arorakashish0911" }, { "code": null, "e": 32603, "s": 32585, "text": "cpp-unordered_map" }, { "code": null, "e": 32622, "s": 32603, "text": "frequency-counting" }, { "code": null, "e": 32632, "s": 32622, "text": "HashTable" }, { "code": null, "e": 32656, "s": 32632, "text": "Technical Scripter 2020" }, { "code": null, "e": 32663, "s": 32656, "text": "Arrays" }, { "code": null, "e": 32668, "s": 32663, "text": "Hash" }, { "code": null, "e": 32678, "s": 32668, "text": "Searching" }, { "code": null, "e": 32686, "s": 32678, "text": "Strings" }, { "code": null, "e": 32705, "s": 32686, "text": "Technical Scripter" }, { "code": null, "e": 32712, "s": 32705, "text": "Arrays" }, { "code": null, "e": 32722, "s": 32712, "text": "Searching" }, { "code": null, "e": 32727, "s": 32722, "text": "Hash" }, { "code": null, "e": 32735, "s": 32727, "text": "Strings" }, { "code": null, "e": 32833, "s": 32735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32901, "s": 32833, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32945, "s": 32901, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32993, "s": 32945, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33016, "s": 32993, "text": "Introduction to Arrays" }, { "code": null, "e": 33048, "s": 33016, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33133, "s": 33048, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33169, "s": 33133, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33196, "s": 33169, "text": "Count pairs with given sum" }, { "code": null, "e": 33227, "s": 33196, "text": "Hashing | Set 1 (Introduction)" } ]
Bash Script to get Low Battery Alert in Linux - GeeksforGeeks
31 Jan, 2021 We are going to write a bash script that will speak “Battery Low” when the battery’s charging percentage will go below some specified threshold value. Before starting this, first, we need to understand some basic commands and terminology which are described below:Some Bash Commands: acpi: This command returns the percentage of battery charged, whether the device is charging or discharging and the amount of time left before the battery fully discharges. Example: acpi -b produces the following output: Battery 0: Discharging, 13%, 00:52:52 remaining Here, Battery 0 means it is not charging and Battery 1 means it is charging. 13% is the Percentage of Battery Charged. 00:52:52 is the time left before it Hibernates. notify-send: This command is used to alert the notification popups in Linux. We will have the alert of the battery charging/discharging warning with this command. Required Package: espeak command speaks or narrates whatever parameter you pass with it e.g it will speak out “demo espeak” if you run espeak “demo espeak”. Espeak can be installed like any normal package: sudo apt install espeak Required Linux Filters: grep: The grep filter is used to search for some specified string in a given file. cut: The cut filter allows us to cut and strip the desired section of text file before the standard output. sed: It stands for stream editor. This filter is used to make insertion, deletion, search, and replacement. We are using sed here for replacing the “%” sign by “”. Python3 #!/bin/bash # echo "Saurav Chaudhary Gujjar"battery_level =$(acpi - b | grep - P - o '[0-9]+(?=%)') # Battery 0: Discharging, 13%, 00:52:52 remaining# To get the battery percentage only we'll cut the# second value which ends at ", ". So we get 13%# Now we'll replace the % sign by "", so 13% will# be changed to 13 now.# acpi -b produces output as# echo $battery_level #$battery_level=13 # If the charger is plugged in, acpi shows "charging"# and if it's not plugged in, it shows "discharging".# if acpi -b shows charging, "grep -c" will return 1# else it will return 0ac_power =$(acpi - b | grep - c "Charging")# echo $ac_power #1 if charging(plugged in) and 0 if discharging (not plugged in)# checks if ac_power is ON and battery is fullbattery_full =$(acpi - b | grep - c "Full")# echo $battery_full # when the battery is charging and it gets charged up to 100%# echo $battery_level# if charging and battery_level==100if [[$ac_power - eq 1 & & $battery_level - eq 100]] | | [$battery_full - eq 1]thenexport DISPLAY = : 0.0 & &sudo - u saurav DISPLAY = : 0 DBUS_SESSION_BUS_ADDRESS = unix: path = /run/user/1000/bus notify-send - u critical "Saurav, Battery is full" "Level: $battery_level% "# it notifies Battery is full and shows the battery# full image which is stored in /usr/local/bin directory # so, it will narrate, please remove the# charger. It's charged up to 100%.espeak "Saurav, Battrey is full, Please Remove the charger" - s 140 fi# when the battery is not charging# and it goes below 30% if [[$ac_power - eq 0 & & $battery_level - lt 30]]then export DISPLAY = : 0.0 & &sudo - u saurav DISPLAY =: 0 DBUS_SESSION_BUS_ADDRESS = unix: path = /run/user/1000/bus notify-send - u critical "Saurav Gujjar, Battery is Low." "Level: $battery_level% " # similarily, it narrates#"please connect the charger"espeak "Saurav, Battery is Low, Please connect the charger" - s 140 fi saurabhpanwar127 Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples How to Find the Wi-Fi Password Using CMD in Windows? Top Programming Languages for Android App Development Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker?
[ { "code": null, "e": 25677, "s": 25649, "text": "\n31 Jan, 2021" }, { "code": null, "e": 25963, "s": 25677, "text": "We are going to write a bash script that will speak “Battery Low” when the battery’s charging percentage will go below some specified threshold value. Before starting this, first, we need to understand some basic commands and terminology which are described below:Some Bash Commands: " }, { "code": null, "e": 26137, "s": 25963, "text": "acpi: This command returns the percentage of battery charged, whether the device is charging or discharging and the amount of time left before the battery fully discharges. " }, { "code": null, "e": 26186, "s": 26137, "text": "Example: acpi -b produces the following output: " }, { "code": null, "e": 26235, "s": 26186, "text": "Battery 0: Discharging, 13%, 00:52:52 remaining\n" }, { "code": null, "e": 26402, "s": 26235, "text": "Here, Battery 0 means it is not charging and Battery 1 means it is charging. 13% is the Percentage of Battery Charged. 00:52:52 is the time left before it Hibernates." }, { "code": null, "e": 26566, "s": 26402, "text": "notify-send: This command is used to alert the notification popups in Linux. We will have the alert of the battery charging/discharging warning with this command. " }, { "code": null, "e": 26773, "s": 26566, "text": "Required Package: espeak command speaks or narrates whatever parameter you pass with it e.g it will speak out “demo espeak” if you run espeak “demo espeak”. Espeak can be installed like any normal package: " }, { "code": null, "e": 26798, "s": 26773, "text": "sudo apt install espeak\n" }, { "code": null, "e": 26824, "s": 26798, "text": "Required Linux Filters: " }, { "code": null, "e": 26907, "s": 26824, "text": "grep: The grep filter is used to search for some specified string in a given file." }, { "code": null, "e": 27015, "s": 26907, "text": "cut: The cut filter allows us to cut and strip the desired section of text file before the standard output." }, { "code": null, "e": 27179, "s": 27015, "text": "sed: It stands for stream editor. This filter is used to make insertion, deletion, search, and replacement. We are using sed here for replacing the “%” sign by “”." }, { "code": null, "e": 27187, "s": 27179, "text": "Python3" }, { "code": "#!/bin/bash # echo \"Saurav Chaudhary Gujjar\"battery_level =$(acpi - b | grep - P - o '[0-9]+(?=%)') # Battery 0: Discharging, 13%, 00:52:52 remaining# To get the battery percentage only we'll cut the# second value which ends at \", \". So we get 13%# Now we'll replace the % sign by \"\", so 13% will# be changed to 13 now.# acpi -b produces output as# echo $battery_level #$battery_level=13 # If the charger is plugged in, acpi shows \"charging\"# and if it's not plugged in, it shows \"discharging\".# if acpi -b shows charging, \"grep -c\" will return 1# else it will return 0ac_power =$(acpi - b | grep - c \"Charging\")# echo $ac_power #1 if charging(plugged in) and 0 if discharging (not plugged in)# checks if ac_power is ON and battery is fullbattery_full =$(acpi - b | grep - c \"Full\")# echo $battery_full # when the battery is charging and it gets charged up to 100%# echo $battery_level# if charging and battery_level==100if [[$ac_power - eq 1 & & $battery_level - eq 100]] | | [$battery_full - eq 1]thenexport DISPLAY = : 0.0 & &sudo - u saurav DISPLAY = : 0 DBUS_SESSION_BUS_ADDRESS = unix: path = /run/user/1000/bus notify-send - u critical \"Saurav, Battery is full\" \"Level: $battery_level% \"# it notifies Battery is full and shows the battery# full image which is stored in /usr/local/bin directory # so, it will narrate, please remove the# charger. It's charged up to 100%.espeak \"Saurav, Battrey is full, Please Remove the charger\" - s 140 fi# when the battery is not charging# and it goes below 30% if [[$ac_power - eq 0 & & $battery_level - lt 30]]then export DISPLAY = : 0.0 & &sudo - u saurav DISPLAY =: 0 DBUS_SESSION_BUS_ADDRESS = unix: path = /run/user/1000/bus notify-send - u critical \"Saurav Gujjar, Battery is Low.\" \"Level: $battery_level% \" # similarily, it narrates#\"please connect the charger\"espeak \"Saurav, Battery is Low, Please connect the charger\" - s 140 fi", "e": 29084, "s": 27187, "text": null }, { "code": null, "e": 29101, "s": 29084, "text": "saurabhpanwar127" }, { "code": null, "e": 29112, "s": 29101, "text": "Linux-Unix" }, { "code": null, "e": 29121, "s": 29112, "text": "TechTips" }, { "code": null, "e": 29219, "s": 29121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29254, "s": 29219, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29288, "s": 29254, "text": "mv command in Linux with examples" }, { "code": null, "e": 29314, "s": 29288, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29343, "s": 29314, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29380, "s": 29343, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29433, "s": 29380, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 29487, "s": 29433, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 29513, "s": 29487, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29548, "s": 29513, "text": "Setting up the environment in Java" } ]
Find the largest number that can be formed by changing at most K digits - GeeksforGeeks
13 Mar, 2022 Given string str representing a number and an integer K, the task is to find the largest number that can be formed by changing at most K digits in the given number. Examples: Input: str = “569431”, K = 3 Output: 999931 Replace first, second and fourth digits with 9.Input: str = “5687”, K = 2 Output: 9987 Approach: In order to get the maximum number possible, leftmost digits must be replaced with 9s. For every digit of the number starting from the leftmost digit, if it is not already 9 and K is greater than 0 then replace it with 9 and decrement K by 1. Repeat these steps for every digit while K is greater than 0. Finally, print the updated number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the maximum number// that can be formed by changing// at most k digits in strstring findMaximumNum(string str, int n, int k){ // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] != '9') { // Replace it with 9 str[i] = '9'; // One digit has been used k--; } } return str;} // Driver codeint main(){ string str = "569431"; int n = str.length(); int k = 3; cout << findMaximumNum(str, n, k); return 0;} // Java implementation of the approachclass GFG{ // Function to return the maximum number // that can be formed by changing // at most k digits in str static StringBuilder findMaximumNum(StringBuilder str, int n, int k) { // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str.charAt(i) != '9') { // Replace it with 9 str.setCharAt(i, '9'); // One digit has been used k--; } } return str; } // Driver code public static void main (String [] args) { StringBuilder str = new StringBuilder("569431"); int n = str.length(); int k = 3; System.out.println(findMaximumNum(str, n, k)); }} // This code is contributed by ihritik # Python3 implementation of the approach # Function to return the maximum number# that can be formed by changing# at most k digits in strdef findMaximumNum(st, n, k): # For every digit of the number for i in range(n): # If no more digits can be replaced if (k < 1): break # If current digit is not already 9 if (st[i] != '9'): # Replace it with 9 st = st[0:i] + '9' + st[i + 1:] # One digit has been used k -= 1 return st # Driver codest = "569431"n = len(st)k = 3print(findMaximumNum(st, n, k)) # This code is contributed by# divyamohan123 // C# implementation of the approachusing System;using System.Text; class GFG{ // Function to return the maximum number // that can be formed by changing // at most k digits in str static StringBuilder findMaximumNum(StringBuilder str, int n, int k) { // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] != '9') { // Replace it with 9 str[i] = '9'; // One digit has been used k--; } } return str; } // Driver code public static void Main () { StringBuilder str = new StringBuilder("569431"); int n = str.Length; int k = 3; Console.WriteLine(findMaximumNum(str, n, k)); }} // This code is contributed by ihritik <script> // JavaScript implementation of the approach // Function to return the maximum number // that can be formed by changing // at most k digits in str function findMaximumNum(str, n, k) { // For every digit of the number for (var i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] !== "9") { // Replace it with 9 str[i] = "9"; // One digit has been used k--; } } return str.join(""); } // Driver code var str = "569431"; var n = str.length; var k = 3; document.write(findMaximumNum(str.split(""), n, k)); </script> 999931 Time Complexity: O(n) Auxiliary Space: O(1) ihritik divyamohan123 rdtank subhammahato348 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 26285, "s": 26257, "text": "\n13 Mar, 2022" }, { "code": null, "e": 26450, "s": 26285, "text": "Given string str representing a number and an integer K, the task is to find the largest number that can be formed by changing at most K digits in the given number." }, { "code": null, "e": 26461, "s": 26450, "text": "Examples: " }, { "code": null, "e": 26594, "s": 26461, "text": "Input: str = “569431”, K = 3 Output: 999931 Replace first, second and fourth digits with 9.Input: str = “5687”, K = 2 Output: 9987 " }, { "code": null, "e": 26944, "s": 26594, "text": "Approach: In order to get the maximum number possible, leftmost digits must be replaced with 9s. For every digit of the number starting from the leftmost digit, if it is not already 9 and K is greater than 0 then replace it with 9 and decrement K by 1. Repeat these steps for every digit while K is greater than 0. Finally, print the updated number." }, { "code": null, "e": 26997, "s": 26944, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27001, "s": 26997, "text": "C++" }, { "code": null, "e": 27006, "s": 27001, "text": "Java" }, { "code": null, "e": 27014, "s": 27006, "text": "Python3" }, { "code": null, "e": 27017, "s": 27014, "text": "C#" }, { "code": null, "e": 27028, "s": 27017, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the maximum number// that can be formed by changing// at most k digits in strstring findMaximumNum(string str, int n, int k){ // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] != '9') { // Replace it with 9 str[i] = '9'; // One digit has been used k--; } } return str;} // Driver codeint main(){ string str = \"569431\"; int n = str.length(); int k = 3; cout << findMaximumNum(str, n, k); return 0;}", "e": 27766, "s": 27028, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum number // that can be formed by changing // at most k digits in str static StringBuilder findMaximumNum(StringBuilder str, int n, int k) { // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str.charAt(i) != '9') { // Replace it with 9 str.setCharAt(i, '9'); // One digit has been used k--; } } return str; } // Driver code public static void main (String [] args) { StringBuilder str = new StringBuilder(\"569431\"); int n = str.length(); int k = 3; System.out.println(findMaximumNum(str, n, k)); }} // This code is contributed by ihritik", "e": 28816, "s": 27766, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum number# that can be formed by changing# at most k digits in strdef findMaximumNum(st, n, k): # For every digit of the number for i in range(n): # If no more digits can be replaced if (k < 1): break # If current digit is not already 9 if (st[i] != '9'): # Replace it with 9 st = st[0:i] + '9' + st[i + 1:] # One digit has been used k -= 1 return st # Driver codest = \"569431\"n = len(st)k = 3print(findMaximumNum(st, n, k)) # This code is contributed by# divyamohan123", "e": 29455, "s": 28816, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Text; class GFG{ // Function to return the maximum number // that can be formed by changing // at most k digits in str static StringBuilder findMaximumNum(StringBuilder str, int n, int k) { // For every digit of the number for (int i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] != '9') { // Replace it with 9 str[i] = '9'; // One digit has been used k--; } } return str; } // Driver code public static void Main () { StringBuilder str = new StringBuilder(\"569431\"); int n = str.Length; int k = 3; Console.WriteLine(findMaximumNum(str, n, k)); }} // This code is contributed by ihritik", "e": 30497, "s": 29455, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the maximum number // that can be formed by changing // at most k digits in str function findMaximumNum(str, n, k) { // For every digit of the number for (var i = 0; i < n; i++) { // If no more digits can be replaced if (k < 1) break; // If current digit is not already 9 if (str[i] !== \"9\") { // Replace it with 9 str[i] = \"9\"; // One digit has been used k--; } } return str.join(\"\"); } // Driver code var str = \"569431\"; var n = str.length; var k = 3; document.write(findMaximumNum(str.split(\"\"), n, k)); </script>", "e": 31269, "s": 30497, "text": null }, { "code": null, "e": 31276, "s": 31269, "text": "999931" }, { "code": null, "e": 31300, "s": 31278, "text": "Time Complexity: O(n)" }, { "code": null, "e": 31322, "s": 31300, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31330, "s": 31322, "text": "ihritik" }, { "code": null, "e": 31344, "s": 31330, "text": "divyamohan123" }, { "code": null, "e": 31351, "s": 31344, "text": "rdtank" }, { "code": null, "e": 31367, "s": 31351, "text": "subhammahato348" }, { "code": null, "e": 31381, "s": 31367, "text": "number-digits" }, { "code": null, "e": 31394, "s": 31381, "text": "Mathematical" }, { "code": null, "e": 31407, "s": 31394, "text": "Mathematical" }, { "code": null, "e": 31505, "s": 31407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31529, "s": 31505, "text": "Merge two sorted arrays" }, { "code": null, "e": 31572, "s": 31529, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31586, "s": 31572, "text": "Prime Numbers" }, { "code": null, "e": 31628, "s": 31586, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31650, "s": 31628, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 31723, "s": 31650, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31764, "s": 31723, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31807, "s": 31764, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31828, "s": 31807, "text": "Operators in C / C++" } ]
p5.js | constrain() Function - GeeksforGeeks
25 Mar, 2020 The constrain() function in p5.js is used to constrain a number between a given minimum and maximum limit. Syntax: constrain( n, low, high ) Parameters: This function accept three parameters as mentioned above and described below: n: It is a number which denotes the value that has to be constrained. low: It is a number which denotes the minimum limit to which the number is constrained. high: It is a number which denotes the maximum limit to which the number is constrained. Return Value: It returns a number with the constrained value. The example below illustrates the constrain() function in p5.js: Example 1: function setup() { createCanvas(650, 200); textSize(20); inputElemA = createInput(10); inputElemA.position(30, 40); inputElemB = createInput(100); inputElemB.position(30, 60); sliderElem = createSlider(-100, 100, 50, 1); sliderElem.position(30, 120);} function draw() { clear(); text("Enter two values between which the " + "number would be constrained", 20, 20); text("Move the slider to observe the effects" + " of the constrain() function", 20, 100); // Convert the string value to a number value inputValA = Number(inputElemA.value()); inputValB = Number(inputElemB.value()); sliderVal = sliderElem.value(); text("The slider value is: " + sliderVal, 20, 160); // Display the constrained value text("The constrained value is: " + constrain(sliderVal, inputValA, inputValB), 20, 180);} Output: Example 2: function setup() { createCanvas(600, 350); textSize(20); } function draw() { clear(); text("Move the pointer to see the effect " + "of constrain() in the square", 20, 30); text("White circle represents unconstrained" + " mouse", 20, 50); text("Red circle represents mouse constrained" + " to box dimensions", 20, 70); noFill(); square(100, 100, 200); circle(mouseX, mouseY, 40); // Constrain the mouse x and y position constrainedMouseX = constrain(mouseX, 100, 300); constrainedMouseY = constrain(mouseY, 100, 300); fill('red'); circle(constrainedMouseX, constrainedMouseY, 20);} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/constrain 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 44937, "s": 44909, "text": "\n25 Mar, 2020" }, { "code": null, "e": 45044, "s": 44937, "text": "The constrain() function in p5.js is used to constrain a number between a given minimum and maximum limit." }, { "code": null, "e": 45052, "s": 45044, "text": "Syntax:" }, { "code": null, "e": 45078, "s": 45052, "text": "constrain( n, low, high )" }, { "code": null, "e": 45168, "s": 45078, "text": "Parameters: This function accept three parameters as mentioned above and described below:" }, { "code": null, "e": 45238, "s": 45168, "text": "n: It is a number which denotes the value that has to be constrained." }, { "code": null, "e": 45326, "s": 45238, "text": "low: It is a number which denotes the minimum limit to which the number is constrained." }, { "code": null, "e": 45415, "s": 45326, "text": "high: It is a number which denotes the maximum limit to which the number is constrained." }, { "code": null, "e": 45477, "s": 45415, "text": "Return Value: It returns a number with the constrained value." }, { "code": null, "e": 45542, "s": 45477, "text": "The example below illustrates the constrain() function in p5.js:" }, { "code": null, "e": 45553, "s": 45542, "text": "Example 1:" }, { "code": "function setup() { createCanvas(650, 200); textSize(20); inputElemA = createInput(10); inputElemA.position(30, 40); inputElemB = createInput(100); inputElemB.position(30, 60); sliderElem = createSlider(-100, 100, 50, 1); sliderElem.position(30, 120);} function draw() { clear(); text(\"Enter two values between which the \" + \"number would be constrained\", 20, 20); text(\"Move the slider to observe the effects\" + \" of the constrain() function\", 20, 100); // Convert the string value to a number value inputValA = Number(inputElemA.value()); inputValB = Number(inputElemB.value()); sliderVal = sliderElem.value(); text(\"The slider value is: \" + sliderVal, 20, 160); // Display the constrained value text(\"The constrained value is: \" + constrain(sliderVal, inputValA, inputValB), 20, 180);}", "e": 46399, "s": 45553, "text": null }, { "code": null, "e": 46407, "s": 46399, "text": "Output:" }, { "code": null, "e": 46418, "s": 46407, "text": "Example 2:" }, { "code": "function setup() { createCanvas(600, 350); textSize(20); } function draw() { clear(); text(\"Move the pointer to see the effect \" + \"of constrain() in the square\", 20, 30); text(\"White circle represents unconstrained\" + \" mouse\", 20, 50); text(\"Red circle represents mouse constrained\" + \" to box dimensions\", 20, 70); noFill(); square(100, 100, 200); circle(mouseX, mouseY, 40); // Constrain the mouse x and y position constrainedMouseX = constrain(mouseX, 100, 300); constrainedMouseY = constrain(mouseY, 100, 300); fill('red'); circle(constrainedMouseX, constrainedMouseY, 20);}", "e": 47050, "s": 46418, "text": null }, { "code": null, "e": 47058, "s": 47050, "text": "Output:" }, { "code": null, "e": 47098, "s": 47058, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 47196, "s": 47098, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 47249, "s": 47196, "text": "Reference: https://p5js.org/reference/#/p5/constrain" }, { "code": null, "e": 47266, "s": 47249, "text": "JavaScript-p5.js" }, { "code": null, "e": 47277, "s": 47266, "text": "JavaScript" }, { "code": null, "e": 47294, "s": 47277, "text": "Web Technologies" }, { "code": null, "e": 47392, "s": 47294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47432, "s": 47392, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47477, "s": 47432, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47538, "s": 47477, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 47610, "s": 47538, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 47679, "s": 47610, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 47719, "s": 47679, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47752, "s": 47719, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47797, "s": 47752, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47840, "s": 47797, "text": "How to fetch data from an API in ReactJS ?" } ]
Type Casting in Scala - GeeksforGeeks
26 Jul, 2021 A Type casting is basically a conversion from one type to another. In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another.Type Casting in Scala is done using the asInstanceOf[] method. This perspective is required in manifesting beans from an application context file. It is also used to cast numeric types. It can even be applied in complex codes like communicating with Java and sending it an array of Object instances. Syntax: obj1 = obj.asInstanceOf[class];where, obj1 is the object to which the casted instance of obj is returned, obj is the object to be casted, and class is the name of the class to which obj is to be casted into. Here, only an object of an extended(child) class can be casted to be an object of its parent class but not vice-versa. If class A extends class B, A’s object can be cast to be an object of class B and B’s object cannot be cast to be an object of class A. This method informs the compiler that the value is of the type specified. During runtime, if the value/object supplied is not compatible with the type or class specified, an exception is thrown. Examples: Scala // Scala program of type castingobject GFG{ // Function to display name, value and // class-name of a variable def display[A](y:String, x:A) { println(y + " = " + x + " is of type " + x.getClass.getName); } // Main method def main(args: Array[String]) { var i:Int = 40; var f:Float = 6.0F; var d:Double = 85.2; var c:Char = 'c'; display("i", i); display("f", f); display("d", d); display("c", c); var i1 = i.asInstanceOf[Char]; //Casting var f1 = f.asInstanceOf[Double]; //Casting var d1 = d.asInstanceOf[Float]; //Casting var c1 = c.asInstanceOf[Int]; //Casting display("i1", i1); display("f1", f1); display("d1", d1); display("c1", c1); }} Output: i = 40 is of type java.lang.Integer f = 6.0 is of type java.lang.Float d = 85.2 is of type java.lang.Double c = c is of type java.lang.Character i1 = ( is of type java.lang.Character f1 = 6.0 is of type java.lang.Double d1 = 85.2 is of type java.lang.Float c1 = 99 is of type java.lang.Integer Examples: Scala // Scala program of type casting // The parent classclass Parent{ var i: Int = 10; var j: Int = 5; // Function to display i and j values def display() { println("Value of i : " + i + "\nValue of j : " + j); }} // The child classclass Child extends Parent{ // Used to change i and j values def change() { i = 6; j = 12; println("Values Changed"); }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var c:Child = new Child(); c.display(); c.change(); // Casting var p:Parent = c.asInstanceOf[Parent]; p.display(); /* p.change(); This will have raised an error as p is seen as an object of class Parent and Parent does not contain change() */ }} Output: Value of i : 10 Value of j : 5 Values Changed Value of i : 6 Value of j : 12 In above example p.change(); will be added, the following error would have been occured: error:value change is not a member of parent. Examples: Scala // Scala program of type casting class Parent{ // Member variables and functions. } class Child extends Parent{ // Member variables and functions. } class Unrelated{ // Member variables and functions. } // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var p:Parent = new Parent(); try { p.asInstanceOf[Unrelated]; } catch { // Used to print the thrown exception. case e: Exception => e.printStackTrace(); print(e); } try { p.asInstanceOf[Child]; } catch { // Used to print the thrown exception. case e1: Exception => e1.printStackTrace(); print(e1); } }} Output: java.lang.ClassCastException: Parent cannot be cast to Unrelated java.lang.ClassCastException: Parent cannot be cast to Child sweetyty Picked Scala Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala Constructors Inheritance in Scala Scala String substring() method with example Scala | Arrays How to get the first element of List in Scala Lambda Expression in Scala
[ { "code": null, "e": 25081, "s": 25053, "text": "\n26 Jul, 2021" }, { "code": null, "e": 25313, "s": 25081, "text": "A Type casting is basically a conversion from one type to another. In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another.Type Casting in Scala is done using the asInstanceOf[] method. " }, { "code": null, "e": 25397, "s": 25313, "text": "This perspective is required in manifesting beans from an application context file." }, { "code": null, "e": 25436, "s": 25397, "text": "It is also used to cast numeric types." }, { "code": null, "e": 25550, "s": 25436, "text": "It can even be applied in complex codes like communicating with Java and sending it an array of Object instances." }, { "code": null, "e": 25768, "s": 25550, "text": "Syntax: obj1 = obj.asInstanceOf[class];where, obj1 is the object to which the casted instance of obj is returned, obj is the object to be casted, and class is the name of the class to which obj is to be casted into. " }, { "code": null, "e": 26218, "s": 25768, "text": "Here, only an object of an extended(child) class can be casted to be an object of its parent class but not vice-versa. If class A extends class B, A’s object can be cast to be an object of class B and B’s object cannot be cast to be an object of class A. This method informs the compiler that the value is of the type specified. During runtime, if the value/object supplied is not compatible with the type or class specified, an exception is thrown." }, { "code": null, "e": 26230, "s": 26218, "text": "Examples: " }, { "code": null, "e": 26236, "s": 26230, "text": "Scala" }, { "code": "// Scala program of type castingobject GFG{ // Function to display name, value and // class-name of a variable def display[A](y:String, x:A) { println(y + \" = \" + x + \" is of type \" + x.getClass.getName); } // Main method def main(args: Array[String]) { var i:Int = 40; var f:Float = 6.0F; var d:Double = 85.2; var c:Char = 'c'; display(\"i\", i); display(\"f\", f); display(\"d\", d); display(\"c\", c); var i1 = i.asInstanceOf[Char]; //Casting var f1 = f.asInstanceOf[Double]; //Casting var d1 = d.asInstanceOf[Float]; //Casting var c1 = c.asInstanceOf[Int]; //Casting display(\"i1\", i1); display(\"f1\", f1); display(\"d1\", d1); display(\"c1\", c1); }}", "e": 27075, "s": 26236, "text": null }, { "code": null, "e": 27084, "s": 27075, "text": "Output: " }, { "code": null, "e": 27378, "s": 27084, "text": "i = 40 is of type java.lang.Integer\nf = 6.0 is of type java.lang.Float\nd = 85.2 is of type java.lang.Double\nc = c is of type java.lang.Character\ni1 = ( is of type java.lang.Character\nf1 = 6.0 is of type java.lang.Double\nd1 = 85.2 is of type java.lang.Float\nc1 = 99 is of type java.lang.Integer" }, { "code": null, "e": 27389, "s": 27378, "text": "Examples: " }, { "code": null, "e": 27395, "s": 27389, "text": "Scala" }, { "code": "// Scala program of type casting // The parent classclass Parent{ var i: Int = 10; var j: Int = 5; // Function to display i and j values def display() { println(\"Value of i : \" + i + \"\\nValue of j : \" + j); }} // The child classclass Child extends Parent{ // Used to change i and j values def change() { i = 6; j = 12; println(\"Values Changed\"); }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var c:Child = new Child(); c.display(); c.change(); // Casting var p:Parent = c.asInstanceOf[Parent]; p.display(); /* p.change(); This will have raised an error as p is seen as an object of class Parent and Parent does not contain change() */ }}", "e": 28238, "s": 27395, "text": null }, { "code": null, "e": 28247, "s": 28238, "text": "Output: " }, { "code": null, "e": 28324, "s": 28247, "text": "Value of i : 10\nValue of j : 5\nValues Changed\nValue of i : 6\nValue of j : 12" }, { "code": null, "e": 28415, "s": 28324, "text": "In above example p.change(); will be added, the following error would have been occured: " }, { "code": null, "e": 28461, "s": 28415, "text": "error:value change is not a member of parent." }, { "code": null, "e": 28473, "s": 28461, "text": "Examples: " }, { "code": null, "e": 28479, "s": 28473, "text": "Scala" }, { "code": "// Scala program of type casting class Parent{ // Member variables and functions. } class Child extends Parent{ // Member variables and functions. } class Unrelated{ // Member variables and functions. } // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var p:Parent = new Parent(); try { p.asInstanceOf[Unrelated]; } catch { // Used to print the thrown exception. case e: Exception => e.printStackTrace(); print(e); } try { p.asInstanceOf[Child]; } catch { // Used to print the thrown exception. case e1: Exception => e1.printStackTrace(); print(e1); } }}", "e": 29295, "s": 28479, "text": null }, { "code": null, "e": 29304, "s": 29295, "text": "Output: " }, { "code": null, "e": 29430, "s": 29304, "text": "java.lang.ClassCastException: Parent cannot be cast to Unrelated\njava.lang.ClassCastException: Parent cannot be cast to Child" }, { "code": null, "e": 29441, "s": 29432, "text": "sweetyty" }, { "code": null, "e": 29448, "s": 29441, "text": "Picked" }, { "code": null, "e": 29454, "s": 29448, "text": "Scala" }, { "code": null, "e": 29465, "s": 29454, "text": "Scala-OOPS" }, { "code": null, "e": 29471, "s": 29465, "text": "Scala" }, { "code": null, "e": 29569, "s": 29471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29595, "s": 29569, "text": "Class and Object in Scala" }, { "code": null, "e": 29607, "s": 29595, "text": "Scala Lists" }, { "code": null, "e": 29660, "s": 29607, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 29679, "s": 29660, "text": "Operators in Scala" }, { "code": null, "e": 29698, "s": 29679, "text": "Scala Constructors" }, { "code": null, "e": 29719, "s": 29698, "text": "Inheritance in Scala" }, { "code": null, "e": 29764, "s": 29719, "text": "Scala String substring() method with example" }, { "code": null, "e": 29779, "s": 29764, "text": "Scala | Arrays" }, { "code": null, "e": 29825, "s": 29779, "text": "How to get the first element of List in Scala" } ]
Print all funny words in a string - GeeksforGeeks
31 May, 2021 We are given a sentence. Our task is to print all funny words/strings in that sentence. Reverse the given string. Iterate through each character of that string, compare the absolute difference in the ASCII values of the characters at positions 0 and 1, 1 and 2, 2 and 3 and so on to the end. If the list of absolute differences is the same for both strings, they are funny otherwise not. Examples: Input : HKMNPS Output : Yes Let r be the reverse of original string s s = "HKMNPS" r = "SPNMKH" |H-K| = 3 = |S-P| |K-M| = 2 = |P-N| |M-N| = 1 = |N-M| |N-P| = 2 = |M-K| |P-S| = 3 = |K-H| Since each comparison is equal so given string is funny Input : bdwy Output : No NOTE: Every palindrome string is a funny string but not vice-versa. The idea is to split the string into words. For every word, traverse it from both ends and compare differences between adjacent characters. C++ Java Python3 C# Javascript // C++ pprogram to print all// funny words in a string#include <bits/stdc++.h>using namespace std; bool checkFunny(string word){ int i = 1; int j = word.length() - 2; for (int i = 0; i < word.length(); i++) word[i] = tolower(word[i]); while (i <= j) { if (abs(word[i] - word[i - 1]) != abs(word[j] - word[j + 1])) return false; i++; j--; } return true;} void printFunnyWords(string str){ // to extract last word of sentence str += " "; // to word stores each word of sentence string word = ""; for (int i = 0; i < str.length(); i++) { char ch = str[i]; // extracting each wor if (ch != ' ') word += ch; else { if (checkFunny(word)) cout << word << endl; word = ""; } }} // Driver Codeint main(){ printFunnyWords("Miss Arora teaches us malayalam bdwy "); return 0;} // This code is contributed by// sanjeev2552 class Funny { static boolean checkFunny(String word) { int i = 1; int j = word.length() - 2; word = word.toLowerCase(); while (i <= j) { if ((Math.abs(word.charAt(i) - word.charAt(i - 1))) != Math.abs((word.charAt(j) - word.charAt(j + 1)))) return false; i++; j--; } return true; } static void printFunnyWords(String str) { // to extract last word of sentence str = str + " "; // to word stores each word of sentence String word = ""; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // extracting each word if (ch != ' ') word = word + ch; else { if (Funny.checkFunny(word)) System.out.println(word); word = ""; } } } public static void main(String[] args) { Funny.printFunnyWords("Miss Arora teaches us malayalam bdwy "); }} # Python program to print all funny words in a stringdef checkFunny(word): i = 1 j = len(word) - 2 word = word.lower() while (i <= j): if ((abs(ord(word[i]) - ord(word[i - 1]))) != abs((ord(word[j]) - ord(word[j + 1])))): return False i = i + 1 j = j - 1 return True def printFunnyWords(str): # to extract last word of sentence str = str + " " # to word stores each word of sentence word = "" i = 0 for i in range(len(str)): ch = str[i] # extracting each word if (ch != ' '): word = word + ch else: if (checkFunny(word)): print (word) word = "" # Driver codeprintFunnyWords("Miss Arora teaches us malayalam bdwy ") # This code is contributed by Prateek Bajaj // C# program to print funny stringusing System; class GFG{public static bool checkFunny(string word){ int i = 1; int j = word.Length - 2; word = word.ToLower(); while (i <= j) { if ((Math.Abs(word[i] - word[i - 1])) != Math.Abs((word[j] - word[j + 1]))) { return false; } i++; j--; } return true;} public static void printFunnyWords(string str){ // to extract last word of sentence str = str + " "; // to word stores each word of sentence string word = ""; for (int i = 0; i < str.Length; i++) { char ch = str[i]; // extracting each word if (ch != ' ') { word = word + ch; } else { if (GFG.checkFunny(word)) { Console.WriteLine(word); } word = ""; } }} // Driver Codepublic static void Main(string[] args){ GFG.printFunnyWords("Miss Arora teaches us " + "malayalam bdwy ");}} // This code is contributed by Shrikant13 <script> // Javascript pprogram to print all// funny words in a string function checkFunny(word){ var i = 1; var j = word.length - 2; word= (word.toLowerCase()); while (i <= j) { if (Math.abs(word[i].charCodeAt(0) - word[i - 1].charCodeAt(0)) != Math.abs(word[j].charCodeAt(0) - word[j + 1].charCodeAt(0))) return false; i++; j--; } return true;} function printFunnyWords(str){ // to extract last word of sentence str += " "; // to word stores each word of sentence var word = ""; for (var i = 0; i < str.length; i++) { var ch = str[i]; // extracting each wor if (ch != ' ') word += ch; else { if (checkFunny(word)) document.write( word + "<br>"); word = ""; } }} // Driver CodeprintFunnyWords("Miss Arora teaches us malayalam bdwy "); </script> Arora us malayalam bdwy YouTubeGeeksforGeeks507K subscribersPrint all funny words in a string | 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 / 3:19•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=f0GkhCOX5eY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Prateek Bajaj shrikanth13 sanjeev2552 noob2000 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher sprintf() in C String class in Java | Set 1 Convert character array to string in C++ Program to count occurrence of a given character in a string How to Append a Character to a String in C Print all subsequences of a string Naive algorithm for Pattern Searching
[ { "code": null, "e": 26098, "s": 26070, "text": "\n31 May, 2021" }, { "code": null, "e": 26188, "s": 26098, "text": "We are given a sentence. Our task is to print all funny words/strings in that sentence. " }, { "code": null, "e": 26489, "s": 26188, "text": "Reverse the given string. Iterate through each character of that string, compare the absolute difference in the ASCII values of the characters at positions 0 and 1, 1 and 2, 2 and 3 and so on to the end. If the list of absolute differences is the same for both strings, they are funny otherwise not. " }, { "code": null, "e": 26500, "s": 26489, "text": "Examples: " }, { "code": null, "e": 26793, "s": 26500, "text": "Input : HKMNPS\nOutput : Yes\nLet r be the reverse of original string s\ns = \"HKMNPS\"\nr = \"SPNMKH\" \n|H-K| = 3 = |S-P| \n|K-M| = 2 = |P-N| \n|M-N| = 1 = |N-M|\n|N-P| = 2 = |M-K|\n|P-S| = 3 = |K-H|\nSince each comparison is equal so given string is funny\n\nInput : bdwy \nOutput : No " }, { "code": null, "e": 26861, "s": 26793, "text": "NOTE: Every palindrome string is a funny string but not vice-versa." }, { "code": null, "e": 27002, "s": 26861, "text": "The idea is to split the string into words. For every word, traverse it from both ends and compare differences between adjacent characters. " }, { "code": null, "e": 27006, "s": 27002, "text": "C++" }, { "code": null, "e": 27011, "s": 27006, "text": "Java" }, { "code": null, "e": 27019, "s": 27011, "text": "Python3" }, { "code": null, "e": 27022, "s": 27019, "text": "C#" }, { "code": null, "e": 27033, "s": 27022, "text": "Javascript" }, { "code": "// C++ pprogram to print all// funny words in a string#include <bits/stdc++.h>using namespace std; bool checkFunny(string word){ int i = 1; int j = word.length() - 2; for (int i = 0; i < word.length(); i++) word[i] = tolower(word[i]); while (i <= j) { if (abs(word[i] - word[i - 1]) != abs(word[j] - word[j + 1])) return false; i++; j--; } return true;} void printFunnyWords(string str){ // to extract last word of sentence str += \" \"; // to word stores each word of sentence string word = \"\"; for (int i = 0; i < str.length(); i++) { char ch = str[i]; // extracting each wor if (ch != ' ') word += ch; else { if (checkFunny(word)) cout << word << endl; word = \"\"; } }} // Driver Codeint main(){ printFunnyWords(\"Miss Arora teaches us malayalam bdwy \"); return 0;} // This code is contributed by// sanjeev2552", "e": 28080, "s": 27033, "text": null }, { "code": "class Funny { static boolean checkFunny(String word) { int i = 1; int j = word.length() - 2; word = word.toLowerCase(); while (i <= j) { if ((Math.abs(word.charAt(i) - word.charAt(i - 1))) != Math.abs((word.charAt(j) - word.charAt(j + 1)))) return false; i++; j--; } return true; } static void printFunnyWords(String str) { // to extract last word of sentence str = str + \" \"; // to word stores each word of sentence String word = \"\"; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // extracting each word if (ch != ' ') word = word + ch; else { if (Funny.checkFunny(word)) System.out.println(word); word = \"\"; } } } public static void main(String[] args) { Funny.printFunnyWords(\"Miss Arora teaches us malayalam bdwy \"); }}", "e": 29132, "s": 28080, "text": null }, { "code": "# Python program to print all funny words in a stringdef checkFunny(word): i = 1 j = len(word) - 2 word = word.lower() while (i <= j): if ((abs(ord(word[i]) - ord(word[i - 1]))) != abs((ord(word[j]) - ord(word[j + 1])))): return False i = i + 1 j = j - 1 return True def printFunnyWords(str): # to extract last word of sentence str = str + \" \" # to word stores each word of sentence word = \"\" i = 0 for i in range(len(str)): ch = str[i] # extracting each word if (ch != ' '): word = word + ch else: if (checkFunny(word)): print (word) word = \"\" # Driver codeprintFunnyWords(\"Miss Arora teaches us malayalam bdwy \") # This code is contributed by Prateek Bajaj", "e": 29954, "s": 29132, "text": null }, { "code": "// C# program to print funny stringusing System; class GFG{public static bool checkFunny(string word){ int i = 1; int j = word.Length - 2; word = word.ToLower(); while (i <= j) { if ((Math.Abs(word[i] - word[i - 1])) != Math.Abs((word[j] - word[j + 1]))) { return false; } i++; j--; } return true;} public static void printFunnyWords(string str){ // to extract last word of sentence str = str + \" \"; // to word stores each word of sentence string word = \"\"; for (int i = 0; i < str.Length; i++) { char ch = str[i]; // extracting each word if (ch != ' ') { word = word + ch; } else { if (GFG.checkFunny(word)) { Console.WriteLine(word); } word = \"\"; } }} // Driver Codepublic static void Main(string[] args){ GFG.printFunnyWords(\"Miss Arora teaches us \" + \"malayalam bdwy \");}} // This code is contributed by Shrikant13", "e": 31092, "s": 29954, "text": null }, { "code": "<script> // Javascript pprogram to print all// funny words in a string function checkFunny(word){ var i = 1; var j = word.length - 2; word= (word.toLowerCase()); while (i <= j) { if (Math.abs(word[i].charCodeAt(0) - word[i - 1].charCodeAt(0)) != Math.abs(word[j].charCodeAt(0) - word[j + 1].charCodeAt(0))) return false; i++; j--; } return true;} function printFunnyWords(str){ // to extract last word of sentence str += \" \"; // to word stores each word of sentence var word = \"\"; for (var i = 0; i < str.length; i++) { var ch = str[i]; // extracting each wor if (ch != ' ') word += ch; else { if (checkFunny(word)) document.write( word + \"<br>\"); word = \"\"; } }} // Driver CodeprintFunnyWords(\"Miss Arora teaches us malayalam bdwy \"); </script>", "e": 32080, "s": 31092, "text": null }, { "code": null, "e": 32104, "s": 32080, "text": "Arora\nus\nmalayalam\nbdwy" }, { "code": null, "e": 32938, "s": 32106, "text": "YouTubeGeeksforGeeks507K subscribersPrint all funny words in a string | 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 / 3:19•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=f0GkhCOX5eY\" 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": 32952, "s": 32938, "text": "Prateek Bajaj" }, { "code": null, "e": 32964, "s": 32952, "text": "shrikanth13" }, { "code": null, "e": 32976, "s": 32964, "text": "sanjeev2552" }, { "code": null, "e": 32985, "s": 32976, "text": "noob2000" }, { "code": null, "e": 32996, "s": 32985, "text": "palindrome" }, { "code": null, "e": 33004, "s": 32996, "text": "Strings" }, { "code": null, "e": 33012, "s": 33004, "text": "Strings" }, { "code": null, "e": 33023, "s": 33012, "text": "palindrome" }, { "code": null, "e": 33121, "s": 33023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33166, "s": 33121, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 33211, "s": 33166, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 33228, "s": 33211, "text": "Vigenère Cipher" }, { "code": null, "e": 33243, "s": 33228, "text": "sprintf() in C" }, { "code": null, "e": 33272, "s": 33243, "text": "String class in Java | Set 1" }, { "code": null, "e": 33313, "s": 33272, "text": "Convert character array to string in C++" }, { "code": null, "e": 33374, "s": 33313, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 33417, "s": 33374, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 33452, "s": 33417, "text": "Print all subsequences of a string" } ]
Generate 0 and 1 with 25% and 75% probability - GeeksforGeeks
06 Nov, 2021 Given a function rand50() that returns 0 or 1 with equal probability, write a function that returns 1 with 75% probability and 0 with 25% probability using rand50() only. Minimize the number of calls to rand50() method. Also, use of any other library function and floating point arithmetic are not allowed. The idea is to use Bitwise OR. A bitwise OR takes two bits and returns 0 if both bits are 0, while otherwise the result is 1. So it has 75% probability that it will return 1.Below is the implementation of above idea : C++ Java PHP Javascript // Program to print 1 with 75% probability and 0// with 25% probability#include <iostream>using namespace std; // Random Function to that returns 0 or 1 with// equal probabilityint rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// Bitwise ORbool rand75(){ return rand50() | rand50();} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); for(int i = 0; i < 50; i++) cout << rand75(); return 0;} // Java program to print 1 with 75% probability and 0// with 25% probabilityclass GFG{ // Random Function to that returns 0 or 1 with // equal probability static int rand50() { // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return (int) (10 * Math.random()) & 1; } // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise OR static int rand75() { return rand50() | rand50(); } // Driver code public static void main(String[] args) { // Initialize random number generator //srand(time(null)); for (int i = 0; i < 50; i++) { System.out.print(rand75()); } } } // This code is contributed by 29AjayKumar <?php// Program to print 1 with 75% probability// and 0 with 25% probability // Random Function to that returns 0 or// 1 with equal probabilityfunction rand50(){ // rand() function will generate // odd or even number with equal // probability. If rand() generates // odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns// 1 with 75% probability and 0// with 25% probability using// Bitwise ORfunction rand75(){ return rand50() | rand50();} // Driver Code // Initialize random // number generator srand(time(NULL)); for($i = 0; $i < 50; $i++) echo rand75(); // This code is contributed m_kit?> <script>// Program to print 1 with 75% probability and 0// with 25% probability // Random Function to that returns 0 or 1 with// equal probabilityfunction rand50() { // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return Math.floor(Math.random() * 10) & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// Bitwise ORfunction rand75() { return rand50() | rand50();} // Driver code to test above functions // Initialize random number generator for (let i = 0; i < 50; i++) document.write(rand75()); // This code is contributed by gfgking</script> Output: 11101111110010010110011111111101111110111100011000 Time Complexity: O(1) Auxiliary Space: O(1) On similar lines, we can also use Bitwise AND. Since it returns 0 with 75% probability, we have to invert the result. // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise AND bool rand75() { return !(rand50() & rand50()); } We can replace Bitwise OR and Bitwise AND operator by OR and AND operators as well – // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // OR or AND operator int rand75() { return !(rand50() && rand50()); // return rand50() || rand50() } We can also achieve the result using left shift operator and Bitwise XOR – C++ Java PHP Javascript // Program to print 1 with 75% probability and 0// with 25% probability#include <iostream>using namespace std; // Random Function to that returns 0 or 1 with// equal probabilityint rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// left shift and Bitwise XORint rand75(){ // x is one of {0, 1} int x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); for (int i = 0; i < 50; i++) cout << rand75(); return 0;} // Java program to print 1 with 75% probability and 0// with 25% probabilityclass GFG{ // Random Function to that returns 0 or 1 with// equal probabilitystatic int rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return (int) (10 * Math.random()) & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// left shift and Bitwise XORstatic int rand75(){ // x is one of {0, 1} int x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver codepublic static void main(String[] args){ for (int i = 0; i < 50; i++) System.out.print(rand75());}} // This code is contributed by 29AjayKumar <?php// Program to print 1 with// 75% probability and 0// with 25% probability // Random Function to that// returns 0 or 1 with// equal probabilityfunction rand50(){ // rand() function will // generate odd or even // number with equal // probability. If rand() // generates odd number, // the function will return // 1 else it will return 0. return rand() & 1;} // Random Function to that// returns 1 with 75%// probability and 0 with// 25% probability using// left shift and Bitwise XORfunction rand75(){ // x is one of {0, 1} $x = rand50(); $x = $x << 1; // x is now one // of {00, 10} $x = $x ^ rand50(); // x is now one of // {00, 01, 10, 11} return ($x > 0) ? 1 : 0;} // Driver code // Initialize random// number generatorsrand(time(NULL)); for ($i = 0; $i < 50; $i++) echo rand75(); // This code is contributed// by ajit?> <script>// Javascript program to print 1 with 75% probability and 0// with 25% probability // Random Function to that returns 0 or 1 with // equal probabilityfunction rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return Math.floor((10 * Math.random())) & 1;} // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise ORfunction rand75(){ // x is one of {0, 1} let x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver code for (let i = 0; i < 50; i++){ document.write(rand75());} // This code is contributed by rag2127</script> Output: 01101110111011000111111111110001111011101110110110 Time Complexity: O(1) Auxiliary Space: O(1) Please note above solutions will produce different results every time we run them.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t 29AjayKumar Akanksha_Rai gfgking rag2127 subhammahato348 Bitwise-XOR Bit Magic Randomized Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Add two numbers without using arithmetic operators K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Shuffle a given array using Fisher–Yates shuffle Algorithm QuickSort using Random Pivoting Shuffle or Randomize a list in Java Estimating the value of Pi using Monte Carlo
[ { "code": null, "e": 26619, "s": 26591, "text": "\n06 Nov, 2021" }, { "code": null, "e": 26927, "s": 26619, "text": "Given a function rand50() that returns 0 or 1 with equal probability, write a function that returns 1 with 75% probability and 0 with 25% probability using rand50() only. Minimize the number of calls to rand50() method. Also, use of any other library function and floating point arithmetic are not allowed. " }, { "code": null, "e": 27146, "s": 26927, "text": "The idea is to use Bitwise OR. A bitwise OR takes two bits and returns 0 if both bits are 0, while otherwise the result is 1. So it has 75% probability that it will return 1.Below is the implementation of above idea : " }, { "code": null, "e": 27150, "s": 27146, "text": "C++" }, { "code": null, "e": 27155, "s": 27150, "text": "Java" }, { "code": null, "e": 27159, "s": 27155, "text": "PHP" }, { "code": null, "e": 27170, "s": 27159, "text": "Javascript" }, { "code": "// Program to print 1 with 75% probability and 0// with 25% probability#include <iostream>using namespace std; // Random Function to that returns 0 or 1 with// equal probabilityint rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// Bitwise ORbool rand75(){ return rand50() | rand50();} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); for(int i = 0; i < 50; i++) cout << rand75(); return 0;}", "e": 27900, "s": 27170, "text": null }, { "code": "// Java program to print 1 with 75% probability and 0// with 25% probabilityclass GFG{ // Random Function to that returns 0 or 1 with // equal probability static int rand50() { // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return (int) (10 * Math.random()) & 1; } // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise OR static int rand75() { return rand50() | rand50(); } // Driver code public static void main(String[] args) { // Initialize random number generator //srand(time(null)); for (int i = 0; i < 50; i++) { System.out.print(rand75()); } } } // This code is contributed by 29AjayKumar", "e": 28806, "s": 27900, "text": null }, { "code": "<?php// Program to print 1 with 75% probability// and 0 with 25% probability // Random Function to that returns 0 or// 1 with equal probabilityfunction rand50(){ // rand() function will generate // odd or even number with equal // probability. If rand() generates // odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns// 1 with 75% probability and 0// with 25% probability using// Bitwise ORfunction rand75(){ return rand50() | rand50();} // Driver Code // Initialize random // number generator srand(time(NULL)); for($i = 0; $i < 50; $i++) echo rand75(); // This code is contributed m_kit?>", "e": 29516, "s": 28806, "text": null }, { "code": "<script>// Program to print 1 with 75% probability and 0// with 25% probability // Random Function to that returns 0 or 1 with// equal probabilityfunction rand50() { // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return Math.floor(Math.random() * 10) & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// Bitwise ORfunction rand75() { return rand50() | rand50();} // Driver code to test above functions // Initialize random number generator for (let i = 0; i < 50; i++) document.write(rand75()); // This code is contributed by gfgking</script>", "e": 30252, "s": 29516, "text": null }, { "code": null, "e": 30262, "s": 30252, "text": "Output: " }, { "code": null, "e": 30313, "s": 30262, "text": "11101111110010010110011111111101111110111100011000" }, { "code": null, "e": 30335, "s": 30313, "text": "Time Complexity: O(1)" }, { "code": null, "e": 30357, "s": 30335, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30476, "s": 30357, "text": "On similar lines, we can also use Bitwise AND. Since it returns 0 with 75% probability, we have to invert the result. " }, { "code": null, "e": 30640, "s": 30476, "text": "// Random Function to that returns 1 with 75% \n// probability and 0 with 25% probability using\n// Bitwise AND\nbool rand75() \n{\n return !(rand50() & rand50());\n}" }, { "code": null, "e": 30727, "s": 30640, "text": "We can replace Bitwise OR and Bitwise AND operator by OR and AND operators as well – " }, { "code": null, "e": 30932, "s": 30727, "text": "// Random Function to that returns 1 with 75%\n// probability and 0 with 25% probability using \n// OR or AND operator\nint rand75()\n{\n return !(rand50() && rand50());\n // return rand50() || rand50()\n}" }, { "code": null, "e": 31009, "s": 30932, "text": "We can also achieve the result using left shift operator and Bitwise XOR – " }, { "code": null, "e": 31013, "s": 31009, "text": "C++" }, { "code": null, "e": 31018, "s": 31013, "text": "Java" }, { "code": null, "e": 31022, "s": 31018, "text": "PHP" }, { "code": null, "e": 31033, "s": 31022, "text": "Javascript" }, { "code": "// Program to print 1 with 75% probability and 0// with 25% probability#include <iostream>using namespace std; // Random Function to that returns 0 or 1 with// equal probabilityint rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return rand() & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// left shift and Bitwise XORint rand75(){ // x is one of {0, 1} int x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); for (int i = 0; i < 50; i++) cout << rand75(); return 0;}", "e": 31932, "s": 31033, "text": null }, { "code": "// Java program to print 1 with 75% probability and 0// with 25% probabilityclass GFG{ // Random Function to that returns 0 or 1 with// equal probabilitystatic int rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return (int) (10 * Math.random()) & 1;} // Random Function to that returns 1 with 75%// probability and 0 with 25% probability using// left shift and Bitwise XORstatic int rand75(){ // x is one of {0, 1} int x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver codepublic static void main(String[] args){ for (int i = 0; i < 50; i++) System.out.print(rand75());}} // This code is contributed by 29AjayKumar", "e": 32822, "s": 31932, "text": null }, { "code": "<?php// Program to print 1 with// 75% probability and 0// with 25% probability // Random Function to that// returns 0 or 1 with// equal probabilityfunction rand50(){ // rand() function will // generate odd or even // number with equal // probability. If rand() // generates odd number, // the function will return // 1 else it will return 0. return rand() & 1;} // Random Function to that// returns 1 with 75%// probability and 0 with// 25% probability using// left shift and Bitwise XORfunction rand75(){ // x is one of {0, 1} $x = rand50(); $x = $x << 1; // x is now one // of {00, 10} $x = $x ^ rand50(); // x is now one of // {00, 01, 10, 11} return ($x > 0) ? 1 : 0;} // Driver code // Initialize random// number generatorsrand(time(NULL)); for ($i = 0; $i < 50; $i++) echo rand75(); // This code is contributed// by ajit?>", "e": 33714, "s": 32822, "text": null }, { "code": "<script>// Javascript program to print 1 with 75% probability and 0// with 25% probability // Random Function to that returns 0 or 1 with // equal probabilityfunction rand50(){ // rand() function will generate odd or even // number with equal probability. If rand() // generates odd number, the function will // return 1 else it will return 0. return Math.floor((10 * Math.random())) & 1;} // Random Function to that returns 1 with 75% // probability and 0 with 25% probability using // Bitwise ORfunction rand75(){ // x is one of {0, 1} let x = rand50(); x = x << 1; // x is now one of {00, 10} x = x ^ rand50(); // x is now one of {00, 01, 10, 11} return (x > 0) ? 1 : 0;} // Driver code for (let i = 0; i < 50; i++){ document.write(rand75());} // This code is contributed by rag2127</script>", "e": 34598, "s": 33714, "text": null }, { "code": null, "e": 34608, "s": 34598, "text": "Output: " }, { "code": null, "e": 34659, "s": 34608, "text": "01101110111011000111111111110001111011101110110110" }, { "code": null, "e": 34681, "s": 34659, "text": "Time Complexity: O(1)" }, { "code": null, "e": 34703, "s": 34681, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 35205, "s": 34703, "text": "Please note above solutions will produce different results every time we run them.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35211, "s": 35205, "text": "jit_t" }, { "code": null, "e": 35223, "s": 35211, "text": "29AjayKumar" }, { "code": null, "e": 35236, "s": 35223, "text": "Akanksha_Rai" }, { "code": null, "e": 35244, "s": 35236, "text": "gfgking" }, { "code": null, "e": 35252, "s": 35244, "text": "rag2127" }, { "code": null, "e": 35268, "s": 35252, "text": "subhammahato348" }, { "code": null, "e": 35280, "s": 35268, "text": "Bitwise-XOR" }, { "code": null, "e": 35290, "s": 35280, "text": "Bit Magic" }, { "code": null, "e": 35301, "s": 35290, "text": "Randomized" }, { "code": null, "e": 35311, "s": 35301, "text": "Bit Magic" }, { "code": null, "e": 35409, "s": 35311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35439, "s": 35409, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 35485, "s": 35439, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 35525, "s": 35485, "text": "Binary representation of a given number" }, { "code": null, "e": 35578, "s": 35525, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 35629, "s": 35578, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 35708, "s": 35629, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 35767, "s": 35708, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 35799, "s": 35767, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 35835, "s": 35799, "text": "Shuffle or Randomize a list in Java" } ]
Absolute Difference of even and odd indexed elements in an Array - GeeksforGeeks
28 May, 2021 Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: Even Index absolute difference : 3 Odd Index absolute difference : 4 Explanation : Here, even indexed elements are 1, 3 and 5 So the even absolute difference will be (|1 – 3| = 2) => (|2 – 5| = 3) Similarly odd indexed elements are 2, 4 and 6 And the odd absolute difference will be (|2 – 4| = 2) => (|2 – 6| = 4)Input: arr[] = {10, 20, 30, 40, 50, 60, 70} Output: Even Index absolute difference : 40 Odd Index absolute difference : 40 Approach: Traverse the array and keep two variables even and odd to store the absolute difference of elements of even and odd indexes respectively. While traversing check if the current index is even, i.e. (i%2) == 0. Print the results in the end.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find absolute difference of elements// at even and odd index positions separately#include <bits/stdc++.h>using namespace std; // Function to calculate absolute differencevoid EvenOddAbsoluteDifference(int arr[], int n){ int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd absolute difference if (i % 2 == 0) even = abs(even - arr[i]); else odd = abs(odd - arr[i]); } cout << "Even Index absolute difference : " << even; cout << endl; cout << "Odd Index absolute difference : " << odd;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); EvenOddAbsoluteDifference(arr, n); return 0;} // Java program to find absolute difference of elements// at even and odd index positions separately public class GFG{ // Function to calculate absolute difference static void EvenOddAbsoluteDifference(int arr[], int n) { int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd absolute difference if (i % 2 == 0) even = Math.abs(even - arr[i]); else odd = Math.abs(odd - arr[i]); } System.out.println("Even Index absolute difference : " + even); System.out.println("Odd Index absolute difference : " + odd); } // Driver Code public static void main(String []args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; EvenOddAbsoluteDifference(arr, n); } // This code is contributed by ANKITRAI1} # Python 3 program to find absolute difference of# elements at even and odd index positions separately # Function to calculate absolute differencedef EvenOddAbsoluteDifference(arr, n): even = 0 odd = 0 for i in range(0, n, 1): # Loop to find even, odd absolute # difference if (i % 2 == 0): even = abs(even - arr[i]); else: odd = abs(odd - arr[i]); print("Even Index absolute difference :", even) print("Odd Index absolute difference :", odd) # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6] n = len(arr) EvenOddAbsoluteDifference(arr, n) # This code is contributed by# Sahil_shelangia // C# program to find absolute difference// of elements at even and odd index// positions separatelyusing System; class GFG{// Function to calculate absolute differencestatic void EvenOddAbsoluteDifference(int []arr, int n){ int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd // absolute difference if (i % 2 == 0) even = Math.Abs(even - arr[i]); else odd = Math.Abs(odd - arr[i]); } Console.WriteLine("Even Index absolute " + "difference : " + even); Console.WriteLine("Odd Index absolute " + "difference : " + odd);} // Driver Codestatic public void Main (){ int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; EvenOddAbsoluteDifference(arr, n);}} // This code is contributed by Sachin <?php// PHP program to find absolute// difference of elements at even// and odd index positions separately // Function to calculate absolute// differencefunction EvenOddAbsoluteDifference($arr, $n){ $even = 0; $odd = 0; for ($i = 0; $i < $n; $i++) { // Loop to find even, odd // absolute difference if ($i % 2 == 0) $even = abs($even - $arr[$i]); else $odd = abs($odd - $arr[$i]); } echo "Even Index absolute difference : ", $even; echo "\n"; echo "Odd Index absolute difference : ", $odd;} // Driver Code$arr = array( 1, 2, 3, 4, 5, 6 );$n = sizeof($arr); EvenOddAbsoluteDifference($arr, $n); // This code is contributed by Sachin?> <script> // Javascript program to find absolute difference // of elements at even and odd index // positions separately // Function to calculate absolute difference function EvenOddAbsoluteDifference(arr, n) { let even = 0; let odd = 0; for (let i = 0; i < n; i++) { // Loop to find even, odd // absolute difference if (i % 2 == 0) even = Math.abs(even - arr[i]); else odd = Math.abs(odd - arr[i]); } document.write("Even Index absolute " + "difference : " + even + "</br>"); document.write("Odd Index absolute " + "difference : " + odd + "</br>"); } let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; EvenOddAbsoluteDifference(arr, n); </script> Even Index absolute difference : 3 Odd Index absolute difference : 4 Time complexity : O(n) ankthon Sach_Code VishalBachchas sahilshelangia rameshtravel07 array-traversal-question Technical Scripter 2018 Arrays Technical Scripter Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers) Building Heap from Array Remove duplicates from sorted array Program to find sum of elements in a given array
[ { "code": null, "e": 26175, "s": 26147, "text": "\n28 May, 2021" }, { "code": null, "e": 26440, "s": 26175, "text": "Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: " }, { "code": null, "e": 26920, "s": 26440, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6} Output: Even Index absolute difference : 3 Odd Index absolute difference : 4 Explanation : Here, even indexed elements are 1, 3 and 5 So the even absolute difference will be (|1 – 3| = 2) => (|2 – 5| = 3) Similarly odd indexed elements are 2, 4 and 6 And the odd absolute difference will be (|2 – 4| = 2) => (|2 – 6| = 4)Input: arr[] = {10, 20, 30, 40, 50, 60, 70} Output: Even Index absolute difference : 40 Odd Index absolute difference : 40 " }, { "code": null, "e": 27221, "s": 26922, "text": "Approach: Traverse the array and keep two variables even and odd to store the absolute difference of elements of even and odd indexes respectively. While traversing check if the current index is even, i.e. (i%2) == 0. Print the results in the end.Below is the implementation of the above approach: " }, { "code": null, "e": 27225, "s": 27221, "text": "C++" }, { "code": null, "e": 27230, "s": 27225, "text": "Java" }, { "code": null, "e": 27238, "s": 27230, "text": "Python3" }, { "code": null, "e": 27241, "s": 27238, "text": "C#" }, { "code": null, "e": 27245, "s": 27241, "text": "PHP" }, { "code": null, "e": 27256, "s": 27245, "text": "Javascript" }, { "code": "// CPP program to find absolute difference of elements// at even and odd index positions separately#include <bits/stdc++.h>using namespace std; // Function to calculate absolute differencevoid EvenOddAbsoluteDifference(int arr[], int n){ int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd absolute difference if (i % 2 == 0) even = abs(even - arr[i]); else odd = abs(odd - arr[i]); } cout << \"Even Index absolute difference : \" << even; cout << endl; cout << \"Odd Index absolute difference : \" << odd;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); EvenOddAbsoluteDifference(arr, n); return 0;}", "e": 28016, "s": 27256, "text": null }, { "code": "// Java program to find absolute difference of elements// at even and odd index positions separately public class GFG{ // Function to calculate absolute difference static void EvenOddAbsoluteDifference(int arr[], int n) { int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd absolute difference if (i % 2 == 0) even = Math.abs(even - arr[i]); else odd = Math.abs(odd - arr[i]); } System.out.println(\"Even Index absolute difference : \" + even); System.out.println(\"Odd Index absolute difference : \" + odd); } // Driver Code public static void main(String []args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; EvenOddAbsoluteDifference(arr, n); } // This code is contributed by ANKITRAI1}", "e": 28946, "s": 28016, "text": null }, { "code": "# Python 3 program to find absolute difference of# elements at even and odd index positions separately # Function to calculate absolute differencedef EvenOddAbsoluteDifference(arr, n): even = 0 odd = 0 for i in range(0, n, 1): # Loop to find even, odd absolute # difference if (i % 2 == 0): even = abs(even - arr[i]); else: odd = abs(odd - arr[i]); print(\"Even Index absolute difference :\", even) print(\"Odd Index absolute difference :\", odd) # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6] n = len(arr) EvenOddAbsoluteDifference(arr, n) # This code is contributed by# Sahil_shelangia", "e": 29638, "s": 28946, "text": null }, { "code": "// C# program to find absolute difference// of elements at even and odd index// positions separatelyusing System; class GFG{// Function to calculate absolute differencestatic void EvenOddAbsoluteDifference(int []arr, int n){ int even = 0; int odd = 0; for (int i = 0; i < n; i++) { // Loop to find even, odd // absolute difference if (i % 2 == 0) even = Math.Abs(even - arr[i]); else odd = Math.Abs(odd - arr[i]); } Console.WriteLine(\"Even Index absolute \" + \"difference : \" + even); Console.WriteLine(\"Odd Index absolute \" + \"difference : \" + odd);} // Driver Codestatic public void Main (){ int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; EvenOddAbsoluteDifference(arr, n);}} // This code is contributed by Sachin", "e": 30522, "s": 29638, "text": null }, { "code": "<?php// PHP program to find absolute// difference of elements at even// and odd index positions separately // Function to calculate absolute// differencefunction EvenOddAbsoluteDifference($arr, $n){ $even = 0; $odd = 0; for ($i = 0; $i < $n; $i++) { // Loop to find even, odd // absolute difference if ($i % 2 == 0) $even = abs($even - $arr[$i]); else $odd = abs($odd - $arr[$i]); } echo \"Even Index absolute difference : \", $even; echo \"\\n\"; echo \"Odd Index absolute difference : \", $odd;} // Driver Code$arr = array( 1, 2, 3, 4, 5, 6 );$n = sizeof($arr); EvenOddAbsoluteDifference($arr, $n); // This code is contributed by Sachin?>", "e": 31309, "s": 30522, "text": null }, { "code": "<script> // Javascript program to find absolute difference // of elements at even and odd index // positions separately // Function to calculate absolute difference function EvenOddAbsoluteDifference(arr, n) { let even = 0; let odd = 0; for (let i = 0; i < n; i++) { // Loop to find even, odd // absolute difference if (i % 2 == 0) even = Math.abs(even - arr[i]); else odd = Math.abs(odd - arr[i]); } document.write(\"Even Index absolute \" + \"difference : \" + even + \"</br>\"); document.write(\"Odd Index absolute \" + \"difference : \" + odd + \"</br>\"); } let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; EvenOddAbsoluteDifference(arr, n); </script>", "e": 32178, "s": 31309, "text": null }, { "code": null, "e": 32247, "s": 32178, "text": "Even Index absolute difference : 3\nOdd Index absolute difference : 4" }, { "code": null, "e": 32273, "s": 32249, "text": "Time complexity : O(n) " }, { "code": null, "e": 32281, "s": 32273, "text": "ankthon" }, { "code": null, "e": 32291, "s": 32281, "text": "Sach_Code" }, { "code": null, "e": 32306, "s": 32291, "text": "VishalBachchas" }, { "code": null, "e": 32321, "s": 32306, "text": "sahilshelangia" }, { "code": null, "e": 32336, "s": 32321, "text": "rameshtravel07" }, { "code": null, "e": 32361, "s": 32336, "text": "array-traversal-question" }, { "code": null, "e": 32385, "s": 32361, "text": "Technical Scripter 2018" }, { "code": null, "e": 32392, "s": 32385, "text": "Arrays" }, { "code": null, "e": 32411, "s": 32392, "text": "Technical Scripter" }, { "code": null, "e": 32418, "s": 32411, "text": "Arrays" }, { "code": null, "e": 32516, "s": 32418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32547, "s": 32516, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32572, "s": 32547, "text": "Window Sliding Technique" }, { "code": null, "e": 32610, "s": 32572, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32631, "s": 32610, "text": "Next Greater Element" }, { "code": null, "e": 32689, "s": 32631, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 32716, "s": 32689, "text": "Count pairs with given sum" }, { "code": null, "e": 32775, "s": 32716, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 32800, "s": 32775, "text": "Building Heap from Array" }, { "code": null, "e": 32836, "s": 32800, "text": "Remove duplicates from sorted array" } ]
Recursive program to check if number is palindrome or not in C++
We are given an integer as input. The goal is to find whether the input number Num is a palindrome or not using recursion. To check if a number is palindrome, reverse that number and check if both numbers are the same or not. If the reversed number is equal to the original number, then it is palindrome. Input − Num = 34212; Output − 34212 is not a Palindrome! Explanation − If we reverse 34212 then we get 21243. 34212 != 21243 hence the input number is not palindrome. Input − Num = 32123; Output − 32123 is Palindrome! Explanation − If we reverse 32123 then we get 32132. 32123!= 32123 hence the input number is palindrome. In this approach we are using the recursive function revrsNum(int num1, int num2) which takes input number num1 and temporary number num2. For base cases-: if num1 is 0 return num2. Else-: calculate reverse of num1 using recursion. Return calculated reverse. If both are the same, then the input number is palindrome. Take the input number Num. Take the input number Num. Take Num2 = revrsNum(Num,0) Take Num2 = revrsNum(Num,0) Function revrsNum(int num1, int num2) generates reverse of num1 recursively and returns the reversed number. Function revrsNum(int num1, int num2) generates reverse of num1 recursively and returns the reversed number. If num1 is 0 then return num2 as calculated reverse. If num1 is 0 then return num2 as calculated reverse. Else multiple num2 by 10 and add num1%10 to it. Else multiple num2 by 10 and add num1%10 to it. Reduce num1 by 10 using num1=num1/10. Reduce num1 by 10 using num1=num1/10. Recurse using revrsNum(num1, num2); Recurse using revrsNum(num1, num2); Return result. Return result. Print result obtained inside main. Print result obtained inside main. #include <bits/stdc++.h> using namespace std; int revrsNum(int num1, int num2){ if (num1 == 0){ return num2; } num2 *= 10; num2 += (num1 % 10); num1 = num1/10; return revrsNum(num1, num2); } int main(){ int Num = 1345431; int Num2 = revrsNum(Num,0); if (Num == Num2){ cout <<Num<<" is Palindrome!"; } else{ cout <<Num<<" is not a Palindrome!"; } return 0; } If we run the above code it will generate the following Output 1345431 is Palindrome!
[ { "code": null, "e": 1185, "s": 1062, "text": "We are given an integer as input. The goal is to find whether the input number Num is a palindrome or not using recursion." }, { "code": null, "e": 1367, "s": 1185, "text": "To check if a number is palindrome, reverse that number and check if both numbers are the same or not. If the reversed number is equal to the original number, then it is palindrome." }, { "code": null, "e": 1388, "s": 1367, "text": "Input − Num = 34212;" }, { "code": null, "e": 1424, "s": 1388, "text": "Output − 34212 is not a Palindrome!" }, { "code": null, "e": 1534, "s": 1424, "text": "Explanation − If we reverse 34212 then we get 21243. 34212 != 21243 hence the input number is not palindrome." }, { "code": null, "e": 1555, "s": 1534, "text": "Input − Num = 32123;" }, { "code": null, "e": 1585, "s": 1555, "text": "Output − 32123 is Palindrome!" }, { "code": null, "e": 1690, "s": 1585, "text": "Explanation − If we reverse 32123 then we get 32132. 32123!= 32123 hence the input number is palindrome." }, { "code": null, "e": 1829, "s": 1690, "text": "In this approach we are using the recursive function revrsNum(int num1, int num2) which takes input number num1 and temporary number num2." }, { "code": null, "e": 1872, "s": 1829, "text": "For base cases-: if num1 is 0 return num2." }, { "code": null, "e": 1949, "s": 1872, "text": "Else-: calculate reverse of num1 using recursion. Return calculated reverse." }, { "code": null, "e": 2008, "s": 1949, "text": "If both are the same, then the input number is palindrome." }, { "code": null, "e": 2035, "s": 2008, "text": "Take the input number Num." }, { "code": null, "e": 2062, "s": 2035, "text": "Take the input number Num." }, { "code": null, "e": 2090, "s": 2062, "text": "Take Num2 = revrsNum(Num,0)" }, { "code": null, "e": 2118, "s": 2090, "text": "Take Num2 = revrsNum(Num,0)" }, { "code": null, "e": 2227, "s": 2118, "text": "Function revrsNum(int num1, int num2) generates reverse of num1 recursively and returns the reversed number." }, { "code": null, "e": 2336, "s": 2227, "text": "Function revrsNum(int num1, int num2) generates reverse of num1 recursively and returns the reversed number." }, { "code": null, "e": 2389, "s": 2336, "text": "If num1 is 0 then return num2 as calculated reverse." }, { "code": null, "e": 2442, "s": 2389, "text": "If num1 is 0 then return num2 as calculated reverse." }, { "code": null, "e": 2490, "s": 2442, "text": "Else multiple num2 by 10 and add num1%10 to it." }, { "code": null, "e": 2538, "s": 2490, "text": "Else multiple num2 by 10 and add num1%10 to it." }, { "code": null, "e": 2576, "s": 2538, "text": "Reduce num1 by 10 using num1=num1/10." }, { "code": null, "e": 2614, "s": 2576, "text": "Reduce num1 by 10 using num1=num1/10." }, { "code": null, "e": 2650, "s": 2614, "text": "Recurse using revrsNum(num1, num2);" }, { "code": null, "e": 2686, "s": 2650, "text": "Recurse using revrsNum(num1, num2);" }, { "code": null, "e": 2701, "s": 2686, "text": "Return result." }, { "code": null, "e": 2716, "s": 2701, "text": "Return result." }, { "code": null, "e": 2751, "s": 2716, "text": "Print result obtained inside main." }, { "code": null, "e": 2786, "s": 2751, "text": "Print result obtained inside main." }, { "code": null, "e": 3201, "s": 2786, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint revrsNum(int num1, int num2){\n if (num1 == 0){\n return num2;\n }\n num2 *= 10;\n num2 += (num1 % 10);\n num1 = num1/10;\n return revrsNum(num1, num2);\n}\nint main(){\n int Num = 1345431;\n int Num2 = revrsNum(Num,0);\n if (Num == Num2){\n cout <<Num<<\" is Palindrome!\";\n }\n else{\n cout <<Num<<\" is not a Palindrome!\";\n }\n return 0;\n}" }, { "code": null, "e": 3264, "s": 3201, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 3287, "s": 3264, "text": "1345431 is Palindrome!" } ]
Serving Prophet Model with Flask — Predicting Future | by Andrej Baranovskij | Towards Data Science
An accurate forecast and future prediction are crucial almost for any business. This is an obvious thing and it doesn’t need explanation. There is a concept of time series data, this data is ordered by date and typically each date is assigned with one or more values specific to that date. Machine Learning powered models could generate forecasts based on time series data. Such forecasts could be an important source of information for business decisions. I was researching LSTM models for time series forecasting. LSTM neural networks are good in predicting sequence data, time series is sequence data too and this is the reasons LSTM networks are used to forecast time series. LSTM implementation is complex, it is hard to prepare input data for LSTM training. Probably all LSTM examples demonstrate forecast based on data from current dataset, but not the real future data — this makes it hard to apply LSTM in practice. When I found on GitHub and evaluated Prophet Python library for future forecasting, I was impressed by its simplicity and practicality. Prophet — Open Source forecast library developed by Facebook. I will share a sample Python notebook with Prophet forecast implementation and show how to save/load Prophet model and serve it through Flask API. Source code and data are available in my GitHub repo. First, you need to import Prophet library: import pandas as pdimport matplotlib.pyplot as pltfrom fbprophet import Prophet%matplotlib inline If Prophet is not installed in your environment, you need to install it. I was installing it in Ubuntu running within Docker container. It didn’t work to install with pip. But I was able to install with conda: conda install gccconda install -c conda-forge fbprophet Typically the next step is to load data. For this sample, I’m using iron/steel price dataset (downloaded from here). Data is loaded into the frame with Pandas library. Pandas data frame allows to manipulate and wrangle data. We are removing unused columns, setting index and re-ordering time series data: df = pd.read_csv('Dow Jones Iron & Steel Historical Data.csv')df = df[['Date', 'Price']].dropna()df['Date'] = pd.to_datetime(df['Date'])df = df.set_index('Date')daily_df = df.resample('D').mean()d_df = daily_df.reset_index().dropna() Prophet operates with ds/y columns, we should rename columns in the data frame: d_df.columns = ['ds', 'y']fig = plt.figure(facecolor='w', figsize=(20, 6))plt.plot(d_df.ds, d_df.y) Iron/steel price data we are going to use for Prophet model training: Here it comes the key part — Prophet model training: m = Prophet()m.fit(d_df)future = m.make_future_dataframe(periods=90)forecast = m.predict(future)forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() Model training is executed by calling fit function and passing Pandas data frame. Future prediction is executed by predict function and passing parameter to describe how many days into the future to predict (90 days in the above example). Prophet returns a data frame with various parameters to describe the forecast. One of the most important: ds — forecast dateyhat — forecast value for the given dateyhat_lower — lower forecast boundary for the given dateyhat_uppet — upper forecast boundary for the given date ds — forecast date yhat — forecast value for the given date yhat_lower — lower forecast boundary for the given date yhat_uppet — upper forecast boundary for the given date Calling plot function for Prophet model displays how the model was trained according to training data (black points — training data, blue line — forecast value, light blue area — forecast boundaries): This chart shows model prediction for 90 days into the future. But it is hard to see it, the chart shows all the data. We can zoom into the data and render chart with a vertical line splitting prediction from training data: from datetime import datetime, timedeltafig1 = m.plot(forecast)#datenow = datetime.now()datenow = datetime(2019, 7, 2)dateend = datenow + timedelta(days=90)datestart = dateend - timedelta(days=450)plt.xlim([datestart, dateend])plt.title("Iron/steel forecast", fontsize=20)plt.xlabel("Day", fontsize=20)plt.ylabel("Iron/steel price", fontsize=20)plt.axvline(datenow, color="k", linestyle=":")plt.show() This helps to see the prediction for 90 days clearer. We can see a downward trend in the price forecast: There is a simple way to print forecast values, accessing last 90 days from the forecast data frame: forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']][-90:] To evaluate the model, it is useful to display learned trends: fig2 = m.plot_components(forecast) Prophet learns that price is usually going down from March to October. You should check what is the expected error, when predicting by a certain number of days. This is called model cross-validation: from fbprophet.diagnostics import cross_validation, performance_metricsdf_cv = cross_validation(m, horizon='90 days')df_p = performance_metrics(df_cv)df_p.head(5) Result: We can plot these metrics to see visually how the model would perform. It is easier to understand percentage error (MAPE), this is how we can plot it: from fbprophet.plot import plot_cross_validation_metricfig3 = plot_cross_validation_metric(df_cv, metric='mape') It shows that 10 days forecast results in around 10% error and then error grows to about 18%: The model should be re-trained when new data becomes available. There is no point to re-train model, if data is not changed. Save model instead and use it again, when user wants to call predict function. Use pickle functionality for that: import picklewith open('forecast_model.pckl', 'wb') as fout: pickle.dump(m, fout)with open('forecast_model.pckl', 'rb') as fin: m2 = pickle.load(fin) This will save the model into a physical file on disk. In this example I show how to save and load the model for your convenience, in a real implementation, load function will be called in a different place (in a function which will be responsible to process user request for forecast). Flask works perfectly to expose Prophet model to the external world through REST API. Import Flask library: from flask import Flask, jsonify, requestfrom flask_cors import CORS, cross_origin Call predict within the function with Flask annotation: app = Flask(__name__)CORS(app)@app.route("/katana-ml/api/v1.0/forecast/ironsteel", methods=['POST'])def predict(): horizon = int(request.json['horizon']) future2 = m2.make_future_dataframe(periods=horizon) forecast2 = m2.predict(future2) data = forecast2[['ds', 'yhat', 'yhat_lower', 'yhat_upper']][-horizon:] ret = data.to_json(orient='records', date_format='iso') return ret# running REST interface, port=3000 for direct testif __name__ == "__main__": app.run(debug=False, host='0.0.0.0', port=3000) Example of REST API call through Postman. Prediction horizon parameter is passed to the API and we get back JSON response with forecast data: Source code and sample data are available in my GitHub repo.
[ { "code": null, "e": 628, "s": 171, "text": "An accurate forecast and future prediction are crucial almost for any business. This is an obvious thing and it doesn’t need explanation. There is a concept of time series data, this data is ordered by date and typically each date is assigned with one or more values specific to that date. Machine Learning powered models could generate forecasts based on time series data. Such forecasts could be an important source of information for business decisions." }, { "code": null, "e": 1096, "s": 628, "text": "I was researching LSTM models for time series forecasting. LSTM neural networks are good in predicting sequence data, time series is sequence data too and this is the reasons LSTM networks are used to forecast time series. LSTM implementation is complex, it is hard to prepare input data for LSTM training. Probably all LSTM examples demonstrate forecast based on data from current dataset, but not the real future data — this makes it hard to apply LSTM in practice." }, { "code": null, "e": 1294, "s": 1096, "text": "When I found on GitHub and evaluated Prophet Python library for future forecasting, I was impressed by its simplicity and practicality. Prophet — Open Source forecast library developed by Facebook." }, { "code": null, "e": 1441, "s": 1294, "text": "I will share a sample Python notebook with Prophet forecast implementation and show how to save/load Prophet model and serve it through Flask API." }, { "code": null, "e": 1495, "s": 1441, "text": "Source code and data are available in my GitHub repo." }, { "code": null, "e": 1538, "s": 1495, "text": "First, you need to import Prophet library:" }, { "code": null, "e": 1636, "s": 1538, "text": "import pandas as pdimport matplotlib.pyplot as pltfrom fbprophet import Prophet%matplotlib inline" }, { "code": null, "e": 1846, "s": 1636, "text": "If Prophet is not installed in your environment, you need to install it. I was installing it in Ubuntu running within Docker container. It didn’t work to install with pip. But I was able to install with conda:" }, { "code": null, "e": 1902, "s": 1846, "text": "conda install gccconda install -c conda-forge fbprophet" }, { "code": null, "e": 2207, "s": 1902, "text": "Typically the next step is to load data. For this sample, I’m using iron/steel price dataset (downloaded from here). Data is loaded into the frame with Pandas library. Pandas data frame allows to manipulate and wrangle data. We are removing unused columns, setting index and re-ordering time series data:" }, { "code": null, "e": 2441, "s": 2207, "text": "df = pd.read_csv('Dow Jones Iron & Steel Historical Data.csv')df = df[['Date', 'Price']].dropna()df['Date'] = pd.to_datetime(df['Date'])df = df.set_index('Date')daily_df = df.resample('D').mean()d_df = daily_df.reset_index().dropna()" }, { "code": null, "e": 2521, "s": 2441, "text": "Prophet operates with ds/y columns, we should rename columns in the data frame:" }, { "code": null, "e": 2621, "s": 2521, "text": "d_df.columns = ['ds', 'y']fig = plt.figure(facecolor='w', figsize=(20, 6))plt.plot(d_df.ds, d_df.y)" }, { "code": null, "e": 2691, "s": 2621, "text": "Iron/steel price data we are going to use for Prophet model training:" }, { "code": null, "e": 2744, "s": 2691, "text": "Here it comes the key part — Prophet model training:" }, { "code": null, "e": 2900, "s": 2744, "text": "m = Prophet()m.fit(d_df)future = m.make_future_dataframe(periods=90)forecast = m.predict(future)forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()" }, { "code": null, "e": 3245, "s": 2900, "text": "Model training is executed by calling fit function and passing Pandas data frame. Future prediction is executed by predict function and passing parameter to describe how many days into the future to predict (90 days in the above example). Prophet returns a data frame with various parameters to describe the forecast. One of the most important:" }, { "code": null, "e": 3414, "s": 3245, "text": "ds — forecast dateyhat — forecast value for the given dateyhat_lower — lower forecast boundary for the given dateyhat_uppet — upper forecast boundary for the given date" }, { "code": null, "e": 3433, "s": 3414, "text": "ds — forecast date" }, { "code": null, "e": 3474, "s": 3433, "text": "yhat — forecast value for the given date" }, { "code": null, "e": 3530, "s": 3474, "text": "yhat_lower — lower forecast boundary for the given date" }, { "code": null, "e": 3586, "s": 3530, "text": "yhat_uppet — upper forecast boundary for the given date" }, { "code": null, "e": 3787, "s": 3586, "text": "Calling plot function for Prophet model displays how the model was trained according to training data (black points — training data, blue line — forecast value, light blue area — forecast boundaries):" }, { "code": null, "e": 4011, "s": 3787, "text": "This chart shows model prediction for 90 days into the future. But it is hard to see it, the chart shows all the data. We can zoom into the data and render chart with a vertical line splitting prediction from training data:" }, { "code": null, "e": 4413, "s": 4011, "text": "from datetime import datetime, timedeltafig1 = m.plot(forecast)#datenow = datetime.now()datenow = datetime(2019, 7, 2)dateend = datenow + timedelta(days=90)datestart = dateend - timedelta(days=450)plt.xlim([datestart, dateend])plt.title(\"Iron/steel forecast\", fontsize=20)plt.xlabel(\"Day\", fontsize=20)plt.ylabel(\"Iron/steel price\", fontsize=20)plt.axvline(datenow, color=\"k\", linestyle=\":\")plt.show()" }, { "code": null, "e": 4518, "s": 4413, "text": "This helps to see the prediction for 90 days clearer. We can see a downward trend in the price forecast:" }, { "code": null, "e": 4619, "s": 4518, "text": "There is a simple way to print forecast values, accessing last 90 days from the forecast data frame:" }, { "code": null, "e": 4678, "s": 4619, "text": "forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']][-90:]" }, { "code": null, "e": 4741, "s": 4678, "text": "To evaluate the model, it is useful to display learned trends:" }, { "code": null, "e": 4776, "s": 4741, "text": "fig2 = m.plot_components(forecast)" }, { "code": null, "e": 4847, "s": 4776, "text": "Prophet learns that price is usually going down from March to October." }, { "code": null, "e": 4976, "s": 4847, "text": "You should check what is the expected error, when predicting by a certain number of days. This is called model cross-validation:" }, { "code": null, "e": 5139, "s": 4976, "text": "from fbprophet.diagnostics import cross_validation, performance_metricsdf_cv = cross_validation(m, horizon='90 days')df_p = performance_metrics(df_cv)df_p.head(5)" }, { "code": null, "e": 5147, "s": 5139, "text": "Result:" }, { "code": null, "e": 5298, "s": 5147, "text": "We can plot these metrics to see visually how the model would perform. It is easier to understand percentage error (MAPE), this is how we can plot it:" }, { "code": null, "e": 5411, "s": 5298, "text": "from fbprophet.plot import plot_cross_validation_metricfig3 = plot_cross_validation_metric(df_cv, metric='mape')" }, { "code": null, "e": 5505, "s": 5411, "text": "It shows that 10 days forecast results in around 10% error and then error grows to about 18%:" }, { "code": null, "e": 5744, "s": 5505, "text": "The model should be re-trained when new data becomes available. There is no point to re-train model, if data is not changed. Save model instead and use it again, when user wants to call predict function. Use pickle functionality for that:" }, { "code": null, "e": 5900, "s": 5744, "text": "import picklewith open('forecast_model.pckl', 'wb') as fout: pickle.dump(m, fout)with open('forecast_model.pckl', 'rb') as fin: m2 = pickle.load(fin)" }, { "code": null, "e": 6187, "s": 5900, "text": "This will save the model into a physical file on disk. In this example I show how to save and load the model for your convenience, in a real implementation, load function will be called in a different place (in a function which will be responsible to process user request for forecast)." }, { "code": null, "e": 6295, "s": 6187, "text": "Flask works perfectly to expose Prophet model to the external world through REST API. Import Flask library:" }, { "code": null, "e": 6378, "s": 6295, "text": "from flask import Flask, jsonify, requestfrom flask_cors import CORS, cross_origin" }, { "code": null, "e": 6434, "s": 6378, "text": "Call predict within the function with Flask annotation:" }, { "code": null, "e": 6973, "s": 6434, "text": "app = Flask(__name__)CORS(app)@app.route(\"/katana-ml/api/v1.0/forecast/ironsteel\", methods=['POST'])def predict(): horizon = int(request.json['horizon']) future2 = m2.make_future_dataframe(periods=horizon) forecast2 = m2.predict(future2) data = forecast2[['ds', 'yhat', 'yhat_lower', 'yhat_upper']][-horizon:] ret = data.to_json(orient='records', date_format='iso') return ret# running REST interface, port=3000 for direct testif __name__ == \"__main__\": app.run(debug=False, host='0.0.0.0', port=3000)" }, { "code": null, "e": 7115, "s": 6973, "text": "Example of REST API call through Postman. Prediction horizon parameter is passed to the API and we get back JSON response with forecast data:" } ]
XPath - Relative Path
Location path specifies the location of node in XML document. This path can be absolute or relative. If location path starts with the node that we've selected then it is a relative path. Following are few examples locating the elements using relative path. firstname − select firstname related to student nodes. <p><xsl:value-of select = "firstname"/></p> In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions. Following is the sample XML used. <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/" > <html> <body> <h3>Details of each Students. </h3> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "/class/student"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> 90 Lectures 20 hours Arun Motoori 23 Lectures 8 hours Sanjay Kumar 13 Lectures 1.5 hours Sanjay Kumar 24 Lectures 1.5 hours Sanjay Kumar 47 Lectures 3 hours Krishna Sakinala Print Add Notes Bookmark this page
[ { "code": null, "e": 1916, "s": 1729, "text": "Location path specifies the location of node in XML document. This path can be absolute or relative. If location path starts with the node that we've selected then it is a relative path." }, { "code": null, "e": 1986, "s": 1916, "text": "Following are few examples locating the elements using relative path." }, { "code": null, "e": 2041, "s": 1986, "text": "firstname − select firstname related to student nodes." }, { "code": null, "e": 2085, "s": 2041, "text": "<p><xsl:value-of select = \"firstname\"/></p>" }, { "code": null, "e": 2226, "s": 2085, "text": "In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions." }, { "code": null, "e": 2260, "s": 2226, "text": "Following is the sample XML used." }, { "code": null, "e": 2862, "s": 2260, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 3942, "s": 2862, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\">\n\t\n <xsl:template match = \"/\" >\n <html>\n <body>\n <h3>Details of each Students. </h3>\n <table border = \"1\">\n <tr bgcolor = \"#9acd32\">\n <th>Roll No</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Nick Name</th>\n <th>Marks</th>\t\t \n </tr>\t\t \n\t\t\t\t\t\n <xsl:for-each select = \"/class/student\">\n <tr>\n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\t\t \n </tr>\n </xsl:for-each>\n </table> \n </body>\n </html>\n </xsl:template>\n</xsl:stylesheet>" }, { "code": null, "e": 3976, "s": 3942, "text": "\n 90 Lectures \n 20 hours \n" }, { "code": null, "e": 3990, "s": 3976, "text": " Arun Motoori" }, { "code": null, "e": 4023, "s": 3990, "text": "\n 23 Lectures \n 8 hours \n" }, { "code": null, "e": 4037, "s": 4023, "text": " Sanjay Kumar" }, { "code": null, "e": 4072, "s": 4037, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4086, "s": 4072, "text": " Sanjay Kumar" }, { "code": null, "e": 4121, "s": 4086, "text": "\n 24 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4135, "s": 4121, "text": " Sanjay Kumar" }, { "code": null, "e": 4168, "s": 4135, "text": "\n 47 Lectures \n 3 hours \n" }, { "code": null, "e": 4186, "s": 4168, "text": " Krishna Sakinala" }, { "code": null, "e": 4193, "s": 4186, "text": " Print" }, { "code": null, "e": 4204, "s": 4193, "text": " Add Notes" } ]
Scikit Learn - Logistic Regression
Logistic regression, despite its name, is a classification algorithm rather than regression algorithm. Based on a given set of independent variables, it is used to estimate discrete value (0 or 1, yes/no, true/false). It is also called logit or MaxEnt Classifier. Basically, it measures the relationship between the categorical dependent variable and one or more independent variables by estimating the probability of occurrence of an event using its logistics function. sklearn.linear_model.LogisticRegression is the module used to implement logistic regression. Following table lists the parameters used by Logistic Regression module − penalty − str, ‘L1’, ‘L2’, ‘elasticnet’ or none, optional, default = ‘L2’ This parameter is used to specify the norm (L1 or L2) used in penalization (regularization). dual − Boolean, optional, default = False It is used for dual or primal formulation whereas dual formulation is only implemented for L2 penalty. tol − float, optional, default=1e-4 It represents the tolerance for stopping criteria. C − float, optional, default=1.0 It represents the inverse of regularization strength, which must always be a positive float. fit_intercept − Boolean, optional, default = True This parameter specifies that a constant (bias or intercept) should be added to the decision function. intercept_scaling − float, optional, default = 1 This parameter is useful when the solver ‘liblinear’ is used the solver ‘liblinear’ is used fit_intercept is set to true fit_intercept is set to true class_weight − dict or ‘balanced’ optional, default = none It represents the weights associated with classes. If we use the default option, it means all the classes are supposed to have weight one. On the other hand, if you choose class_weight: balanced, it will use the values of y to automatically adjust weights. random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options int − in this case, random_state is the seed used by random number generator. int − in this case, random_state is the seed used by random number generator. RandomState instance − in this case, random_state is the random number generator. RandomState instance − in this case, random_state is the random number generator. None − in this case, the random number generator is the RandonState instance used by np.random. None − in this case, the random number generator is the RandonState instance used by np.random. solver − str, {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘saag’, ‘saga’}, optional, default = ‘liblinear’ This parameter represents which algorithm to use in the optimization problem. Followings are the properties of options under this parameter − liblinear − It is a good choice for small datasets. It also handles L1 penalty. For multiclass problems, it is limited to one-versus-rest schemes. liblinear − It is a good choice for small datasets. It also handles L1 penalty. For multiclass problems, it is limited to one-versus-rest schemes. newton-cg − It handles only L2 penalty. newton-cg − It handles only L2 penalty. lbfgs − For multiclass problems, it handles multinomial loss. It also handles only L2 penalty. lbfgs − For multiclass problems, it handles multinomial loss. It also handles only L2 penalty. saga − It is a good choice for large datasets. For multiclass problems, it also handles multinomial loss. Along with L1 penalty, it also supports ‘elasticnet’ penalty. saga − It is a good choice for large datasets. For multiclass problems, it also handles multinomial loss. Along with L1 penalty, it also supports ‘elasticnet’ penalty. sag − It is also used for large datasets. For multiclass problems, it also handles multinomial loss. sag − It is also used for large datasets. For multiclass problems, it also handles multinomial loss. max_iter − int, optional, default = 100 As name suggest, it represents the maximum number of iterations taken for solvers to converge. multi_class − str, {‘ovr’, ‘multinomial’, ‘auto’}, optional, default = ‘ovr’ ovr − For this option, a binary problem is fit for each label. ovr − For this option, a binary problem is fit for each label. multimonial − For this option, the loss minimized is the multinomial loss fit across the entire probability distribution. We can’t use this option if solver = ‘liblinear’. multimonial − For this option, the loss minimized is the multinomial loss fit across the entire probability distribution. We can’t use this option if solver = ‘liblinear’. auto − This option will select ‘ovr’ if solver = ‘liblinear’ or data is binary, else it will choose ‘multinomial’. auto − This option will select ‘ovr’ if solver = ‘liblinear’ or data is binary, else it will choose ‘multinomial’. verbose − int, optional, default = 0 By default, the value of this parameter is 0 but for liblinear and lbfgs solver we should set verbose to any positive number. warm_start − bool, optional, default = false With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution. n_jobs − int or None, optional, default = None If multi_class = ‘ovr’, this parameter represents the number of CPU cores used when parallelizing over classes. It is ignored when solver = ‘liblinear’. l1_ratio − float or None, optional, dgtefault = None It is used in case when penalty = ‘elasticnet’. It is basically the Elastic-Net mixing parameter with 0 < = l1_ratio > = 1. Followings table consist the attributes used by Logistic Regression module − coef_ − array, shape(n_features,) or (n_classes, n_features) It is used to estimate the coefficients of the features in the decision function. When the given problem is binary, it is of the shape (1, n_features). Intercept_ − array, shape(1) or (n_classes) It represents the constant, also known as bias, added to the decision function. classes_ − array, shape(n_classes) It will provide a list of class labels known to the classifier. n_iter_ − array, shape (n_classes) or (1) It returns the actual number of iterations for all the classes. Following Python script provides a simple example of implementing logistic regression on iris dataset of scikit-learn − from sklearn import datasets from sklearn import linear_model from sklearn.datasets import load_iris X, y = load_iris(return_X_y = True) LRG = linear_model.LogisticRegression( random_state = 0,solver = 'liblinear',multi class = 'auto' ) .fit(X, y) LRG.score(X, y) 0.96 The output shows that the above Logistic Regression model gave the accuracy of 96 percent. 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2485, "s": 2221, "text": "Logistic regression, despite its name, is a classification algorithm rather than regression algorithm. Based on a given set of independent variables, it is used to estimate discrete value (0 or 1, yes/no, true/false). It is also called logit or MaxEnt Classifier." }, { "code": null, "e": 2692, "s": 2485, "text": "Basically, it measures the relationship between the categorical dependent variable and one or more independent variables by estimating the probability of occurrence of an event using its logistics function." }, { "code": null, "e": 2785, "s": 2692, "text": "sklearn.linear_model.LogisticRegression is the module used to implement logistic regression." }, { "code": null, "e": 2859, "s": 2785, "text": "Following table lists the parameters used by Logistic Regression module −" }, { "code": null, "e": 2933, "s": 2859, "text": "penalty − str, ‘L1’, ‘L2’, ‘elasticnet’ or none, optional, default = ‘L2’" }, { "code": null, "e": 3026, "s": 2933, "text": "This parameter is used to specify the norm (L1 or L2) used in penalization (regularization)." }, { "code": null, "e": 3068, "s": 3026, "text": "dual − Boolean, optional, default = False" }, { "code": null, "e": 3171, "s": 3068, "text": "It is used for dual or primal formulation whereas dual formulation is only implemented for L2 penalty." }, { "code": null, "e": 3207, "s": 3171, "text": "tol − float, optional, default=1e-4" }, { "code": null, "e": 3258, "s": 3207, "text": "It represents the tolerance for stopping criteria." }, { "code": null, "e": 3291, "s": 3258, "text": "C − float, optional, default=1.0" }, { "code": null, "e": 3384, "s": 3291, "text": "It represents the inverse of regularization strength, which must always be a positive float." }, { "code": null, "e": 3434, "s": 3384, "text": "fit_intercept − Boolean, optional, default = True" }, { "code": null, "e": 3537, "s": 3434, "text": "This parameter specifies that a constant (bias or intercept) should be added to the decision function." }, { "code": null, "e": 3586, "s": 3537, "text": "intercept_scaling − float, optional, default = 1" }, { "code": null, "e": 3616, "s": 3586, "text": "This parameter is useful when" }, { "code": null, "e": 3647, "s": 3616, "text": "the solver ‘liblinear’ is used" }, { "code": null, "e": 3678, "s": 3647, "text": "the solver ‘liblinear’ is used" }, { "code": null, "e": 3707, "s": 3678, "text": "fit_intercept is set to true" }, { "code": null, "e": 3736, "s": 3707, "text": "fit_intercept is set to true" }, { "code": null, "e": 3795, "s": 3736, "text": "class_weight − dict or ‘balanced’ optional, default = none" }, { "code": null, "e": 4052, "s": 3795, "text": "It represents the weights associated with classes. If we use the default option, it means all the classes are supposed to have weight one. On the other hand, if you choose class_weight: balanced, it will use the values of y to automatically adjust weights." }, { "code": null, "e": 4127, "s": 4052, "text": "random_state − int, RandomState instance or None, optional, default = none" }, { "code": null, "e": 4267, "s": 4127, "text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options" }, { "code": null, "e": 4345, "s": 4267, "text": "int − in this case, random_state is the seed used by random number generator." }, { "code": null, "e": 4423, "s": 4345, "text": "int − in this case, random_state is the seed used by random number generator." }, { "code": null, "e": 4505, "s": 4423, "text": "RandomState instance − in this case, random_state is the random number generator." }, { "code": null, "e": 4587, "s": 4505, "text": "RandomState instance − in this case, random_state is the random number generator." }, { "code": null, "e": 4683, "s": 4587, "text": "None − in this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 4779, "s": 4683, "text": "None − in this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 4878, "s": 4779, "text": "solver − str, {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘saag’, ‘saga’}, optional, default = ‘liblinear’" }, { "code": null, "e": 5020, "s": 4878, "text": "This parameter represents which algorithm to use in the optimization problem. Followings are the properties of options under this parameter −" }, { "code": null, "e": 5167, "s": 5020, "text": "liblinear − It is a good choice for small datasets. It also handles L1 penalty. For multiclass problems, it is limited to one-versus-rest schemes." }, { "code": null, "e": 5314, "s": 5167, "text": "liblinear − It is a good choice for small datasets. It also handles L1 penalty. For multiclass problems, it is limited to one-versus-rest schemes." }, { "code": null, "e": 5354, "s": 5314, "text": "newton-cg − It handles only L2 penalty." }, { "code": null, "e": 5394, "s": 5354, "text": "newton-cg − It handles only L2 penalty." }, { "code": null, "e": 5489, "s": 5394, "text": "lbfgs − For multiclass problems, it handles multinomial loss. It also handles only L2 penalty." }, { "code": null, "e": 5584, "s": 5489, "text": "lbfgs − For multiclass problems, it handles multinomial loss. It also handles only L2 penalty." }, { "code": null, "e": 5752, "s": 5584, "text": "saga − It is a good choice for large datasets. For multiclass problems, it also handles multinomial loss. Along with L1 penalty, it also supports ‘elasticnet’ penalty." }, { "code": null, "e": 5920, "s": 5752, "text": "saga − It is a good choice for large datasets. For multiclass problems, it also handles multinomial loss. Along with L1 penalty, it also supports ‘elasticnet’ penalty." }, { "code": null, "e": 6021, "s": 5920, "text": "sag − It is also used for large datasets. For multiclass problems, it also handles multinomial loss." }, { "code": null, "e": 6122, "s": 6021, "text": "sag − It is also used for large datasets. For multiclass problems, it also handles multinomial loss." }, { "code": null, "e": 6162, "s": 6122, "text": "max_iter − int, optional, default = 100" }, { "code": null, "e": 6257, "s": 6162, "text": "As name suggest, it represents the maximum number of iterations taken for solvers to converge." }, { "code": null, "e": 6334, "s": 6257, "text": "multi_class − str, {‘ovr’, ‘multinomial’, ‘auto’}, optional, default = ‘ovr’" }, { "code": null, "e": 6397, "s": 6334, "text": "ovr − For this option, a binary problem is fit for each label." }, { "code": null, "e": 6460, "s": 6397, "text": "ovr − For this option, a binary problem is fit for each label." }, { "code": null, "e": 6632, "s": 6460, "text": "multimonial − For this option, the loss minimized is the multinomial loss fit across the entire probability distribution. We can’t use this option if solver = ‘liblinear’." }, { "code": null, "e": 6804, "s": 6632, "text": "multimonial − For this option, the loss minimized is the multinomial loss fit across the entire probability distribution. We can’t use this option if solver = ‘liblinear’." }, { "code": null, "e": 6919, "s": 6804, "text": "auto − This option will select ‘ovr’ if solver = ‘liblinear’ or data is binary, else it will choose ‘multinomial’." }, { "code": null, "e": 7034, "s": 6919, "text": "auto − This option will select ‘ovr’ if solver = ‘liblinear’ or data is binary, else it will choose ‘multinomial’." }, { "code": null, "e": 7071, "s": 7034, "text": "verbose − int, optional, default = 0" }, { "code": null, "e": 7197, "s": 7071, "text": "By default, the value of this parameter is 0 but for liblinear and lbfgs solver we should set verbose to any positive number." }, { "code": null, "e": 7242, "s": 7197, "text": "warm_start − bool, optional, default = false" }, { "code": null, "e": 7418, "s": 7242, "text": "With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution." }, { "code": null, "e": 7465, "s": 7418, "text": "n_jobs − int or None, optional, default = None" }, { "code": null, "e": 7618, "s": 7465, "text": "If multi_class = ‘ovr’, this parameter represents the number of CPU cores used when parallelizing over classes. It is ignored when solver = ‘liblinear’." }, { "code": null, "e": 7671, "s": 7618, "text": "l1_ratio − float or None, optional, dgtefault = None" }, { "code": null, "e": 7795, "s": 7671, "text": "It is used in case when penalty = ‘elasticnet’. It is basically the Elastic-Net mixing parameter with 0 < = l1_ratio > = 1." }, { "code": null, "e": 7872, "s": 7795, "text": "Followings table consist the attributes used by Logistic Regression module −" }, { "code": null, "e": 7933, "s": 7872, "text": "coef_ − array, shape(n_features,) or (n_classes, n_features)" }, { "code": null, "e": 8085, "s": 7933, "text": "It is used to estimate the coefficients of the features in the decision function. When the given problem is binary, it is of the shape (1, n_features)." }, { "code": null, "e": 8129, "s": 8085, "text": "Intercept_ − array, shape(1) or (n_classes)" }, { "code": null, "e": 8209, "s": 8129, "text": "It represents the constant, also known as bias, added to the decision function." }, { "code": null, "e": 8244, "s": 8209, "text": "classes_ − array, shape(n_classes)" }, { "code": null, "e": 8308, "s": 8244, "text": "It will provide a list of class labels known to the classifier." }, { "code": null, "e": 8350, "s": 8308, "text": "n_iter_ − array, shape (n_classes) or (1)" }, { "code": null, "e": 8414, "s": 8350, "text": "It returns the actual number of iterations for all the classes." }, { "code": null, "e": 8534, "s": 8414, "text": "Following Python script provides a simple example of implementing logistic regression on iris dataset of scikit-learn −" }, { "code": null, "e": 8801, "s": 8534, "text": "from sklearn import datasets\nfrom sklearn import linear_model\nfrom sklearn.datasets import load_iris\nX, y = load_iris(return_X_y = True)\nLRG = linear_model.LogisticRegression(\n random_state = 0,solver = 'liblinear',multi class = 'auto'\n)\n.fit(X, y)\nLRG.score(X, y)" }, { "code": null, "e": 8807, "s": 8801, "text": "0.96\n" }, { "code": null, "e": 8898, "s": 8807, "text": "The output shows that the above Logistic Regression model gave the accuracy of 96 percent." }, { "code": null, "e": 8931, "s": 8898, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 8948, "s": 8931, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 8955, "s": 8948, "text": " Print" }, { "code": null, "e": 8966, "s": 8955, "text": " Add Notes" } ]
Running COBOL Programs using JCL
In order to execute a COBOL program in batch mode using JCL, the program needs to be compiled and a load module is created with all the sub-programs. The JCL uses the load module and not the actual program at the time of execution. The load libraries are concatenated and given to the JCL at the time of execution using JCLLIB or STEPLIB. There are many mainframe compiler utilities available to compile a COBOL program. Some corporate companies use Change Management tools like Endevor, which compiles and stores every version of the program. This is useful in tracking the changes made to the program. //COMPILE JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID //* //STEP1 EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE //SYSIN DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR //SYSLIB DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR //SYSLMOD DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR //SYSPRINT DD SYSOUT=* //* IGYCRCTL is an IBM COBOL compiler utility. The compiler options are passed using PARM parameter. In the above example, RMODE instructs the compiler to use relative addressing mode in the program. The COBOL program is passed using SYSIN parameter and the copybook is the library used by the program in SYSLIB. This JCL produces the load module of the program as output which is used as the input to the execution JCL. Below a JCL example where the program MYPROG is executed using the input file MYDATA.URMI.INPUT and produces two output files written to the spool. //COBBSTEP JOB CLASS=6,NOTIFY=&SYSUID // //STEP10 EXEC PGM=MYPROG,PARM=ACCT5000 //STEPLIB DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR //INPUT1 DD DSN=MYDATA.URMI.INPUT,DISP=SHR //OUT1 DD SYSOUT=* //OUT2 DD SYSOUT=* //SYSIN DD * //CUST1 1000 //CUST2 1001 /* The load module of MYPROG is located in MYDATA.URMI.LOADLIB. This is important to note that the above JCL can be used for a non-DB2 COBOL module only. Data input to COBOL batch program can be through files, PARAM parameter and SYSIN DD statement. In the above example: Data records are passed to MYPROG through file MYDATA.URMI.INPUT. This file will be referred in the program using the DD name INPUT1. The file can be opened, read and closed in the program. Data records are passed to MYPROG through file MYDATA.URMI.INPUT. This file will be referred in the program using the DD name INPUT1. The file can be opened, read and closed in the program. The PARM parameter data ACCT5000 is received in the LINKAGE section of the program MYPROG in a variable defined within that section. The PARM parameter data ACCT5000 is received in the LINKAGE section of the program MYPROG in a variable defined within that section. The data in the SYSIN statement is received through ACCEPT statement in the PROCEDURE division of the program. Every ACCEPT statement reads one whole record (i.e., CUST1 1000) into a working storage variable defined in the program. The data in the SYSIN statement is received through ACCEPT statement in the PROCEDURE division of the program. Every ACCEPT statement reads one whole record (i.e., CUST1 1000) into a working storage variable defined in the program. For running COBOL DB2 program, specialised IBM utility is used in the JCL and program; DB2 region and required parameters are passed as input to the utility. The below steps are followed in running a COBOL-DB2 program: When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct. When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct. The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL. The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL. After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and DBRM library as the input to the JCL. After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and DBRM library as the input to the JCL. //STEP001 EXEC PGM=IKJEFT01 //* //STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR //* //input files //output files //SYSPRINT DD SYSOUT=* //SYSABOUT DD SYSOUT=* //SYSDBOUT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //DISPLAY DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSTSPRT DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(MYCOBB) PLAN(PLANNAME) PARM(parameters to cobol program) - LIB('MYDATA.URMI.LOADLIB') END /* In the above example, MYCOBB is the COBOL-DB2 program run using IKJEFT01. Please note that the program name, DB2 Sub-System Id (SSID), DB2 Plan name are passed within the SYSTSIN DD statement. The DBRM library is specified in the STEPLIB. 12 Lectures 2 hours Nishant Malik 73 Lectures 4.5 hours Topictrick Education Print Add Notes Bookmark this page
[ { "code": null, "e": 2203, "s": 1864, "text": "In order to execute a COBOL program in batch mode using JCL, the program needs to be compiled and a load module is created with all the sub-programs. The JCL uses the load module and not the actual program at the time of execution. The load libraries are concatenated and given to the JCL at the time of execution using JCLLIB or STEPLIB." }, { "code": null, "e": 2468, "s": 2203, "text": "There are many mainframe compiler utilities available to compile a COBOL program. Some corporate companies use Change Management tools like Endevor, which compiles and stores every version of the program. This is useful in tracking the changes made to the program." }, { "code": null, "e": 2793, "s": 2468, "text": "//COMPILE JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID \n//* \n//STEP1 EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE\n//SYSIN DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR\n//SYSLIB DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR\n//SYSLMOD DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR\n//SYSPRINT DD SYSOUT=*\n//*" }, { "code": null, "e": 3102, "s": 2793, "text": "IGYCRCTL is an IBM COBOL compiler utility. The compiler options are passed using PARM parameter. In the above example, RMODE instructs the compiler to use relative addressing mode in the program. The COBOL program is passed using SYSIN parameter and the copybook is the library used by the program in SYSLIB." }, { "code": null, "e": 3210, "s": 3102, "text": "This JCL produces the load module of the program as output which is used as the input to the execution JCL." }, { "code": null, "e": 3358, "s": 3210, "text": "Below a JCL example where the program MYPROG is executed using the input file MYDATA.URMI.INPUT and produces two output files written to the spool." }, { "code": null, "e": 3638, "s": 3358, "text": "//COBBSTEP JOB CLASS=6,NOTIFY=&SYSUID\n//\n//STEP10 EXEC PGM=MYPROG,PARM=ACCT5000\n//STEPLIB DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR\n//INPUT1 DD DSN=MYDATA.URMI.INPUT,DISP=SHR\n//OUT1 DD SYSOUT=*\n//OUT2 DD SYSOUT=*\n//SYSIN DD *\n//CUST1 1000\n//CUST2 1001\n/*" }, { "code": null, "e": 3789, "s": 3638, "text": "The load module of MYPROG is located in MYDATA.URMI.LOADLIB. This is important to note that the above JCL can be used for a non-DB2 COBOL module only." }, { "code": null, "e": 3907, "s": 3789, "text": "Data input to COBOL batch program can be through files, PARAM parameter and SYSIN DD statement. In the above example:" }, { "code": null, "e": 4097, "s": 3907, "text": "Data records are passed to MYPROG through file MYDATA.URMI.INPUT. This file will be referred in the program using the DD name INPUT1. The file can be opened, read and closed in the program." }, { "code": null, "e": 4287, "s": 4097, "text": "Data records are passed to MYPROG through file MYDATA.URMI.INPUT. This file will be referred in the program using the DD name INPUT1. The file can be opened, read and closed in the program." }, { "code": null, "e": 4420, "s": 4287, "text": "The PARM parameter data ACCT5000 is received in the LINKAGE section of the program MYPROG in a variable defined within that section." }, { "code": null, "e": 4553, "s": 4420, "text": "The PARM parameter data ACCT5000 is received in the LINKAGE section of the program MYPROG in a variable defined within that section." }, { "code": null, "e": 4785, "s": 4553, "text": "The data in the SYSIN statement is received through ACCEPT statement in the PROCEDURE division of the program. Every ACCEPT statement reads one whole record (i.e., CUST1 1000) into a working storage variable defined in the program." }, { "code": null, "e": 5017, "s": 4785, "text": "The data in the SYSIN statement is received through ACCEPT statement in the PROCEDURE division of the program. Every ACCEPT statement reads one whole record (i.e., CUST1 1000) into a working storage variable defined in the program." }, { "code": null, "e": 5175, "s": 5017, "text": "For running COBOL DB2 program, specialised IBM utility is used in the JCL and program; DB2 region and required parameters are passed as input to the utility." }, { "code": null, "e": 5236, "s": 5175, "text": "The below steps are followed in running a COBOL-DB2 program:" }, { "code": null, "e": 5444, "s": 5236, "text": "When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct." }, { "code": null, "e": 5652, "s": 5444, "text": "When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct." }, { "code": null, "e": 5785, "s": 5652, "text": "The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL." }, { "code": null, "e": 5918, "s": 5785, "text": "The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL." }, { "code": null, "e": 6055, "s": 5918, "text": "After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and DBRM library as the input to the JCL." }, { "code": null, "e": 6192, "s": 6055, "text": "After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and DBRM library as the input to the JCL." }, { "code": null, "e": 6620, "s": 6192, "text": "//STEP001 EXEC PGM=IKJEFT01\n//*\n//STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR\n//*\n//input files\n//output files\n//SYSPRINT DD SYSOUT=*\n//SYSABOUT DD SYSOUT=*\n//SYSDBOUT DD SYSOUT=*\n//SYSUDUMP DD SYSOUT=*\n//DISPLAY DD SYSOUT=*\n//SYSOUT DD SYSOUT=*\n//SYSTSPRT DD SYSOUT=*\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(MYCOBB) PLAN(PLANNAME) PARM(parameters to cobol program) -\n LIB('MYDATA.URMI.LOADLIB')\n END\n/*" }, { "code": null, "e": 6859, "s": 6620, "text": "In the above example, MYCOBB is the COBOL-DB2 program run using IKJEFT01. Please note that the program name, DB2 Sub-System Id (SSID), DB2 Plan name are passed within the SYSTSIN DD statement. The DBRM library is specified in the STEPLIB." }, { "code": null, "e": 6892, "s": 6859, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 6907, "s": 6892, "text": " Nishant Malik" }, { "code": null, "e": 6942, "s": 6907, "text": "\n 73 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6964, "s": 6942, "text": " Topictrick Education" }, { "code": null, "e": 6971, "s": 6964, "text": " Print" }, { "code": null, "e": 6982, "s": 6971, "text": " Add Notes" } ]
Multithreaded using the Pthreads API
Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization, which is a specification for thread behavior, not an implementation. This specification may be implemented by Operating-system designers in any way they wish. The C program shown in below, demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a nonnegative integer in a separate thread. Separate threads begin execution in a specified function, in a Pthreads program. In below program, this is the runner() function. When the program begins, a single thread of control begins in main(). main() creates a second thread that begins control in the runner() function, after some initialization. Both threads share the global data sum. the pthread.h header file must be included by all Pthreads programs. The identifier for the thread we will create. A set of attributes, including stack size and scheduling information are there in each thread. The attributes for the thread is represented by declaration of the pthread attr_t_attr. We set the attributes in the function call pthread attr init(&attr). Because we did not explicitly set any attributes, we use the default attributes provided. With the pthread create() function call, separate thread is created. To passing the thread identifier and the attributes for the thread, we also pass the runner() function, where the new thread will begin execution. At Last, we pass the integer parameter that was provided on the command line, argv[1]. At this point, the program has two threads: the initial (or parent) thread in main() and the summation (or child) thread performing the summation operation in the runner() function. This program follows the fork-join strategy: after creating the summation thread, the parent thread will wait for it to terminate by calling the pthread join() function. When it calls the function pthread exit(), when the summation thread will terminate .The parent thread will output the value of the shared data sum, once the summation thread has returned, #include<pthread.h> #include<stdio.h> int sum; /* This ‘sum’ is shared by the thread(s) */ void *runner(void *param); /* threads call this function */ int main(int argc, char *argv[]){ pthread t tid; /* the thread identifier */ pthread attr t attr; /* set of thread attributes */ if (argc != 2){ fprintf(stderr,"usage: a.out \n"); return -1; } if (atoi(argv[1]) < 0){ fprintf(stderr,"%d must be >= 0\n",atoi(argv[1])); return -1; } /* get the default attributes */ pthread attr init(&attr); /* create the thread */ pthread create(&tid,&attr,runner,argv[1]); /* wait for the thread to exit */ pthread join(tid,NULL); printf("sum = %d\n",sum); } /* The thread will begin handle in this function */ void *runner(void *param){ int i, upper = atoi(param); sum = 0; for (i = 1; i <= upper; i++) sum += i; pthread exit(0); }
[ { "code": null, "e": 3160, "s": 1062, "text": "Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization, which is a specification for thread behavior, not an implementation. This specification may be implemented by Operating-system designers in any way they wish. The C program shown in below, demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a nonnegative integer in a separate thread. Separate threads begin execution in a specified function, in a Pthreads program. In below program, this is the runner() function. When the program begins, a single thread of control begins in main(). main() creates a second thread that begins control in the runner() function, after some initialization. Both threads share the global data sum. the pthread.h header file must be included by all Pthreads programs. The identifier for the thread we will create. A set of attributes, including stack size and scheduling information are there in each thread. The attributes for the thread is represented by declaration of the pthread attr_t_attr. We set the attributes in the function call pthread attr init(&attr). Because we did not explicitly set any attributes, we use the default attributes provided. With the pthread create() function call, separate thread is created. To passing the thread identifier and the attributes for the thread, we also pass the runner() function, where the new thread will begin execution. At Last, we pass the integer parameter that was provided on the command line, argv[1]. At this point, the program has two threads: the initial (or parent) thread in main() and the summation (or child) thread performing the summation operation in the runner() function. This program follows the fork-join strategy: after creating the summation thread, the parent thread will wait for it to terminate by calling the pthread join() function. When it calls the function pthread exit(), when the summation thread will terminate .The parent thread will output the value of the shared data sum, once the summation thread has returned," }, { "code": null, "e": 4059, "s": 3160, "text": "#include<pthread.h>\n#include<stdio.h>\nint sum;\n/* This ‘sum’ is shared by the thread(s) */\nvoid *runner(void *param);\n/* threads call this function */\nint main(int argc, char *argv[]){\n pthread t tid;\n /* the thread identifier */\n pthread attr t attr;\n /* set of thread attributes */\n if (argc != 2){\n fprintf(stderr,\"usage: a.out \\n\");\n return -1;\n }\n if (atoi(argv[1]) < 0){\n fprintf(stderr,\"%d must be >= 0\\n\",atoi(argv[1])); return -1;\n }\n /* get the default attributes */\n pthread attr init(&attr);\n /* create the thread */\n pthread create(&tid,&attr,runner,argv[1]);\n /* wait for the thread to exit */\n pthread join(tid,NULL);\n printf(\"sum = %d\\n\",sum);\n}\n/* The thread will begin handle in this function */\nvoid *runner(void *param){\n int i, upper = atoi(param);\n sum = 0;\n for (i = 1; i <= upper; i++)\n sum += i;\n pthread exit(0);\n}" } ]
Batch Script - ASSOC
This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association. assoc – Displays all the file extensions assoc | find “.ext” – Displays only those file extensions which have the extension ext. @echo off assoc > C:\lists.txt assoc | find “.doc” > C:\listsdoc.txt The list of file associations will be routed to the file lists.txt. The following output shows what is there in the listsdoc.txt file after the above batch file is run. .doc=Word.Document.8 .dochtml=wordhtmlfile .docm=Word.DocumentMacroEnabled.12 .docmhtml=wordmhtmlfile .docx=Word.Document.12 .docxml=wordxmlfile Print Add Notes Bookmark this page
[ { "code": null, "e": 2307, "s": 2169, "text": "This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association." }, { "code": null, "e": 2438, "s": 2307, "text": "assoc – Displays all the file extensions \nassoc | find “.ext” – Displays only those file extensions which have the extension ext.\n" }, { "code": null, "e": 2509, "s": 2438, "text": "@echo off \nassoc > C:\\lists.txt \nassoc | find “.doc” > C:\\listsdoc.txt" }, { "code": null, "e": 2678, "s": 2509, "text": "The list of file associations will be routed to the file lists.txt. The following output shows what is there in the listsdoc.txt file after the above batch file is run." }, { "code": null, "e": 2829, "s": 2678, "text": ".doc=Word.Document.8 \n.dochtml=wordhtmlfile \n.docm=Word.DocumentMacroEnabled.12 \n.docmhtml=wordmhtmlfile \n.docx=Word.Document.12 \n.docxml=wordxmlfile\n" }, { "code": null, "e": 2836, "s": 2829, "text": " Print" }, { "code": null, "e": 2847, "s": 2836, "text": " Add Notes" } ]
Real Time Edge Detection in Browser | by Andrew Udell | Towards Data Science
Edge detection is a fundamental tool in computer vision. By using sharp contrasts in brightness, general outlines and shapes can be found in an image. Often used as a filter to find distinctions between items in a photo, edge detection offers a first stepping stone into object recognition. OpenCV offers a wide range of computer vision tools in C++, Java, Python, and JavaScript. Among them include an edge detection algorithm using the Canny method. Built with performance in mind, OpenCV’s implementation of edge detection can be interfaced with real time video with little to no noticeable latency. While many examples and tutorials exist in Python, there are fewer in JavaScript. With the increase portability of web technologies, now taking over space in desktop applications and even phone apps, it makes sense to cover the basics of using OpenCV in a web application. Named after its innovator John Canny, Canny edge detection tries to find edges such that: it finds as many edges in the image as possible,the edge point should localize on the center of the edge, andedges are only marked once and don’t include background noise it finds as many edges in the image as possible, the edge point should localize on the center of the edge, and edges are only marked once and don’t include background noise Developed in the early days of computer vision (1986), Canny edge detection is still the gold standard for cutting edge applications. For those few edge detection algorithms that perform better than Canny, they usually require more time and computational power, which make them poor candidates for real time detection. Luckily there’s no need to write an algorithm from scratch. OpenCV offers an efficient implementation of the Canny edge detection with a few simple lines of code. The mathematics of how the Canny method finds edges goes beyond the scope of this article, but further details may be found here. Before jumping into the JavaScript to apply edge detection, the proper elements must be set up on an HTML page. For real time detection to work OpenCV requires a video tag and two canvases. <!DOCTYPE html><html> <head> <Title> Real Time Edge Detection with OpenCV.js </Title> </head> <body> <video id="video" playsinline autoplay></video> <canvas id = "streamCanvas"></canvas> <canvas id = "edgeDetectionCanvas"></canvas> <script type="text/javascript" src="lib/CV2/opencv.js"></script> <script type="text/javascript" src="js/edgeDetection.js"></script> </body></html> The reason to include two canvases is because OpenCV can’t read frames from the video tag. Instead, a work around will be used to render frames from the video tags to the first canvas. This canvas will be known as the streamCanvas. Then the frames from the first canvas can be read and modified by OpenCV and rendered on the second canvas, named the edgeDetectionCanvas. Note that the opencv.js library is included in the first script tag. A copy may be found at “https://docs.opencv.org/{VERSION_NUMBER}/opencv.js". In this article, version 4.5.1 was used, which may be found here. // Set a variable for the video tagconst video = document.getElementById("video");// Function to stream video from the web camasync function streamVideo() { // Set video parameters const constraints = { // no audio is required audio: false, // Set the video size video: { width: 800, height: 400 } }; try { // Get the video stream const stream = await navigator.mediaDevices.getUserMedia(constraints); window.stream = stream; video.srcObject = stream; } catch (e) { alert("An error occurred while accessing the web cam."); } } The first line simply establishes a variable for the video tag, which will be used periodically through the program. Next, an asynchronous function is defined to stream video from a web cam to the video tag. Within this function, a set of video parameters are defined. The audio was set to False, because this is purely a visual demonstration and the width and height are defined accordingly. A try/catch actually encapsulates the code for streaming. If there’s some issue accessing the web cam or the user simply doesn’t have one, an alert will inform them. Otherwise the video from the camera will stream directly into the video tag without any further issues with the getUserMedia method. // Function to draw a video frame onto the canvasfunction drawCanvas() { // Get context and draw frame from video element var canvas = document.getElementById("streamCanvas") var ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0); } Another function is defined to draw a frame from the video tag onto one of the canvases. Within it, the “streamCanvas” is defined and the canvas is specified as a 2D canvas (as opposed to 3D renderings which are also possible). Finally, the image is drawn from the video tag. The pair of 0’s in the drawImage method simply specify to draw the image at coordinate (0,0) on the canvas. function edgeDetection() { // Start video stream streamVideo(); // Set interval to repeat function every 42 milliseconds setInterval(() => { // Draw frame to the intermediate canvas drawCanvas(); // Get the current frame from the intermediate canvas var src = cv.imread("streamCanvas"); cv.cvtColor(src, src, cv.COLOR_RGB2GRAY, 0); cv.Canny(src, src, 50, 100, 3, false); cv.imshow("edgeDetectionCanvas", src); src.delete(); }, 42);} The actual function for edge detection is defined here. Before doing anything, the function streamVideo is called, so that video will be streamed to the video tag immediately. The setInterval function repeats its contents at a defined interval. In this case, it’s set at 42 milliseconds, because it corresponds to about 24 repetitions per second. When drawCanvas is called, then, it draws the video at 24 frames per second. OpenCV is finally used, starting with the imread command, which simply captures the current frame on the streamCanvas. The next line converts the color image into a black and white image. The following line actually applies the Canny edge detection. Notes the 50 and 100 in the parameters of the Canny function. These are defined as the minimum and maximum values, respectively. Any edges with an intensity above the maximum value are immediately classified as edges. Any edges with an intensity below the minimum value are immediately classified as non-edges. Intensities between the two values are judged based on connectivity to determine its status as an edge. Finally, the imshow method renders the newly modified frame to the edgeDetectionCanvas and the source of the frame is deleted to free up memory. A more thorough explanation may be found in the official documentation here. // main function to clean upfunction main() { // Hide the video tag video.style.display = "none"; // Run edge detection edgeDetection();}// Load mainmain(); In a final clean up, a main function is defined which hides the video tag and runs the edge detection. This will leave the two canvases side-by-side, so that the difference between the regular streamed video and the edge detection may be clearly seen. OpenCV provides an incredibly powerful toolset for computer vision. With an emphasis on real time application, OpenCV provides a valuable asset to anyone interested in gaining insight from images. The use of the Canny Edge detection is the basis for many other computer vision applications, such as background removal and object detection and recognition. Understanding the fundamentals will provide a basis for more complex computer vision tasks.
[ { "code": null, "e": 338, "s": 47, "text": "Edge detection is a fundamental tool in computer vision. By using sharp contrasts in brightness, general outlines and shapes can be found in an image. Often used as a filter to find distinctions between items in a photo, edge detection offers a first stepping stone into object recognition." }, { "code": null, "e": 650, "s": 338, "text": "OpenCV offers a wide range of computer vision tools in C++, Java, Python, and JavaScript. Among them include an edge detection algorithm using the Canny method. Built with performance in mind, OpenCV’s implementation of edge detection can be interfaced with real time video with little to no noticeable latency." }, { "code": null, "e": 923, "s": 650, "text": "While many examples and tutorials exist in Python, there are fewer in JavaScript. With the increase portability of web technologies, now taking over space in desktop applications and even phone apps, it makes sense to cover the basics of using OpenCV in a web application." }, { "code": null, "e": 1013, "s": 923, "text": "Named after its innovator John Canny, Canny edge detection tries to find edges such that:" }, { "code": null, "e": 1184, "s": 1013, "text": "it finds as many edges in the image as possible,the edge point should localize on the center of the edge, andedges are only marked once and don’t include background noise" }, { "code": null, "e": 1233, "s": 1184, "text": "it finds as many edges in the image as possible," }, { "code": null, "e": 1295, "s": 1233, "text": "the edge point should localize on the center of the edge, and" }, { "code": null, "e": 1357, "s": 1295, "text": "edges are only marked once and don’t include background noise" }, { "code": null, "e": 1676, "s": 1357, "text": "Developed in the early days of computer vision (1986), Canny edge detection is still the gold standard for cutting edge applications. For those few edge detection algorithms that perform better than Canny, they usually require more time and computational power, which make them poor candidates for real time detection." }, { "code": null, "e": 1839, "s": 1676, "text": "Luckily there’s no need to write an algorithm from scratch. OpenCV offers an efficient implementation of the Canny edge detection with a few simple lines of code." }, { "code": null, "e": 1969, "s": 1839, "text": "The mathematics of how the Canny method finds edges goes beyond the scope of this article, but further details may be found here." }, { "code": null, "e": 2159, "s": 1969, "text": "Before jumping into the JavaScript to apply edge detection, the proper elements must be set up on an HTML page. For real time detection to work OpenCV requires a video tag and two canvases." }, { "code": null, "e": 2618, "s": 2159, "text": "<!DOCTYPE html><html> <head> <Title> Real Time Edge Detection with OpenCV.js </Title> </head> <body> <video id=\"video\" playsinline autoplay></video> <canvas id = \"streamCanvas\"></canvas> <canvas id = \"edgeDetectionCanvas\"></canvas> <script type=\"text/javascript\" src=\"lib/CV2/opencv.js\"></script> <script type=\"text/javascript\" src=\"js/edgeDetection.js\"></script> </body></html>" }, { "code": null, "e": 2989, "s": 2618, "text": "The reason to include two canvases is because OpenCV can’t read frames from the video tag. Instead, a work around will be used to render frames from the video tags to the first canvas. This canvas will be known as the streamCanvas. Then the frames from the first canvas can be read and modified by OpenCV and rendered on the second canvas, named the edgeDetectionCanvas." }, { "code": null, "e": 3201, "s": 2989, "text": "Note that the opencv.js library is included in the first script tag. A copy may be found at “https://docs.opencv.org/{VERSION_NUMBER}/opencv.js\". In this article, version 4.5.1 was used, which may be found here." }, { "code": null, "e": 3851, "s": 3201, "text": "// Set a variable for the video tagconst video = document.getElementById(\"video\");// Function to stream video from the web camasync function streamVideo() { // Set video parameters const constraints = { // no audio is required audio: false, // Set the video size video: { width: 800, height: 400 } }; try { // Get the video stream const stream = await navigator.mediaDevices.getUserMedia(constraints); window.stream = stream; video.srcObject = stream; } catch (e) { alert(\"An error occurred while accessing the web cam.\"); } }" }, { "code": null, "e": 3968, "s": 3851, "text": "The first line simply establishes a variable for the video tag, which will be used periodically through the program." }, { "code": null, "e": 4244, "s": 3968, "text": "Next, an asynchronous function is defined to stream video from a web cam to the video tag. Within this function, a set of video parameters are defined. The audio was set to False, because this is purely a visual demonstration and the width and height are defined accordingly." }, { "code": null, "e": 4543, "s": 4244, "text": "A try/catch actually encapsulates the code for streaming. If there’s some issue accessing the web cam or the user simply doesn’t have one, an alert will inform them. Otherwise the video from the camera will stream directly into the video tag without any further issues with the getUserMedia method." }, { "code": null, "e": 4795, "s": 4543, "text": "// Function to draw a video frame onto the canvasfunction drawCanvas() { // Get context and draw frame from video element var canvas = document.getElementById(\"streamCanvas\") var ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0); }" }, { "code": null, "e": 5023, "s": 4795, "text": "Another function is defined to draw a frame from the video tag onto one of the canvases. Within it, the “streamCanvas” is defined and the canvas is specified as a 2D canvas (as opposed to 3D renderings which are also possible)." }, { "code": null, "e": 5179, "s": 5023, "text": "Finally, the image is drawn from the video tag. The pair of 0’s in the drawImage method simply specify to draw the image at coordinate (0,0) on the canvas." }, { "code": null, "e": 5699, "s": 5179, "text": "function edgeDetection() { // Start video stream streamVideo(); // Set interval to repeat function every 42 milliseconds setInterval(() => { // Draw frame to the intermediate canvas drawCanvas(); // Get the current frame from the intermediate canvas var src = cv.imread(\"streamCanvas\"); cv.cvtColor(src, src, cv.COLOR_RGB2GRAY, 0); cv.Canny(src, src, 50, 100, 3, false); cv.imshow(\"edgeDetectionCanvas\", src); src.delete(); }, 42);}" }, { "code": null, "e": 5875, "s": 5699, "text": "The actual function for edge detection is defined here. Before doing anything, the function streamVideo is called, so that video will be streamed to the video tag immediately." }, { "code": null, "e": 6123, "s": 5875, "text": "The setInterval function repeats its contents at a defined interval. In this case, it’s set at 42 milliseconds, because it corresponds to about 24 repetitions per second. When drawCanvas is called, then, it draws the video at 24 frames per second." }, { "code": null, "e": 6373, "s": 6123, "text": "OpenCV is finally used, starting with the imread command, which simply captures the current frame on the streamCanvas. The next line converts the color image into a black and white image. The following line actually applies the Canny edge detection." }, { "code": null, "e": 6788, "s": 6373, "text": "Notes the 50 and 100 in the parameters of the Canny function. These are defined as the minimum and maximum values, respectively. Any edges with an intensity above the maximum value are immediately classified as edges. Any edges with an intensity below the minimum value are immediately classified as non-edges. Intensities between the two values are judged based on connectivity to determine its status as an edge." }, { "code": null, "e": 6933, "s": 6788, "text": "Finally, the imshow method renders the newly modified frame to the edgeDetectionCanvas and the source of the frame is deleted to free up memory." }, { "code": null, "e": 7010, "s": 6933, "text": "A more thorough explanation may be found in the official documentation here." }, { "code": null, "e": 7179, "s": 7010, "text": "// main function to clean upfunction main() { // Hide the video tag video.style.display = \"none\"; // Run edge detection edgeDetection();}// Load mainmain();" }, { "code": null, "e": 7431, "s": 7179, "text": "In a final clean up, a main function is defined which hides the video tag and runs the edge detection. This will leave the two canvases side-by-side, so that the difference between the regular streamed video and the edge detection may be clearly seen." }, { "code": null, "e": 7628, "s": 7431, "text": "OpenCV provides an incredibly powerful toolset for computer vision. With an emphasis on real time application, OpenCV provides a valuable asset to anyone interested in gaining insight from images." } ]
NLP in the Financial Market — Sentiment Analysis | by Yuki Takahashi | Towards Data Science
Deep learning in Computer Vision has been successfully adopted in a variety of applications since a pioneer CNN called AlexNet on ImageNet in 2012. On the contrary, NLP has been behind in terms of the deep neural network utilisation. A lot of applications which claim the use of AI often use some sort of rule-based algorithm and traditional machine learning rather than deep neural networks. In 2018 saw a state-of-the-art (STOA) model called BERT outperformed human scores in some NLP tasks. Here, I apply several models for a sentiment analysis task to see how useful they are in the financial market where I’m from. The code is in jupyter notebook and available in git repo. NLP tasks can be broadly categorised as follows. Text Classification — filtering spam emails, categorising documentsWord Sequence — word translation, POS tags, named entity recognitionText Meaning — topic modelling, search, question answeringSequence to Sequence —machine translation, text summarisation, Q&ADialog Systems Text Classification — filtering spam emails, categorising documents Word Sequence — word translation, POS tags, named entity recognition Text Meaning — topic modelling, search, question answering Sequence to Sequence —machine translation, text summarisation, Q&A Dialog Systems Different approaches will be required for different tasks and in most case are the combination of multiple NLP techniques. When developing a bot, the backend logic is often a rule based search engine and ranking algorithms to form a natural communication. There is a good reason for this. The language has grammar and word orders, which could be better handled by a rule-based approach, while machine learning approach could learn collocations and word similarities better. Vectorisation techniques such as word2vec, bag-of-word help the model to express a text in mathematical way. The most famous examples are: King - Man + Woman = QueenParis - France + UK = London The first example describes the gender relationship and the second captures the concept of capital city. In these approaches, however, the context are not captured as the same word is always represented by the same vector in any text, which is not true in many cases. Recurrent Neural Network (RNN) architecture, which uses the previous information from input sequence and handles time series data, performed well in capturing and remembering the context. One of the typical architecture is Long short-term memory (LSTM), which is composed of input gate, output gate and forget gate to overcome the varnishing gradient problem of RNN. The are many improved models based on LSTM, such as bidirectional LSTM to capture the context not only from preceding words but also from backwards. These were good for some specific tasks but not quite in practical applications. In 2017 saw a new approach to tackle the problem without recurrent nor convolution architecture. Attention is All You Need proposes a transformer architecture, which is encoder-decoder stack based on attention mechanism. Bidirectional Encoder Representations from Transformers (BERT), is a masked language model with multiple encoder stack by Google in 2018, which achieved STOA in GLUE, SQuAD and SWAG benchmarks with a big improvement. There are a number of articles and blogs explaining the architecture, such as the one by Jay Alammar. Working in the financial industry, I struggled to see the sufficient robust performance in our past R&D of machine learning models on NLP for the production use in trading systems over the past few years. Now that BERT based models are getting matured and easy to use thanks to Huggingface implementation and many pre-trained models have been made public. My goal is to see if this latest development in NLP reaches a good level to use in my domain. In this post, I compare different models on a rather simple task of the sentiment analysis on financial texts as a baseline to judge if it’s worth trying another R&D in a real solution. Models compared here are: Rule based approach using LexiconTraditional Machine Learning approach using TfidfLSTM as a Recurrent Neural Network architectureBERT (and ALBERT) Rule based approach using Lexicon Traditional Machine Learning approach using Tfidf LSTM as a Recurrent Neural Network architecture BERT (and ALBERT) I took the following two inputs to represent different languages in the industry for the sentiment analysis task. Financial Headlines as more formal styleTweets from Stocktwits as trader informal talk Financial Headlines as more formal style Tweets from Stocktwits as trader informal talk I will write another post for the latter, so focus on the former data here. It is an example of texts containing more formal financial domain specific languages and I used FinancialPhraseBank by Malo et al. (2014), which consist of 4845 hand labeled headline texts by 16 persons and provided with agree level. I used 75% agreed labels with 3448 texts as training data. ## Input text samplespositive "Finnish steel maker Rautaruukki Oyj ( Ruukki ) said on July 7 , 2008 that it won a 9.0 mln euro ( $ 14.1 mln ) contract to supply and install steel superstructures for Partihallsforbindelsen bridge project in Gothenburg , western Sweden."neutral "In 2008 , the steel industry accounted for 64 percent of the cargo volumes transported , whereas the energy industry accounted for 28 percent and other industries for 8 percent."negative "The period-end cash and cash equivalents totaled EUR6 .5 m , compared to EUR10 .5 m in the previous year." Please be noted that all the data belong to the sources and people must honour their copyright and the licence terms. Here are the four models I compared the performance. Creating domain specific dictionaries is a traditional approach and simple yet strong in some cases where the source is from a particular person or media. Loughran and McDonald Sentiment Word Lists. This list contains more than 4k words which appears on financial statements with sentiment labels. Note: This data requires the license to use for commercial application. Please check their website before use. ## Samplenegative: ABANDONnegative: ABANDONEDconstraining: STRICTLY I used negative 2355 words and positive 354 words. It includes the word form, so do not perform stemming and lemmatisation on the input. It is important to consider negation for this kind of approach. Words such as not, no, don’t, etc. change the meaning of negative words to positive and here I simply flip the sentiment if one of negate words occurring within three words preceding a positive words. Then, the tone score is defined as follows and fed into classifiers along the positive/negative counts. tone_score = 100 * (pos_count — neg_count) / word_count 14 different classifier were trained with default parameters, then used grid search cross validation for hyper-parameter tuning of Random Forest. The inputs were tokenized by NLTK word_tokenize(), then lemmatised and stop words were removed. Then fed into TfidfVectorizer and classified by Logistic Regression and Random Forest Classifier. As LSTM is designed to remember long-term memory which expresses the context, used a custom tokenizer to extract alphabetical letters as they are without lemmatisation or stop word removal. Then the inputs were fed into an embedding layer, then two lstm layer. To avoid overfitting, apply dropout as is often the case, then fully-connected layers and finally take the log softmax. As alternative, also tried GloVe word embedding from Stanford, which is an unsupervised learning algorithm for obtaining vector representations for words. Here, took the pre-trained on Wikipedia and Gigawords with 6B tokens, 400k vocab size and 300 dimentional vectors. Around 90% of words in our vocab were found in this GloVe vocab and the rest are initialised randomly. I used pytorch implementation of BERT model by transformers from Huggingface. Now (v3) they provide tokenizer as well as encoder which generate text ids, pad masks and segment ids that can be directly used in their BertModel and no custom implementation was necessary for a standard training process. Similarly to the LSTM model, the output from BERT is then passed to drop-out, fully-connected layters and then apply log softmax. Training the model from scratch is not an option without enough budget for computation resource and also no enough data, so I used pre-trained models and fine tuned. The pre-trained models used as as follows: BERT: bert-base-uncased ALBERT: albert-base-v2 Training process with the pre-trained bert looks like this. First, input data are split to train set and test set at 8:2. The test set is kept untouched until all parameters are fixed and used only once for each model. As the dataset is not large, cross validation is used to evaluate the parameter sets. In addition, to overcome the issue of imbalanced and smaller dataset, Stratified K-Fold Cross Validation is applied for hyper-parameter tuning. Evaluation is based F1 score as the input data are imbalanced, while the accuracy is also referred. Grid Search Cross Validation is used for Model A and B, whereas custom Cross Validation is performed for Deep Neural Network models of C and D. Fine tuned BERT based models clearly outperform the other models after spending more or less similar time in hyper-parameter tuning. Model A didn’t perform well because the input was too simplified as tone score, which is a single value judging the sentiment, and the random forest model ended up labelling the majority class of neutral to most of data. Simple linear model performed better by just applying threshold to tone score but still quite low in both accuracy and f1 score. We didn’t balance the input data using methods like under/over-sampling or SMOTE because it can rectify this issue but would deviate from the actual situation where the imbalance exists. Potential improvement to this model is to build a custom lexicon instead of L-M dictionary if the cost can be justified to build a lexicon per problem to solve. More complex negation could also improve the accuracy of the prediction. Model B was muchbetter than the previous model, but it overfits to the training set with almost 100% of accuracy and f1 score and failed to be generalised. I tried to reduce the model complexity to avoid overfitting but it ended up lower score in validation set. The balancing data could help solve this issue or collect much more data. Model C produced a similar result to the previous model but not improved much. In fact, the number of training data were insufficient to train the neural network from scratch and needed to a number of epochs, which tends to overfit. The pre-trained GloVe embedding does not improve the result. One possible improvement on this latter model is to train the GloVe using a bunch of text from similar domain such as 10K, 10Q financial statements instead of using pre-trained model from wikipedia. Model D performed quite well with more than 90% in both accuracy and f1 score in cross validation as well as final test. It correctly classify negative texts at 84% whereas positive texts at 94%, which could be due to the number of inputs but better to look closely to improve the performance further. This indicates the fine tuning of the pre-trained model performs well on this small data set thanks to transfer learning and the language model. This experiment shows the potential of BERT based model application to my domain where previous models have failed to produce sufficient performance. The result is, however, not deterministic and based on a rather simple manual hyperparameter tuning on free-tier GPU and it could be different depending on the input data and tuning approaches. It is also worth noting that in practical application, getting the proper input data is also quite important. The model cannot be trained well without data with good quality as often referred to as “garbage in, garbage out”. I will cover these points next time. All the code used here are available in git repo.
[ { "code": null, "e": 850, "s": 171, "text": "Deep learning in Computer Vision has been successfully adopted in a variety of applications since a pioneer CNN called AlexNet on ImageNet in 2012. On the contrary, NLP has been behind in terms of the deep neural network utilisation. A lot of applications which claim the use of AI often use some sort of rule-based algorithm and traditional machine learning rather than deep neural networks. In 2018 saw a state-of-the-art (STOA) model called BERT outperformed human scores in some NLP tasks. Here, I apply several models for a sentiment analysis task to see how useful they are in the financial market where I’m from. The code is in jupyter notebook and available in git repo." }, { "code": null, "e": 899, "s": 850, "text": "NLP tasks can be broadly categorised as follows." }, { "code": null, "e": 1173, "s": 899, "text": "Text Classification — filtering spam emails, categorising documentsWord Sequence — word translation, POS tags, named entity recognitionText Meaning — topic modelling, search, question answeringSequence to Sequence —machine translation, text summarisation, Q&ADialog Systems" }, { "code": null, "e": 1241, "s": 1173, "text": "Text Classification — filtering spam emails, categorising documents" }, { "code": null, "e": 1310, "s": 1241, "text": "Word Sequence — word translation, POS tags, named entity recognition" }, { "code": null, "e": 1369, "s": 1310, "text": "Text Meaning — topic modelling, search, question answering" }, { "code": null, "e": 1436, "s": 1369, "text": "Sequence to Sequence —machine translation, text summarisation, Q&A" }, { "code": null, "e": 1451, "s": 1436, "text": "Dialog Systems" }, { "code": null, "e": 1707, "s": 1451, "text": "Different approaches will be required for different tasks and in most case are the combination of multiple NLP techniques. When developing a bot, the backend logic is often a rule based search engine and ranking algorithms to form a natural communication." }, { "code": null, "e": 2064, "s": 1707, "text": "There is a good reason for this. The language has grammar and word orders, which could be better handled by a rule-based approach, while machine learning approach could learn collocations and word similarities better. Vectorisation techniques such as word2vec, bag-of-word help the model to express a text in mathematical way. The most famous examples are:" }, { "code": null, "e": 2119, "s": 2064, "text": "King - Man + Woman = QueenParis - France + UK = London" }, { "code": null, "e": 2984, "s": 2119, "text": "The first example describes the gender relationship and the second captures the concept of capital city. In these approaches, however, the context are not captured as the same word is always represented by the same vector in any text, which is not true in many cases. Recurrent Neural Network (RNN) architecture, which uses the previous information from input sequence and handles time series data, performed well in capturing and remembering the context. One of the typical architecture is Long short-term memory (LSTM), which is composed of input gate, output gate and forget gate to overcome the varnishing gradient problem of RNN. The are many improved models based on LSTM, such as bidirectional LSTM to capture the context not only from preceding words but also from backwards. These were good for some specific tasks but not quite in practical applications." }, { "code": null, "e": 3524, "s": 2984, "text": "In 2017 saw a new approach to tackle the problem without recurrent nor convolution architecture. Attention is All You Need proposes a transformer architecture, which is encoder-decoder stack based on attention mechanism. Bidirectional Encoder Representations from Transformers (BERT), is a masked language model with multiple encoder stack by Google in 2018, which achieved STOA in GLUE, SQuAD and SWAG benchmarks with a big improvement. There are a number of articles and blogs explaining the architecture, such as the one by Jay Alammar." }, { "code": null, "e": 4160, "s": 3524, "text": "Working in the financial industry, I struggled to see the sufficient robust performance in our past R&D of machine learning models on NLP for the production use in trading systems over the past few years. Now that BERT based models are getting matured and easy to use thanks to Huggingface implementation and many pre-trained models have been made public. My goal is to see if this latest development in NLP reaches a good level to use in my domain. In this post, I compare different models on a rather simple task of the sentiment analysis on financial texts as a baseline to judge if it’s worth trying another R&D in a real solution." }, { "code": null, "e": 4186, "s": 4160, "text": "Models compared here are:" }, { "code": null, "e": 4333, "s": 4186, "text": "Rule based approach using LexiconTraditional Machine Learning approach using TfidfLSTM as a Recurrent Neural Network architectureBERT (and ALBERT)" }, { "code": null, "e": 4367, "s": 4333, "text": "Rule based approach using Lexicon" }, { "code": null, "e": 4417, "s": 4367, "text": "Traditional Machine Learning approach using Tfidf" }, { "code": null, "e": 4465, "s": 4417, "text": "LSTM as a Recurrent Neural Network architecture" }, { "code": null, "e": 4483, "s": 4465, "text": "BERT (and ALBERT)" }, { "code": null, "e": 4597, "s": 4483, "text": "I took the following two inputs to represent different languages in the industry for the sentiment analysis task." }, { "code": null, "e": 4684, "s": 4597, "text": "Financial Headlines as more formal styleTweets from Stocktwits as trader informal talk" }, { "code": null, "e": 4725, "s": 4684, "text": "Financial Headlines as more formal style" }, { "code": null, "e": 4772, "s": 4725, "text": "Tweets from Stocktwits as trader informal talk" }, { "code": null, "e": 5141, "s": 4772, "text": "I will write another post for the latter, so focus on the former data here. It is an example of texts containing more formal financial domain specific languages and I used FinancialPhraseBank by Malo et al. (2014), which consist of 4845 hand labeled headline texts by 16 persons and provided with agree level. I used 75% agreed labels with 3448 texts as training data." }, { "code": null, "e": 5714, "s": 5141, "text": "## Input text samplespositive \"Finnish steel maker Rautaruukki Oyj ( Ruukki ) said on July 7 , 2008 that it won a 9.0 mln euro ( $ 14.1 mln ) contract to supply and install steel superstructures for Partihallsforbindelsen bridge project in Gothenburg , western Sweden.\"neutral \"In 2008 , the steel industry accounted for 64 percent of the cargo volumes transported , whereas the energy industry accounted for 28 percent and other industries for 8 percent.\"negative \"The period-end cash and cash equivalents totaled EUR6 .5 m , compared to EUR10 .5 m in the previous year.\"" }, { "code": null, "e": 5832, "s": 5714, "text": "Please be noted that all the data belong to the sources and people must honour their copyright and the licence terms." }, { "code": null, "e": 5885, "s": 5832, "text": "Here are the four models I compared the performance." }, { "code": null, "e": 6294, "s": 5885, "text": "Creating domain specific dictionaries is a traditional approach and simple yet strong in some cases where the source is from a particular person or media. Loughran and McDonald Sentiment Word Lists. This list contains more than 4k words which appears on financial statements with sentiment labels. Note: This data requires the license to use for commercial application. Please check their website before use." }, { "code": null, "e": 6362, "s": 6294, "text": "## Samplenegative: ABANDONnegative: ABANDONEDconstraining: STRICTLY" }, { "code": null, "e": 6764, "s": 6362, "text": "I used negative 2355 words and positive 354 words. It includes the word form, so do not perform stemming and lemmatisation on the input. It is important to consider negation for this kind of approach. Words such as not, no, don’t, etc. change the meaning of negative words to positive and here I simply flip the sentiment if one of negate words occurring within three words preceding a positive words." }, { "code": null, "e": 6868, "s": 6764, "text": "Then, the tone score is defined as follows and fed into classifiers along the positive/negative counts." }, { "code": null, "e": 6924, "s": 6868, "text": "tone_score = 100 * (pos_count — neg_count) / word_count" }, { "code": null, "e": 7070, "s": 6924, "text": "14 different classifier were trained with default parameters, then used grid search cross validation for hyper-parameter tuning of Random Forest." }, { "code": null, "e": 7264, "s": 7070, "text": "The inputs were tokenized by NLTK word_tokenize(), then lemmatised and stop words were removed. Then fed into TfidfVectorizer and classified by Logistic Regression and Random Forest Classifier." }, { "code": null, "e": 7645, "s": 7264, "text": "As LSTM is designed to remember long-term memory which expresses the context, used a custom tokenizer to extract alphabetical letters as they are without lemmatisation or stop word removal. Then the inputs were fed into an embedding layer, then two lstm layer. To avoid overfitting, apply dropout as is often the case, then fully-connected layers and finally take the log softmax." }, { "code": null, "e": 8018, "s": 7645, "text": "As alternative, also tried GloVe word embedding from Stanford, which is an unsupervised learning algorithm for obtaining vector representations for words. Here, took the pre-trained on Wikipedia and Gigawords with 6B tokens, 400k vocab size and 300 dimentional vectors. Around 90% of words in our vocab were found in this GloVe vocab and the rest are initialised randomly." }, { "code": null, "e": 8319, "s": 8018, "text": "I used pytorch implementation of BERT model by transformers from Huggingface. Now (v3) they provide tokenizer as well as encoder which generate text ids, pad masks and segment ids that can be directly used in their BertModel and no custom implementation was necessary for a standard training process." }, { "code": null, "e": 8658, "s": 8319, "text": "Similarly to the LSTM model, the output from BERT is then passed to drop-out, fully-connected layters and then apply log softmax. Training the model from scratch is not an option without enough budget for computation resource and also no enough data, so I used pre-trained models and fine tuned. The pre-trained models used as as follows:" }, { "code": null, "e": 8682, "s": 8658, "text": "BERT: bert-base-uncased" }, { "code": null, "e": 8705, "s": 8682, "text": "ALBERT: albert-base-v2" }, { "code": null, "e": 8765, "s": 8705, "text": "Training process with the pre-trained bert looks like this." }, { "code": null, "e": 9154, "s": 8765, "text": "First, input data are split to train set and test set at 8:2. The test set is kept untouched until all parameters are fixed and used only once for each model. As the dataset is not large, cross validation is used to evaluate the parameter sets. In addition, to overcome the issue of imbalanced and smaller dataset, Stratified K-Fold Cross Validation is applied for hyper-parameter tuning." }, { "code": null, "e": 9254, "s": 9154, "text": "Evaluation is based F1 score as the input data are imbalanced, while the accuracy is also referred." }, { "code": null, "e": 9398, "s": 9254, "text": "Grid Search Cross Validation is used for Model A and B, whereas custom Cross Validation is performed for Deep Neural Network models of C and D." }, { "code": null, "e": 9531, "s": 9398, "text": "Fine tuned BERT based models clearly outperform the other models after spending more or less similar time in hyper-parameter tuning." }, { "code": null, "e": 9881, "s": 9531, "text": "Model A didn’t perform well because the input was too simplified as tone score, which is a single value judging the sentiment, and the random forest model ended up labelling the majority class of neutral to most of data. Simple linear model performed better by just applying threshold to tone score but still quite low in both accuracy and f1 score." }, { "code": null, "e": 10302, "s": 9881, "text": "We didn’t balance the input data using methods like under/over-sampling or SMOTE because it can rectify this issue but would deviate from the actual situation where the imbalance exists. Potential improvement to this model is to build a custom lexicon instead of L-M dictionary if the cost can be justified to build a lexicon per problem to solve. More complex negation could also improve the accuracy of the prediction." }, { "code": null, "e": 10639, "s": 10302, "text": "Model B was muchbetter than the previous model, but it overfits to the training set with almost 100% of accuracy and f1 score and failed to be generalised. I tried to reduce the model complexity to avoid overfitting but it ended up lower score in validation set. The balancing data could help solve this issue or collect much more data." }, { "code": null, "e": 11132, "s": 10639, "text": "Model C produced a similar result to the previous model but not improved much. In fact, the number of training data were insufficient to train the neural network from scratch and needed to a number of epochs, which tends to overfit. The pre-trained GloVe embedding does not improve the result. One possible improvement on this latter model is to train the GloVe using a bunch of text from similar domain such as 10K, 10Q financial statements instead of using pre-trained model from wikipedia." }, { "code": null, "e": 11579, "s": 11132, "text": "Model D performed quite well with more than 90% in both accuracy and f1 score in cross validation as well as final test. It correctly classify negative texts at 84% whereas positive texts at 94%, which could be due to the number of inputs but better to look closely to improve the performance further. This indicates the fine tuning of the pre-trained model performs well on this small data set thanks to transfer learning and the language model." }, { "code": null, "e": 11923, "s": 11579, "text": "This experiment shows the potential of BERT based model application to my domain where previous models have failed to produce sufficient performance. The result is, however, not deterministic and based on a rather simple manual hyperparameter tuning on free-tier GPU and it could be different depending on the input data and tuning approaches." }, { "code": null, "e": 12148, "s": 11923, "text": "It is also worth noting that in practical application, getting the proper input data is also quite important. The model cannot be trained well without data with good quality as often referred to as “garbage in, garbage out”." } ]
How to add items/elements to an existing jagged array in C#?
To add an element to existing jagged array, just set the value of the element with a new value. Let’s say you need to add an element at the following location − a[3][1] Just set the value − a[3][1] = 500; Above, we accessed the first element of the 3rd array in a jagged array. Let us see the complete code − using System; namespace Demo { class Program { static void Main(string[] args) { int[][] x = new int[][]{new int[]{10,20},new int[]{30,40}, new int[]{50,60},new int[]{ 70, 80 }, new int[]{ 90, 100 } }; int i, j; Console.WriteLine("Old Array..."); for (i = 0; i < 5; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0}][{1}] = {2}", i, j, x[i][j]); } } x[3][1] = 500; Console.WriteLine("New Array..."); for (i = 0; i < 5; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0}][{1}] = {2}", i, j, x[i][j]); } } Console.ReadKey(); } } }
[ { "code": null, "e": 1158, "s": 1062, "text": "To add an element to existing jagged array, just set the value of the element with a new value." }, { "code": null, "e": 1223, "s": 1158, "text": "Let’s say you need to add an element at the following location −" }, { "code": null, "e": 1231, "s": 1223, "text": "a[3][1]" }, { "code": null, "e": 1252, "s": 1231, "text": "Just set the value −" }, { "code": null, "e": 1267, "s": 1252, "text": "a[3][1] = 500;" }, { "code": null, "e": 1340, "s": 1267, "text": "Above, we accessed the first element of the 3rd array in a jagged array." }, { "code": null, "e": 1371, "s": 1340, "text": "Let us see the complete code −" }, { "code": null, "e": 2106, "s": 1371, "text": "using System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n\n int[][] x = new int[][]{new int[]{10,20},new int[]{30,40}, new int[]{50,60},new int[]{ 70, 80 }, new int[]{ 90, 100 } };\n int i, j;\n\n Console.WriteLine(\"Old Array...\");\n for (i = 0; i < 5; i++) {\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0}][{1}] = {2}\", i, j, x[i][j]);\n }\n }\n\n x[3][1] = 500;\n\n Console.WriteLine(\"New Array...\");\n for (i = 0; i < 5; i++) {\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0}][{1}] = {2}\", i, j, x[i][j]);\n }\n }\n Console.ReadKey();\n }\n }\n}" } ]
PHP - Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies. There are three steps involved in identifying returning users − Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Browser stores this information on local machine for future use. Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. This chapter will teach you how to set cookies, how to access them and how to delete them. Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser's headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"]. PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately. setcookie(name, value, expire, path, domain, security); Here is the detail of all the arguments − Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies. Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies. Value − This sets the value of the named variable and is the content that you actually want to store. Value − This sets the value of the named variable and is the content that you actually want to store. Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed. Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed. Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories. Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories. Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them. Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them. Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. Following example will create two cookies name and age these cookies will be expired after one hour. <?php setcookie("name", "John Watkin", time()+3600, "/","", 0); setcookie("age", "36", time()+3600, "/", "", 0); ?> <html> <head> <title>Setting Cookies with PHP</title> </head> <body> <?php echo "Set Cookies"?> </body> </html> PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. <html> <head> <title>Accessing Cookies with PHP</title> </head> <body> <?php echo $_COOKIE["name"]. "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["name"]. "<br />"; echo $_COOKIE["age"] . "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["age"] . "<br />"; ?> </body> </html> You can use isset() function to check if a cookie is set or not. <html> <head> <title>Accessing Cookies with PHP</title> </head> <body> <?php if( isset($_COOKIE["name"])) echo "Welcome " . $_COOKIE["name"] . "<br />"; else echo "Sorry... Not recognized" . "<br />"; ?> </body> </html> Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on. It is safest to set the cookie with a date that has already expired − <?php setcookie( "name", "", time()- 60, "/","", 0); setcookie( "age", "", time()- 60, "/","", 0); ?> <html> <head> <title>Deleting Cookies with PHP</title> </head> <body> <?php echo "Deleted Cookies" ?> </body> </html> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2894, "s": 2757, "text": "Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies." }, { "code": null, "e": 2958, "s": 2894, "text": "There are three steps involved in identifying returning users −" }, { "code": null, "e": 3064, "s": 2958, "text": "Server script sends a set of cookies to the browser. For example name, age, or identification number etc." }, { "code": null, "e": 3170, "s": 3064, "text": "Server script sends a set of cookies to the browser. For example name, age, or identification number etc." }, { "code": null, "e": 3235, "s": 3170, "text": "Browser stores this information on local machine for future use." }, { "code": null, "e": 3300, "s": 3235, "text": "Browser stores this information on local machine for future use." }, { "code": null, "e": 3464, "s": 3300, "text": "When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user." }, { "code": null, "e": 3628, "s": 3464, "text": "When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user." }, { "code": null, "e": 3719, "s": 3628, "text": "This chapter will teach you how to set cookies, how to access them and how to delete them." }, { "code": null, "e": 3911, "s": 3719, "text": "Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −" }, { "code": null, "e": 4158, "s": 3911, "text": "HTTP/1.1 200 OK\nDate: Fri, 04 Feb 2000 21:03:38 GMT\nServer: Apache/1.3.9 (UNIX) PHP/4.0b3\nSet-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; \n path=/; domain=tutorialspoint.com\nConnection: close\nContent-Type: text/html\n" }, { "code": null, "e": 4402, "s": 4158, "text": "As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to \"forget\" the cookie after the given time and date." }, { "code": null, "e": 4693, "s": 4402, "text": "If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser's headers might look something like this −" }, { "code": null, "e": 4935, "s": 4693, "text": "GET / HTTP/1.0\nConnection: Keep-Alive\nUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)\nHost: zink.demon.co.uk:1126\nAccept: image/gif, */*\nAccept-Encoding: gzip\nAccept-Language: en\nAccept-Charset: iso-8859-1,*,utf-8\nCookie: name=xyz\n" }, { "code": null, "e": 5150, "s": 4935, "text": "A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[\"name\"]." }, { "code": null, "e": 5342, "s": 5150, "text": "PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately." }, { "code": null, "e": 5399, "s": 5342, "text": "setcookie(name, value, expire, path, domain, security);\n" }, { "code": null, "e": 5441, "s": 5399, "text": "Here is the detail of all the arguments −" }, { "code": null, "e": 5594, "s": 5441, "text": "Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies." }, { "code": null, "e": 5747, "s": 5594, "text": "Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies." }, { "code": null, "e": 5849, "s": 5747, "text": "Value − This sets the value of the named variable and is the content that you actually want to store." }, { "code": null, "e": 5951, "s": 5849, "text": "Value − This sets the value of the named variable and is the content that you actually want to store." }, { "code": null, "e": 6182, "s": 5951, "text": "Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed." }, { "code": null, "e": 6413, "s": 6182, "text": "Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed." }, { "code": null, "e": 6567, "s": 6413, "text": "Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories." }, { "code": null, "e": 6721, "s": 6567, "text": "Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories." }, { "code": null, "e": 6918, "s": 6721, "text": "Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them." }, { "code": null, "e": 7115, "s": 6918, "text": "Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them." }, { "code": null, "e": 7295, "s": 7115, "text": "Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP." }, { "code": null, "e": 7475, "s": 7295, "text": "Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP." }, { "code": null, "e": 7576, "s": 7475, "text": "Following example will create two cookies name and age these cookies will be expired after one hour." }, { "code": null, "e": 7847, "s": 7576, "text": "<?php\n setcookie(\"name\", \"John Watkin\", time()+3600, \"/\",\"\", 0);\n setcookie(\"age\", \"36\", time()+3600, \"/\", \"\", 0);\n?>\n<html>\n \n <head>\n <title>Setting Cookies with PHP</title>\n </head>\n \n <body>\n <?php echo \"Set Cookies\"?>\n </body>\n \n</html>" }, { "code": null, "e": 8028, "s": 7847, "text": "PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example." }, { "code": null, "e": 8456, "s": 8028, "text": "<html>\n \n <head>\n <title>Accessing Cookies with PHP</title>\n </head>\n \n <body>\n \n <?php\n echo $_COOKIE[\"name\"]. \"<br />\";\n \n /* is equivalent to */\n echo $HTTP_COOKIE_VARS[\"name\"]. \"<br />\";\n \n echo $_COOKIE[\"age\"] . \"<br />\";\n \n /* is equivalent to */\n echo $HTTP_COOKIE_VARS[\"age\"] . \"<br />\";\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 8521, "s": 8456, "text": "You can use isset() function to check if a cookie is set or not." }, { "code": null, "e": 8845, "s": 8521, "text": "<html>\n \n <head>\n <title>Accessing Cookies with PHP</title>\n </head>\n \n <body>\n \n <?php\n if( isset($_COOKIE[\"name\"]))\n echo \"Welcome \" . $_COOKIE[\"name\"] . \"<br />\";\n \n else\n echo \"Sorry... Not recognized\" . \"<br />\";\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 9006, "s": 8845, "text": "Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on." }, { "code": null, "e": 9076, "s": 9006, "text": "It is safest to set the cookie with a date that has already expired −" }, { "code": null, "e": 9338, "s": 9076, "text": "<?php\n setcookie( \"name\", \"\", time()- 60, \"/\",\"\", 0);\n setcookie( \"age\", \"\", time()- 60, \"/\",\"\", 0);\n?>\n<html>\n \n <head>\n <title>Deleting Cookies with PHP</title>\n </head>\n \n <body>\n <?php echo \"Deleted Cookies\" ?>\n </body>\n \n</html>" }, { "code": null, "e": 9371, "s": 9338, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 9387, "s": 9371, "text": " Malhar Lathkar" }, { "code": null, "e": 9420, "s": 9387, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 9431, "s": 9420, "text": " Syed Raza" }, { "code": null, "e": 9466, "s": 9431, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9483, "s": 9466, "text": " Frahaan Hussain" }, { "code": null, "e": 9516, "s": 9483, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 9531, "s": 9516, "text": " Nivedita Jain" }, { "code": null, "e": 9566, "s": 9531, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 9578, "s": 9566, "text": " Azaz Patel" }, { "code": null, "e": 9613, "s": 9578, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9641, "s": 9613, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 9648, "s": 9641, "text": " Print" }, { "code": null, "e": 9659, "s": 9648, "text": " Add Notes" } ]
Understanding bias and variance. Anyone learning a data science 101... | by Vinodh Kumar Ravindranath | Towards Data Science
Anyone learning a data science 101 course is confronted with these terms bias and variance that define the accuracy of the machine learning model. I found some of the material around it confusing, so I thought I will try to explain with some illustration and code. Before I get to the code, basically bias is nothing but the expected error (average of the error) in the model when applied on different test data sets. Let me use the dartboard analogy. The numbers in the circles represent the error till the circumference of the circle where it is written. In board A, the average error or bias is equal to (0 + 0 + 0 + 1 + 2) / 5 = 0.6 Even though Board B looks different from Board A, it has the same average error or bias = (0 + 0 + 1 + 1 + 1) / 5= 0.6 Now the question is which dart thrower would you bet on? one using board A or board B. This is where variance comes into the picture. Variance is the variance of the error when applied on different test data points. Lets now try to apply this concept on the two dart throwers using Board A and B respectively. Board A’s variance = (0 + 0 + 0 + 12 + 22) / 5 = 1.0 Board B’s variance = (0 + 0 + 12 + 12 + 12) / 5 = 0.6 This indicates that while board A dart thrower hits the bull’s eye 50% more number of times than the board B dart thrower, he is much more erratic when he does not get it right. On the other hand, board B dart thrower has a steady hand and always hovering on or around the bull’s eye mark. In the world of machine learning models, usually models that are similar to the board B dart thrower are preferred since it avoid embarrassing mistakes and is more steady. Turns out the the behaviour similar to Board B occurs in overfitted machine learning models (overfitted with respect to a training set) — i.e. variance will be high even if the bias of the model is low. So greater the variance you will tend to be worried pushing it to production since when it goes wrong, it can go wrong pretty badly. In a model that is not overfitted (probably regularized), variance will be low — this means that the errors encountered on the test sets are not going to be ridiculous. I have illustrated this by applying both linear and cubic regression to a linear data set with random perturbations. Going through the code below (hopefully self explanatory) will help you see that though the average error (bias) is somewhat similar for both cubic and linear regression (similar to our dart throwers), however the variance is too high for cubic regression that makes it resemble the brilliant but erratic dart thrower on Board A. import numpy as np import matplotlib.pyplot as plt # Generate points that are around a line. Adding noise final_point = 7500 num_points = 300 middle = 4 last = 15 x = np.random.uniform(0, final_point, num_points) # y = 3x + 90 y = 3 * x + 90 p = 0.3 # Add random perturbations # Big perturbations in 30% of the points # Small perturbations at every point. y += (np.random.binomial(1, p, size=num_points) * \ np.random.normal(loc=0.0, scale=10000, size=num_points))\ + \ (np.random.normal(loc=0.0, scale=final_point / 5, size=num_points)) # Plot of Training Data plt.scatter(x, y) plt.xlabel('x') plt.xlabel('y') plt.title("Training Data") plt.show() from sklearn.preprocessing import PolynomialFeatures from sklearn import linear_model # Curve fitting function # Fits both cubic and linear curves and returns the prediction for both in a tuple def fit_curves(sampled_x, sampled_y): lin = linear_model.LinearRegression() lin.fit(sampled_x, sampled_y) linear_ypred = lin.predict(x[:, np.newaxis]) poly = PolynomialFeatures(degree = 3) sampled_x_poly = poly.fit_transform(sampled_x) x_poly = poly.fit_transform(x[:, np.newaxis]) lin2 = linear_model.LinearRegression() lin2.fit(sampled_x_poly, sampled_y) cubic_ypred = lin2.predict(x_poly) return((linear_ypred, cubic_ypred)) # Generate 1000 training sets num_trials = 5 all_cpred = [] all_cbiases = [] all_lpred = [] all_lbiases = [] # Two figures - one each for cubic and linear regression for j in range(2): plt.figure(j) plt.scatter(x, y, color = 'blue') for i in range(num_trials): # Create a training data set sampled_indices = np.random.choice(num_points, size=25) sampled_x = x[sampled_indices] sampled_y = y[sampled_indices] sampled_x = sampled_x[:, np.newaxis] sampled_y = sampled_y[:, np.newaxis] (lpred, cpred) = fit_curves(sampled_x, sampled_y) # Plotting the sampled points - training sample for j in range(3): plt.figure(j) plt.scatter(sampled_x, sampled_y, color = 'green') # Plot results of cubic curve plt.figure(0) plt.scatter(x, cpred, color = 'red') # Plot results of linear curve plt.figure(1) plt.scatter(x, lpred, color = 'yellow') cubic_bias = np.abs(y[:, np.newaxis] - cpred) linear_bias = np.abs(y[:, np.newaxis] - lpred) all_cpred.append(cpred) all_cbiases.append(cubic_bias) all_lpred.append(lpred) all_lbiases.append(linear_bias) plt.show() print("Variance (cubic regression) = ", np.average(np.var(all_cpred, axis=0))) print("Variance (linear regression) = ", np.average(np.var(all_lpred, axis=0))) print("Bias (cubic regression) = ", np.average(all_cbiases)) print("Bias (linear regression) = ", np.average(all_lbiases)) #print(all_cbiases) Variance (cubic regression) = 5896095.929190446 Variance (linear regression) = 1256507.0010197319 Bias (cubic regression) = 4223.96882929893 Bias (linear regression) = 3614.2993395834055 In this case, this would mean that the data scientist should choose the linear regression model for roll out to production. In conclusion, as data scientists, it is important not to look at the average error (bias), but also pay attention to the variance. Higher the variance, it means that while there are cases where the model is super-accurate, there are also cases where the model goes horribly wrong, which you would like to avoid.
[ { "code": null, "e": 437, "s": 172, "text": "Anyone learning a data science 101 course is confronted with these terms bias and variance that define the accuracy of the machine learning model. I found some of the material around it confusing, so I thought I will try to explain with some illustration and code." }, { "code": null, "e": 729, "s": 437, "text": "Before I get to the code, basically bias is nothing but the expected error (average of the error) in the model when applied on different test data sets. Let me use the dartboard analogy. The numbers in the circles represent the error till the circumference of the circle where it is written." }, { "code": null, "e": 809, "s": 729, "text": "In board A, the average error or bias is equal to (0 + 0 + 0 + 1 + 2) / 5 = 0.6" }, { "code": null, "e": 928, "s": 809, "text": "Even though Board B looks different from Board A, it has the same average error or bias = (0 + 0 + 1 + 1 + 1) / 5= 0.6" }, { "code": null, "e": 1062, "s": 928, "text": "Now the question is which dart thrower would you bet on? one using board A or board B. This is where variance comes into the picture." }, { "code": null, "e": 1238, "s": 1062, "text": "Variance is the variance of the error when applied on different test data points. Lets now try to apply this concept on the two dart throwers using Board A and B respectively." }, { "code": null, "e": 1291, "s": 1238, "text": "Board A’s variance = (0 + 0 + 0 + 12 + 22) / 5 = 1.0" }, { "code": null, "e": 1345, "s": 1291, "text": "Board B’s variance = (0 + 0 + 12 + 12 + 12) / 5 = 0.6" }, { "code": null, "e": 1807, "s": 1345, "text": "This indicates that while board A dart thrower hits the bull’s eye 50% more number of times than the board B dart thrower, he is much more erratic when he does not get it right. On the other hand, board B dart thrower has a steady hand and always hovering on or around the bull’s eye mark. In the world of machine learning models, usually models that are similar to the board B dart thrower are preferred since it avoid embarrassing mistakes and is more steady." }, { "code": null, "e": 2143, "s": 1807, "text": "Turns out the the behaviour similar to Board B occurs in overfitted machine learning models (overfitted with respect to a training set) — i.e. variance will be high even if the bias of the model is low. So greater the variance you will tend to be worried pushing it to production since when it goes wrong, it can go wrong pretty badly." }, { "code": null, "e": 2312, "s": 2143, "text": "In a model that is not overfitted (probably regularized), variance will be low — this means that the errors encountered on the test sets are not going to be ridiculous." }, { "code": null, "e": 2429, "s": 2312, "text": "I have illustrated this by applying both linear and cubic regression to a linear data set with random perturbations." }, { "code": null, "e": 2759, "s": 2429, "text": "Going through the code below (hopefully self explanatory) will help you see that though the average error (bias) is somewhat similar for both cubic and linear regression (similar to our dart throwers), however the variance is too high for cubic regression that makes it resemble the brilliant but erratic dart thrower on Board A." }, { "code": null, "e": 3450, "s": 2759, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Generate points that are around a line. Adding noise \nfinal_point = 7500\nnum_points = 300\nmiddle = 4\nlast = 15\n\nx = np.random.uniform(0, final_point, num_points)\n# y = 3x + 90\ny = 3 * x + 90\n\np = 0.3\n\n# Add random perturbations\n# Big perturbations in 30% of the points\n# Small perturbations at every point.\ny += (np.random.binomial(1, p, size=num_points) * \\\n np.random.normal(loc=0.0, scale=10000, size=num_points))\\\n + \\\n (np.random.normal(loc=0.0, scale=final_point / 5, size=num_points))\n \n \n\n# Plot of Training Data \nplt.scatter(x, y) \nplt.xlabel('x') \nplt.xlabel('y') \nplt.title(\"Training Data\") \nplt.show()\n" }, { "code": null, "e": 5614, "s": 3450, "text": "from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn import linear_model\n\n# Curve fitting function\n# Fits both cubic and linear curves and returns the prediction for both in a tuple\ndef fit_curves(sampled_x, sampled_y): \n lin = linear_model.LinearRegression()\n lin.fit(sampled_x, sampled_y)\n linear_ypred = lin.predict(x[:, np.newaxis])\n \n poly = PolynomialFeatures(degree = 3) \n sampled_x_poly = poly.fit_transform(sampled_x)\n x_poly = poly.fit_transform(x[:, np.newaxis])\n lin2 = linear_model.LinearRegression() \n lin2.fit(sampled_x_poly, sampled_y)\n cubic_ypred = lin2.predict(x_poly)\n return((linear_ypred, cubic_ypred))\n\n# Generate 1000 training sets\nnum_trials = 5\nall_cpred = []\nall_cbiases = []\nall_lpred = []\nall_lbiases = []\n\n# Two figures - one each for cubic and linear regression\nfor j in range(2):\n plt.figure(j)\n plt.scatter(x, y, color = 'blue')\n\n\nfor i in range(num_trials):\n # Create a training data set\n sampled_indices = np.random.choice(num_points, size=25)\n sampled_x = x[sampled_indices]\n sampled_y = y[sampled_indices]\n sampled_x = sampled_x[:, np.newaxis]\n sampled_y = sampled_y[:, np.newaxis]\n (lpred, cpred) = fit_curves(sampled_x, sampled_y)\n \n # Plotting the sampled points - training sample\n for j in range(3):\n plt.figure(j)\n plt.scatter(sampled_x, sampled_y, color = 'green')\n \n # Plot results of cubic curve\n plt.figure(0)\n plt.scatter(x, cpred, color = 'red')\n \n # Plot results of linear curve\n plt.figure(1)\n plt.scatter(x, lpred, color = 'yellow')\n \n cubic_bias = np.abs(y[:, np.newaxis] - cpred)\n linear_bias = np.abs(y[:, np.newaxis] - lpred)\n all_cpred.append(cpred)\n all_cbiases.append(cubic_bias)\n \n all_lpred.append(lpred)\n all_lbiases.append(linear_bias)\n \nplt.show()\nprint(\"Variance (cubic regression) = \", np.average(np.var(all_cpred, axis=0)))\nprint(\"Variance (linear regression) = \", np.average(np.var(all_lpred, axis=0)))\nprint(\"Bias (cubic regression) = \", np.average(all_cbiases))\nprint(\"Bias (linear regression) = \", np.average(all_lbiases))\n#print(all_cbiases)\n" }, { "code": null, "e": 5806, "s": 5614, "text": "Variance (cubic regression) = 5896095.929190446\nVariance (linear regression) = 1256507.0010197319\nBias (cubic regression) = 4223.96882929893\nBias (linear regression) = 3614.2993395834055\n" }, { "code": null, "e": 5930, "s": 5806, "text": "In this case, this would mean that the data scientist should choose the linear regression model for roll out to production." } ]
Program to count number of palindromes of size k can be formed from the given string characters in Python
Suppose we have a string s that is representing alphabet characters and a number k. We have to find the number of palindromes where we can construct of length k using only letters in s. And we can use these letters more than once if we want. So, if the input is like s = "xy", k = 4, then the output will be 4 as the palindromes are [xxxx, yyyy, xyyx, yxxy]. To solve this, we will follow these steps − n := quotient of k/2 x := number of unique characters in s return x^(n + k mod 2) Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, s, k): n=k//2 return len(set(s))**(n+k%2) s = "xy" k = 4 ob = Solution() print(ob.solve(s, k)) "xy",4 4
[ { "code": null, "e": 1304, "s": 1062, "text": "Suppose we have a string s that is representing alphabet characters and a number k. We have\nto find the number of palindromes where we can construct of length k using only letters in s.\nAnd we can use these letters more than once if we want." }, { "code": null, "e": 1421, "s": 1304, "text": "So, if the input is like s = \"xy\", k = 4, then the output will be 4 as the palindromes are [xxxx, yyyy,\nxyyx, yxxy]." }, { "code": null, "e": 1465, "s": 1421, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1486, "s": 1465, "text": "n := quotient of k/2" }, { "code": null, "e": 1524, "s": 1486, "text": "x := number of unique characters in s" }, { "code": null, "e": 1547, "s": 1524, "text": "return x^(n + k mod 2)" }, { "code": null, "e": 1617, "s": 1547, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1628, "s": 1617, "text": " Live Demo" }, { "code": null, "e": 1770, "s": 1628, "text": "class Solution:\n def solve(self, s, k):\n n=k//2\n return len(set(s))**(n+k%2)\ns = \"xy\"\nk = 4\nob = Solution()\nprint(ob.solve(s, k))" }, { "code": null, "e": 1777, "s": 1770, "text": "\"xy\",4" }, { "code": null, "e": 1779, "s": 1777, "text": "4" } ]
How to set the Foreground Color of the RadioButton in C#?
30 Jun, 2019 In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the foreground color of the RadioButton using the ForeColor Property of the RadioButton which makes your RadioButton more attractive. This property is an ambient property. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the foreground color of the RadioButton as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RadioButton control to set the foreground color of the RadioButton.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the foreground color of the RadioButton control programmatically with the help of given syntax: public override System.Drawing.Color ForeColor { get; set; } Here, Color indicates the foreground color of the RadioButton. The following steps show how to set the foreground color of the RadioButton dynamically: Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button RadioButton r1 = new RadioButton(); // Creating radio button RadioButton r1 = new RadioButton(); Step 2: After creating RadioButton, set the ForeColor property of the RadioButton provided by the RadioButton class.// Setting the foreground color of the radio button r1.ForeColor = Color.Brown; // Setting the foreground color of the radio button r1.ForeColor = Color.Brown; Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form this.Controls.Add(r1); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Your Branch"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "CSE"; r1.Location = new Point(286, 40); r1.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "ECE"; r2.Location = new Point(356, 40); r2.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r2); }}}Output: // Add this radio button to the form this.Controls.Add(r1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Your Branch"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "CSE"; r1.Location = new Point(286, 40); r1.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "ECE"; r2.Location = new Point(356, 40); r2.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r2); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2019" }, { "code": null, "e": 541, "s": 28, "text": "In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to adjust the foreground color of the RadioButton using the ForeColor Property of the RadioButton which makes your RadioButton more attractive. This property is an ambient property. You can set this property in two different ways:" }, { "code": null, "e": 659, "s": 541, "text": "1. Design-Time: It is the easiest way to set the foreground color of the RadioButton as shown in the following steps:" }, { "code": null, "e": 775, "s": 659, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 962, "s": 775, "text": "Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need." }, { "code": null, "e": 1102, "s": 962, "text": "Step 3: After drag and drop you will go to the properties of the RadioButton control to set the foreground color of the RadioButton.Output:" }, { "code": null, "e": 1110, "s": 1102, "text": "Output:" }, { "code": null, "e": 1298, "s": 1110, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the foreground color of the RadioButton control programmatically with the help of given syntax:" }, { "code": null, "e": 1359, "s": 1298, "text": "public override System.Drawing.Color ForeColor { get; set; }" }, { "code": null, "e": 1511, "s": 1359, "text": "Here, Color indicates the foreground color of the RadioButton. The following steps show how to set the foreground color of the RadioButton dynamically:" }, { "code": null, "e": 1676, "s": 1511, "text": "Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 1738, "s": 1676, "text": "// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 1935, "s": 1738, "text": "Step 2: After creating RadioButton, set the ForeColor property of the RadioButton provided by the RadioButton class.// Setting the foreground color of the radio button\nr1.ForeColor = Color.Brown;\n" }, { "code": null, "e": 2016, "s": 1935, "text": "// Setting the foreground color of the radio button\nr1.ForeColor = Color.Brown;\n" }, { "code": null, "e": 3581, "s": 2016, "text": "Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form\nthis.Controls.Add(r1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Your Branch\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"CSE\"; r1.Location = new Point(286, 40); r1.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"ECE\"; r2.Location = new Point(356, 40); r2.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r2); }}}Output:" }, { "code": null, "e": 3642, "s": 3581, "text": "// Add this radio button to the form\nthis.Controls.Add(r1);\n" }, { "code": null, "e": 3651, "s": 3642, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp20 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Your Branch\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"CSE\"; r1.Location = new Point(286, 40); r1.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"ECE\"; r2.Location = new Point(356, 40); r2.ForeColor = Color.Brown; // Adding this label to the form this.Controls.Add(r2); }}}", "e": 5064, "s": 3651, "text": null }, { "code": null, "e": 5072, "s": 5064, "text": "Output:" }, { "code": null, "e": 5075, "s": 5072, "text": "C#" }, { "code": null, "e": 5173, "s": 5075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5201, "s": 5173, "text": "C# Dictionary with examples" }, { "code": null, "e": 5232, "s": 5201, "text": "Introduction to .NET Framework" }, { "code": null, "e": 5247, "s": 5232, "text": "C# | Delegates" }, { "code": null, "e": 5290, "s": 5247, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5339, "s": 5290, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5362, "s": 5339, "text": "C# | Method Overriding" }, { "code": null, "e": 5378, "s": 5362, "text": "C# | Data Types" }, { "code": null, "e": 5396, "s": 5378, "text": "C# | Constructors" }, { "code": null, "e": 5436, "s": 5396, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
HTML | <hr> width Attribute
28 May, 2019 The HTML <hr> width attribute is used to specify the width of the horizontal line in terms of pixels or percent. Syntax: <hr width="pixels|%"> Attribute Values: pixels: It sets the width of <hr> attribute in terms of pixels. %: It sets the width of <hr> attribute in terms of percentage (%). Note: The <hr> width attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title> HTML hr width Attribute </title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <hr width="500px;"> <p>Computer science portal</p> <hr width="70%"></body> </html> Output: Supported Browsers: The browser supported by HTML <hr> width attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2019" }, { "code": null, "e": 141, "s": 28, "text": "The HTML <hr> width attribute is used to specify the width of the horizontal line in terms of pixels or percent." }, { "code": null, "e": 149, "s": 141, "text": "Syntax:" }, { "code": null, "e": 171, "s": 149, "text": "<hr width=\"pixels|%\">" }, { "code": null, "e": 189, "s": 171, "text": "Attribute Values:" }, { "code": null, "e": 253, "s": 189, "text": "pixels: It sets the width of <hr> attribute in terms of pixels." }, { "code": null, "e": 320, "s": 253, "text": "%: It sets the width of <hr> attribute in terms of percentage (%)." }, { "code": null, "e": 379, "s": 320, "text": "Note: The <hr> width attribute is not supported by HTML 5." }, { "code": null, "e": 388, "s": 379, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML hr width Attribute </title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <hr width=\"500px;\"> <p>Computer science portal</p> <hr width=\"70%\"></body> </html>", "e": 633, "s": 388, "text": null }, { "code": null, "e": 641, "s": 633, "text": "Output:" }, { "code": null, "e": 730, "s": 641, "text": "Supported Browsers: The browser supported by HTML <hr> width attribute are listed below:" }, { "code": null, "e": 744, "s": 730, "text": "Google Chrome" }, { "code": null, "e": 762, "s": 744, "text": "Internet Explorer" }, { "code": null, "e": 770, "s": 762, "text": "Firefox" }, { "code": null, "e": 777, "s": 770, "text": "Safari" }, { "code": null, "e": 783, "s": 777, "text": "Opera" }, { "code": null, "e": 799, "s": 783, "text": "HTML-Attributes" }, { "code": null, "e": 804, "s": 799, "text": "HTML" }, { "code": null, "e": 821, "s": 804, "text": "Web Technologies" }, { "code": null, "e": 826, "s": 821, "text": "HTML" } ]
Print ancestors of a given binary tree node without recursion
21 Jun, 2022 Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1 6 3 1 7 3 1 8 4 2 1 9 5 2 1 10 7 3 1 Recursive solution for this problem is discussed here. It is clear that we need to use a stack based iterative traversal of the Binary Tree. The idea is to have all ancestors in stack when we reach the node with given key. Once we reach the key, all we have to do is, print contents of stack. How to get all ancestors in stack when we reach the given node? We can traverse all nodes in Postorder way. If we take a closer look at the recursive postorder traversal, we can easily observe that, when recursive function is called for a node, the recursion call stack contains ancestors of the node. So idea is do iterative Postorder traversal and stop the traversal when we reach the desired node. Following is implementation of the above approach. Implementation: C C++ Java Python3 C# Javascript // C program to print all ancestors of a given key#include <stdio.h>#include <stdlib.h> // Maximum stack size#define MAX_SIZE 100 // Structure for a tree nodestruct Node{ int data; struct Node *left, *right;}; // Structure for Stackstruct Stack{ int size; int top; struct Node* *array;}; // A utility function to create a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A utility function to create a stack of given sizestruct Stack* createStack(int size){ struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); stack->size = size; stack->top = -1; stack->array = (struct Node**) malloc(stack->size * sizeof(struct Node*)); return stack;} // BASIC OPERATIONS OF STACKint isFull(struct Stack* stack){ return ((stack->top + 1) == stack->size);}int isEmpty(struct Stack* stack){ return stack->top == -1;}void push(struct Stack* stack, struct Node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;}struct Node* pop(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];}struct Node* peek(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top];} // Iterative Function to print all ancestors of a given keyvoid printAncestors(struct Node *root, int key){ if (root == NULL) return; // Create a stack to hold ancestors struct Stack* stack = createStack(MAX_SIZE); // Traverse the complete tree in postorder way till we find the key while (1) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while (root && root->data != key) { push(stack, root); // push current node root = root->left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if (root && root->data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if (peek(stack)->right == NULL) { root = pop(stack); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. // Consider the following tree for example and key = 3. If we // remove the following loop, the program will go in an // infinite loop after reaching 5. // 1 // / \ // 2 3 // \ // 4 // \ // 5 while (!isEmpty(stack) && peek(stack)->right == root) root = pop(stack); } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = isEmpty(stack)? NULL: peek(stack)->right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while (!isEmpty(stack)) printf("%d ", pop(stack)->data);} // Driver program to test above functionsint main(){ // Let us construct a binary tree 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->right->right = newNode(9); root->right->right->left = newNode(10); printf("Following are all keys and their ancestors\n"); for (int key = 1; key <= 10; key++) { printf("%d: ", key); printAncestors(root, key); printf("\n"); } getchar(); return 0;} // C++ program to print all ancestors of a given key#include <bits/stdc++.h>using namespace std; // Structure for a tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Iterative Function to print all ancestors of a given keyvoid printAncestors(struct Node *root, int key){ if (root == NULL) return; // Create a stack to hold ancestors stack<struct Node* > st; // Traverse the complete tree in postorder way till we find the key while (1) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while (root && root->data != key) { st.push(root); // push current node root = root->left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if (root && root->data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if (st.top()->right == NULL) { root = st.top(); st.pop(); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. while (!st.empty() && st.top()->right == root) {root = st.top(); st.pop(); } } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = st.empty()? NULL: st.top()->right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while (!st.empty()) { cout<<st.top()->data<<" "; st.pop(); }} // Driver program to test above functionsint main(){ // Let us construct a binary tree 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->right->right = newNode(9); root->right->right->left = newNode(10); cout<<"Following are all keys and their ancestors"<<endl; for (int key = 1; key <= 10; key++) { cout<<key<<":"<<" "; printAncestors(root, key); cout<<endl; } return 0;}// This code is contributed by Gautam Singh // Java program to print all ancestors of a given keyimport java.util.Stack; public class GFG{ // Class for a tree node static class Node { int data; Node left,right; // constructor to create Node // left and right are by default null Node(int data) { this.data = data; } } // Iterative Function to print all ancestors of a given key static void printAncestors(Node root,int key) { if(root == null) return; // Create a stack to hold ancestors Stack<Node> st = new Stack<>(); // Traverse the complete tree in postorder way till we find the key while(true) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while(root != null && root.data != key) { st.push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if(root != null && root.data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if(st.peek().right == null) { root =st.peek(); st.pop(); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. while( st.empty() == false && st.peek().right == root) { root = st.peek(); st.pop(); } } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = st.empty() ? null : st.peek().right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while( !st.empty() ) { System.out.print(st.peek().data+" "); st.pop(); } } // Driver program to test above functions public static void main(String[] args) { // Let us construct a binary tree 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.right.right = new Node(9); root.right.right.left = new Node(10); System.out.println("Following are all keys and their ancestors"); for(int key = 1;key <= 10;key++) { System.out.print(key+": "); printAncestors(root, key); System.out.println(); } } }//This code is Contributed by Sumit Ghosh # Python3 program to print all ancestors of a given key # Class for a tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Iterative Function to print all ancestors of a given keydef printAncestors(root, key): if(root == None): return; # Create a stack to hold ancestors st = [] # Traverse the complete tree in postorder way till we find the key while(True): # Traverse the left side. While traversing, append the nodes into # the stack so that their right subtrees can be traversed later while(root != None and root.data != key): st.append(root); # append current node root = root.left; # move to next node # If the node whose ancestors are to be printed is found, # then break the while loop. if(root != None and root.data == key): break; # Check if right sub-tree exists for the node at top # If not then pop that node because we don't need this # node any more. if(st[-1].right == None): root = st[-1]; st.pop(); # If the popped node is right child of top, then remove the top # as well. Left child of the top must have processed before. while(len(st) != 0 and st[-1].right == root): root = st[-1]; st.pop(); # if stack is not empty then simply set the root as right child # of top and start traversing right sub-tree. root = None if len(st) == 0 else st[-1].right; # If stack is not empty, print contents of stack # Here assumption is that the key is there in tree while(len(st) != 0): print(st[-1].data, end = " ") st.pop(); # Driver program to test above functionsif __name__=='__main__': # Let us construct a binary tree root = Node(1); root.left = Node(2); root.right = Node(3); root.left.left = Node(4); root.left.right = Node(5); root.right.left = Node(6); root.right.right = Node(7); root.left.left.left = Node(8); root.left.right.right = Node(9); root.right.right.left = Node(10); print("Following are all keys and their ancestors"); for key in range(1, 11): print(key, end = ": "); printAncestors(root, key); print(); # This code is contributed by rutvik_56. // C# program to print all ancestors// of a given keyusing System;using System.Collections.Generic; class GFG{// Class for a tree nodepublic class Node{ public int data; public Node left, right; // constructor to create Node // left and right are by default null public Node(int data) { this.data = data; }} // Iterative Function to print// all ancestors of a given keypublic static void printAncestors(Node root, int key){ if (root == null) { return; } // Create a stack to hold ancestors Stack<Node> st = new Stack<Node>(); // Traverse the complete tree in // postorder way till we find the key while (true) { // Traverse the left side. While // traversing, push the nodes into // the stack so that their right // subtrees can be traversed later while (root != null && root.data != key) { st.Push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors // are to be printed is found, // then break the while loop. if (root != null && root.data == key) { break; } // Check if right sub-tree exists for // the node at top. If not then pop // that node because we don't need // this node any more. if (st.Peek().right == null) { root = st.Peek(); st.Pop(); // If the popped node is right child // of top, then remove the top as well. // Left child of the top must have // processed before. while (st.Count > 0 && st.Peek().right == root) { root = st.Peek(); st.Pop(); } } // if stack is not empty then simply // set the root as right child of top // and start traversing right sub-tree. root = st.Count == 0 ? null : st.Peek().right; } // If stack is not empty, print contents // of stack. Here assumption is that the // key is there in tree while (st.Count > 0) { Console.Write(st.Peek().data + " "); st.Pop(); }} // Driver Codepublic static void Main(string[] args){ // Let us construct a binary tree 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.right.right = new Node(9); root.right.right.left = new Node(10); Console.WriteLine("Following are all keys " + "and their ancestors"); for (int key = 1; key <= 10; key++) { Console.Write(key + ": "); printAncestors(root, key); Console.WriteLine(); }}} // This code is contributed by Shrikant13 <script> // Javascript program to print all ancestors of a given key // Class for a tree node class Node { // constructor to create Node // left and right are by default null constructor(data) { this.left = null; this.right = null; this.data = data; } } // Iterative Function to print // all ancestors of a given key function printAncestors(root, key) { if (root == null) { return; } // Create a stack to hold ancestors let st = []; // Traverse the complete tree in // postorder way till we find the key while (true) { // Traverse the left side. While // traversing, push the nodes into // the stack so that their right // subtrees can be traversed later while (root != null && root.data != key) { st.push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors // are to be printed is found, // then break the while loop. if (root != null && root.data == key) { break; } // Check if right sub-tree exists for // the node at top. If not then pop // that node because we don't need // this node any more. if (st[st.length - 1].right == null) { root = st[st.length - 1]; st.pop(); // If the popped node is right child // of top, then remove the top as well. // Left child of the top must have // processed before. while (st.length > 0 && st[st.length - 1].right == root) { root = st[st.length - 1]; st.pop(); } } // if stack is not empty then simply // set the root as right child of top // and start traversing right sub-tree. root = st.length == 0 ? null : st[st.length - 1].right; } // If stack is not empty, print contents // of stack. Here assumption is that the // key is there in tree while (st.length > 0) { document.write(st[st.length - 1].data + " "); st.pop(); } } // Let us construct a binary tree let 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.right.right = new Node(9); root.right.right.left = new Node(10); document.write("Following are all keys " + "and their ancestors" + "</br>"); for (let key = 1; key <= 10; key++) { document.write(key + ": "); printAncestors(root, key); document.write("</br>"); } // This code is contributed by decode2207.</script> Following are all keys and their ancestors 1: 2: 1 3: 1 4: 2 1 5: 2 1 6: 3 1 7: 3 1 8: 4 2 1 9: 5 2 1 10: 7 3 1 Exercise Note that the above solution assumes that the given key is present in the given Binary Tree. It may go in infinite loop if key is not present. Extend the above solution to work even when the key is not present in tree. shrikanth13 rutvik_56 decode2207 surinderdawra388 hardikkoriintern Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Design a stack with operations on middle element How to efficiently implement k stacks in a single array? Next Smaller Element Real-time application of Data Structures Construct Binary Tree from String with bracket representation ZigZag Tree Traversal Reverse individual words Length of the longest valid substring
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 215, "s": 52, "text": "Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree " }, { "code": null, "e": 354, "s": 215, "text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7 \n / \\ /\n 8 9 10 " }, { "code": null, "e": 427, "s": 354, "text": "Following are different input keys and their ancestors in the above tree" }, { "code": null, "e": 664, "s": 427, "text": "Input Key List of Ancestors \n-------------------------\n 1 \n 2 1\n 3 1\n 4 2 1\n 5 2 1\n 6 3 1\n 7 3 1\n 8 4 2 1\n 9 5 2 1\n10 7 3 1" }, { "code": null, "e": 720, "s": 664, "text": "Recursive solution for this problem is discussed here. " }, { "code": null, "e": 959, "s": 720, "text": "It is clear that we need to use a stack based iterative traversal of the Binary Tree. The idea is to have all ancestors in stack when we reach the node with given key. Once we reach the key, all we have to do is, print contents of stack. " }, { "code": null, "e": 1427, "s": 959, "text": "How to get all ancestors in stack when we reach the given node? We can traverse all nodes in Postorder way. If we take a closer look at the recursive postorder traversal, we can easily observe that, when recursive function is called for a node, the recursion call stack contains ancestors of the node. So idea is do iterative Postorder traversal and stop the traversal when we reach the desired node. Following is implementation of the above approach. Implementation:" }, { "code": null, "e": 1429, "s": 1427, "text": "C" }, { "code": null, "e": 1433, "s": 1429, "text": "C++" }, { "code": null, "e": 1438, "s": 1433, "text": "Java" }, { "code": null, "e": 1446, "s": 1438, "text": "Python3" }, { "code": null, "e": 1449, "s": 1446, "text": "C#" }, { "code": null, "e": 1460, "s": 1449, "text": "Javascript" }, { "code": "// C program to print all ancestors of a given key#include <stdio.h>#include <stdlib.h> // Maximum stack size#define MAX_SIZE 100 // Structure for a tree nodestruct Node{ int data; struct Node *left, *right;}; // Structure for Stackstruct Stack{ int size; int top; struct Node* *array;}; // A utility function to create a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // A utility function to create a stack of given sizestruct Stack* createStack(int size){ struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); stack->size = size; stack->top = -1; stack->array = (struct Node**) malloc(stack->size * sizeof(struct Node*)); return stack;} // BASIC OPERATIONS OF STACKint isFull(struct Stack* stack){ return ((stack->top + 1) == stack->size);}int isEmpty(struct Stack* stack){ return stack->top == -1;}void push(struct Stack* stack, struct Node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;}struct Node* pop(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];}struct Node* peek(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top];} // Iterative Function to print all ancestors of a given keyvoid printAncestors(struct Node *root, int key){ if (root == NULL) return; // Create a stack to hold ancestors struct Stack* stack = createStack(MAX_SIZE); // Traverse the complete tree in postorder way till we find the key while (1) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while (root && root->data != key) { push(stack, root); // push current node root = root->left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if (root && root->data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if (peek(stack)->right == NULL) { root = pop(stack); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. // Consider the following tree for example and key = 3. If we // remove the following loop, the program will go in an // infinite loop after reaching 5. // 1 // / \\ // 2 3 // \\ // 4 // \\ // 5 while (!isEmpty(stack) && peek(stack)->right == root) root = pop(stack); } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = isEmpty(stack)? NULL: peek(stack)->right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while (!isEmpty(stack)) printf(\"%d \", pop(stack)->data);} // Driver program to test above functionsint main(){ // Let us construct a binary tree 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->right->right = newNode(9); root->right->right->left = newNode(10); printf(\"Following are all keys and their ancestors\\n\"); for (int key = 1; key <= 10; key++) { printf(\"%d: \", key); printAncestors(root, key); printf(\"\\n\"); } getchar(); return 0;}", "e": 5493, "s": 1460, "text": null }, { "code": "// C++ program to print all ancestors of a given key#include <bits/stdc++.h>using namespace std; // Structure for a tree nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new tree nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node;} // Iterative Function to print all ancestors of a given keyvoid printAncestors(struct Node *root, int key){ if (root == NULL) return; // Create a stack to hold ancestors stack<struct Node* > st; // Traverse the complete tree in postorder way till we find the key while (1) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while (root && root->data != key) { st.push(root); // push current node root = root->left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if (root && root->data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if (st.top()->right == NULL) { root = st.top(); st.pop(); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. while (!st.empty() && st.top()->right == root) {root = st.top(); st.pop(); } } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = st.empty()? NULL: st.top()->right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while (!st.empty()) { cout<<st.top()->data<<\" \"; st.pop(); }} // Driver program to test above functionsint main(){ // Let us construct a binary tree 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->right->right = newNode(9); root->right->right->left = newNode(10); cout<<\"Following are all keys and their ancestors\"<<endl; for (int key = 1; key <= 10; key++) { cout<<key<<\":\"<<\" \"; printAncestors(root, key); cout<<endl; } return 0;}// This code is contributed by Gautam Singh", "e": 8263, "s": 5493, "text": null }, { "code": "// Java program to print all ancestors of a given keyimport java.util.Stack; public class GFG{ // Class for a tree node static class Node { int data; Node left,right; // constructor to create Node // left and right are by default null Node(int data) { this.data = data; } } // Iterative Function to print all ancestors of a given key static void printAncestors(Node root,int key) { if(root == null) return; // Create a stack to hold ancestors Stack<Node> st = new Stack<>(); // Traverse the complete tree in postorder way till we find the key while(true) { // Traverse the left side. While traversing, push the nodes into // the stack so that their right subtrees can be traversed later while(root != null && root.data != key) { st.push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors are to be printed is found, // then break the while loop. if(root != null && root.data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need this // node any more. if(st.peek().right == null) { root =st.peek(); st.pop(); // If the popped node is right child of top, then remove the top // as well. Left child of the top must have processed before. while( st.empty() == false && st.peek().right == root) { root = st.peek(); st.pop(); } } // if stack is not empty then simply set the root as right child // of top and start traversing right sub-tree. root = st.empty() ? null : st.peek().right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while( !st.empty() ) { System.out.print(st.peek().data+\" \"); st.pop(); } } // Driver program to test above functions public static void main(String[] args) { // Let us construct a binary tree 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.right.right = new Node(9); root.right.right.left = new Node(10); System.out.println(\"Following are all keys and their ancestors\"); for(int key = 1;key <= 10;key++) { System.out.print(key+\": \"); printAncestors(root, key); System.out.println(); } } }//This code is Contributed by Sumit Ghosh", "e": 11446, "s": 8263, "text": null }, { "code": "# Python3 program to print all ancestors of a given key # Class for a tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Iterative Function to print all ancestors of a given keydef printAncestors(root, key): if(root == None): return; # Create a stack to hold ancestors st = [] # Traverse the complete tree in postorder way till we find the key while(True): # Traverse the left side. While traversing, append the nodes into # the stack so that their right subtrees can be traversed later while(root != None and root.data != key): st.append(root); # append current node root = root.left; # move to next node # If the node whose ancestors are to be printed is found, # then break the while loop. if(root != None and root.data == key): break; # Check if right sub-tree exists for the node at top # If not then pop that node because we don't need this # node any more. if(st[-1].right == None): root = st[-1]; st.pop(); # If the popped node is right child of top, then remove the top # as well. Left child of the top must have processed before. while(len(st) != 0 and st[-1].right == root): root = st[-1]; st.pop(); # if stack is not empty then simply set the root as right child # of top and start traversing right sub-tree. root = None if len(st) == 0 else st[-1].right; # If stack is not empty, print contents of stack # Here assumption is that the key is there in tree while(len(st) != 0): print(st[-1].data, end = \" \") st.pop(); # Driver program to test above functionsif __name__=='__main__': # Let us construct a binary tree root = Node(1); root.left = Node(2); root.right = Node(3); root.left.left = Node(4); root.left.right = Node(5); root.right.left = Node(6); root.right.right = Node(7); root.left.left.left = Node(8); root.left.right.right = Node(9); root.right.right.left = Node(10); print(\"Following are all keys and their ancestors\"); for key in range(1, 11): print(key, end = \": \"); printAncestors(root, key); print(); # This code is contributed by rutvik_56.", "e": 13900, "s": 11446, "text": null }, { "code": "// C# program to print all ancestors// of a given keyusing System;using System.Collections.Generic; class GFG{// Class for a tree nodepublic class Node{ public int data; public Node left, right; // constructor to create Node // left and right are by default null public Node(int data) { this.data = data; }} // Iterative Function to print// all ancestors of a given keypublic static void printAncestors(Node root, int key){ if (root == null) { return; } // Create a stack to hold ancestors Stack<Node> st = new Stack<Node>(); // Traverse the complete tree in // postorder way till we find the key while (true) { // Traverse the left side. While // traversing, push the nodes into // the stack so that their right // subtrees can be traversed later while (root != null && root.data != key) { st.Push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors // are to be printed is found, // then break the while loop. if (root != null && root.data == key) { break; } // Check if right sub-tree exists for // the node at top. If not then pop // that node because we don't need // this node any more. if (st.Peek().right == null) { root = st.Peek(); st.Pop(); // If the popped node is right child // of top, then remove the top as well. // Left child of the top must have // processed before. while (st.Count > 0 && st.Peek().right == root) { root = st.Peek(); st.Pop(); } } // if stack is not empty then simply // set the root as right child of top // and start traversing right sub-tree. root = st.Count == 0 ? null : st.Peek().right; } // If stack is not empty, print contents // of stack. Here assumption is that the // key is there in tree while (st.Count > 0) { Console.Write(st.Peek().data + \" \"); st.Pop(); }} // Driver Codepublic static void Main(string[] args){ // Let us construct a binary tree 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.right.right = new Node(9); root.right.right.left = new Node(10); Console.WriteLine(\"Following are all keys \" + \"and their ancestors\"); for (int key = 1; key <= 10; key++) { Console.Write(key + \": \"); printAncestors(root, key); Console.WriteLine(); }}} // This code is contributed by Shrikant13", "e": 16887, "s": 13900, "text": null }, { "code": "<script> // Javascript program to print all ancestors of a given key // Class for a tree node class Node { // constructor to create Node // left and right are by default null constructor(data) { this.left = null; this.right = null; this.data = data; } } // Iterative Function to print // all ancestors of a given key function printAncestors(root, key) { if (root == null) { return; } // Create a stack to hold ancestors let st = []; // Traverse the complete tree in // postorder way till we find the key while (true) { // Traverse the left side. While // traversing, push the nodes into // the stack so that their right // subtrees can be traversed later while (root != null && root.data != key) { st.push(root); // push current node root = root.left; // move to next node } // If the node whose ancestors // are to be printed is found, // then break the while loop. if (root != null && root.data == key) { break; } // Check if right sub-tree exists for // the node at top. If not then pop // that node because we don't need // this node any more. if (st[st.length - 1].right == null) { root = st[st.length - 1]; st.pop(); // If the popped node is right child // of top, then remove the top as well. // Left child of the top must have // processed before. while (st.length > 0 && st[st.length - 1].right == root) { root = st[st.length - 1]; st.pop(); } } // if stack is not empty then simply // set the root as right child of top // and start traversing right sub-tree. root = st.length == 0 ? null : st[st.length - 1].right; } // If stack is not empty, print contents // of stack. Here assumption is that the // key is there in tree while (st.length > 0) { document.write(st[st.length - 1].data + \" \"); st.pop(); } } // Let us construct a binary tree let 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.right.right = new Node(9); root.right.right.left = new Node(10); document.write(\"Following are all keys \" + \"and their ancestors\" + \"</br>\"); for (let key = 1; key <= 10; key++) { document.write(key + \": \"); printAncestors(root, key); document.write(\"</br>\"); } // This code is contributed by decode2207.</script>", "e": 20077, "s": 16887, "text": null }, { "code": null, "e": 20199, "s": 20077, "text": "Following are all keys and their ancestors\n1: \n2: 1 \n3: 1 \n4: 2 1 \n5: 2 1 \n6: 3 1 \n7: 3 1 \n8: 4 2 1 \n9: 5 2 1 \n10: 7 3 1 " }, { "code": null, "e": 20427, "s": 20199, "text": "Exercise Note that the above solution assumes that the given key is present in the given Binary Tree. It may go in infinite loop if key is not present. Extend the above solution to work even when the key is not present in tree." }, { "code": null, "e": 20439, "s": 20427, "text": "shrikanth13" }, { "code": null, "e": 20449, "s": 20439, "text": "rutvik_56" }, { "code": null, "e": 20460, "s": 20449, "text": "decode2207" }, { "code": null, "e": 20477, "s": 20460, "text": "surinderdawra388" }, { "code": null, "e": 20494, "s": 20477, "text": "hardikkoriintern" }, { "code": null, "e": 20500, "s": 20494, "text": "Stack" }, { "code": null, "e": 20506, "s": 20500, "text": "Stack" }, { "code": null, "e": 20604, "s": 20506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20636, "s": 20604, "text": "Introduction to Data Structures" }, { "code": null, "e": 20700, "s": 20636, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20749, "s": 20700, "text": "Design a stack with operations on middle element" }, { "code": null, "e": 20806, "s": 20749, "text": "How to efficiently implement k stacks in a single array?" }, { "code": null, "e": 20827, "s": 20806, "text": "Next Smaller Element" }, { "code": null, "e": 20868, "s": 20827, "text": "Real-time application of Data Structures" }, { "code": null, "e": 20930, "s": 20868, "text": "Construct Binary Tree from String with bracket representation" }, { "code": null, "e": 20952, "s": 20930, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 20977, "s": 20952, "text": "Reverse individual words" } ]
time.Since() Function in Golang With Examples
21 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Since() function in Go language holds time value and is used to evaluate the difference with the actual time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func Since(t Time) Duration Here, t is the time value. Note: This method is shortcut for time.Now().Sub(t). Return value: It returns a duration value. Example 1: // Golang program to illustrate in Golang // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining time value // of Since method now := time.Now() // Prints time elapse fmt.Println("time elapse:", time.Since(now))} Output: time elapse: 210ns // Can be different at different run times Here, time elapse between now and the current time is printed. So, it can be different at different run times. Example 2: // Golang program to illustrate in Golang // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Calling mainfunc main() { // Defining time value // of Since method timevalue := time.Now() // Calling Since method // with its parameter Duration := time.Since(timevalue) // Prints time elapse in nanoseconds fmt.Println("time elapse in nanoseconds:", Duration.Nanoseconds())} Output: time elapse in nanoseconds: 351 // Can be different at different run times GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 372, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Since() function in Go language holds time value and is used to evaluate the difference with the actual time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 380, "s": 372, "text": "Syntax:" }, { "code": null, "e": 409, "s": 380, "text": "func Since(t Time) Duration\n" }, { "code": null, "e": 436, "s": 409, "text": "Here, t is the time value." }, { "code": null, "e": 489, "s": 436, "text": "Note: This method is shortcut for time.Now().Sub(t)." }, { "code": null, "e": 532, "s": 489, "text": "Return value: It returns a duration value." }, { "code": null, "e": 543, "s": 532, "text": "Example 1:" }, { "code": "// Golang program to illustrate in Golang // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining time value // of Since method now := time.Now() // Prints time elapse fmt.Println(\"time elapse:\", time.Since(now))}", "e": 868, "s": 543, "text": null }, { "code": null, "e": 876, "s": 868, "text": "Output:" }, { "code": null, "e": 939, "s": 876, "text": "time elapse: 210ns // Can be different at different run times\n" }, { "code": null, "e": 1050, "s": 939, "text": "Here, time elapse between now and the current time is printed. So, it can be different at different run times." }, { "code": null, "e": 1061, "s": 1050, "text": "Example 2:" }, { "code": "// Golang program to illustrate in Golang // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Calling mainfunc main() { // Defining time value // of Since method timevalue := time.Now() // Calling Since method // with its parameter Duration := time.Since(timevalue) // Prints time elapse in nanoseconds fmt.Println(\"time elapse in nanoseconds:\", Duration.Nanoseconds())}", "e": 1527, "s": 1061, "text": null }, { "code": null, "e": 1535, "s": 1527, "text": "Output:" }, { "code": null, "e": 1611, "s": 1535, "text": "time elapse in nanoseconds: 351 // Can be different at different run times\n" }, { "code": null, "e": 1623, "s": 1611, "text": "GoLang-time" }, { "code": null, "e": 1635, "s": 1623, "text": "Go Language" } ]
How to select an element by name with jQuery ?
24 Nov, 2021 In this article, we will learn to get the selected element by name in jQuery. An element can be selected by the name attribute using 2 methods: By using the name selector method By using JavaScript to get the element by name and passing it on to jQuery We will understand both methods with the help of examples. Method 1: Using the name selector method The name attribute selector can be used to select an element by its name. This selector selects elements that have the value exactly equal to the specified value. Syntax: [name="nameOfElement"] Example: This example illustrates the use of the name selector method to select the specific element. HTML <!DOCTYPE html><html> <head> <title> How to select an element by name with jQuery? </title></head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <b>How to select an element by name with jQuery?</b> <p> The textbox below has the <b>name attribute 'address'.</b> <form> <textarea rows="4" cols="40" name="address"></textarea> </form> </p> <p> The textbox below has the <b>name attribute 'area'.</b> <form> <input type="text" name="area"> </form> </p> <p>Click on the button to hide the input with the name 'area'</p> <button onclick="selectByName()"> Click to hide the area input </button> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> function selectByName() { element = $('[name="area"]'); //hide the element element.hide(); } </script> </center></body> </html> Output: name selector Method Method 2: Using JavaScript to get the element by name and pass it on to jQuery The JavaScript getElementsByName() method can be used to select the required element and this can be passed to a jQuery function to use it further as a jQuery object. Syntax: selector = document.getElementsByName('nameOfElement'); element = $(selector); Example: This example illustrates the use of the getElementsByName() method to get the collection of all elements of a particular document by name HTML <!DOCTYPE html><html> <head> <title> How to select an element by name with jQuery? </title></head> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <b>How to select an element by name with jQuery?</b> <p> The textbox below has the <b>name attribute 'address'.</b> <form> <textarea rows="4" cols="40" name="address"></textarea> </form> </p> <p> The textbox below has the <b>name attribute 'area'.</b> <form> <input type="text" name="area"> </form> </p> <p> Click on the button to hide the input with the name 'address' </p> <button onclick="selectByName()"> Click to hide the address input </button> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> function selectByName() { selector = document.getElementsByName('address'); element = $(selector); // hide the element element.hide(); } </script> </center></body> </html> Output: Getting the element by their name jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. Please refer to the jQuery Tutorial and jQuery Examples article for further details. bhaskargeeksforgeeks jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to get the value in an input text box using jQuery ? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples jQuery | parent() & parents() with Examples 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": "\n24 Nov, 2021" }, { "code": null, "e": 172, "s": 28, "text": "In this article, we will learn to get the selected element by name in jQuery. An element can be selected by the name attribute using 2 methods:" }, { "code": null, "e": 206, "s": 172, "text": "By using the name selector method" }, { "code": null, "e": 281, "s": 206, "text": "By using JavaScript to get the element by name and passing it on to jQuery" }, { "code": null, "e": 340, "s": 281, "text": "We will understand both methods with the help of examples." }, { "code": null, "e": 381, "s": 340, "text": "Method 1: Using the name selector method" }, { "code": null, "e": 544, "s": 381, "text": "The name attribute selector can be used to select an element by its name. This selector selects elements that have the value exactly equal to the specified value." }, { "code": null, "e": 552, "s": 544, "text": "Syntax:" }, { "code": null, "e": 575, "s": 552, "text": "[name=\"nameOfElement\"]" }, { "code": null, "e": 677, "s": 575, "text": "Example: This example illustrates the use of the name selector method to select the specific element." }, { "code": null, "e": 682, "s": 677, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to select an element by name with jQuery? </title></head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to select an element by name with jQuery?</b> <p> The textbox below has the <b>name attribute 'address'.</b> <form> <textarea rows=\"4\" cols=\"40\" name=\"address\"></textarea> </form> </p> <p> The textbox below has the <b>name attribute 'area'.</b> <form> <input type=\"text\" name=\"area\"> </form> </p> <p>Click on the button to hide the input with the name 'area'</p> <button onclick=\"selectByName()\"> Click to hide the area input </button> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> function selectByName() { element = $('[name=\"area\"]'); //hide the element element.hide(); } </script> </center></body> </html>", "e": 1819, "s": 682, "text": null }, { "code": null, "e": 1827, "s": 1819, "text": "Output:" }, { "code": null, "e": 1848, "s": 1827, "text": "name selector Method" }, { "code": null, "e": 1927, "s": 1848, "text": "Method 2: Using JavaScript to get the element by name and pass it on to jQuery" }, { "code": null, "e": 2094, "s": 1927, "text": "The JavaScript getElementsByName() method can be used to select the required element and this can be passed to a jQuery function to use it further as a jQuery object." }, { "code": null, "e": 2102, "s": 2094, "text": "Syntax:" }, { "code": null, "e": 2181, "s": 2102, "text": "selector = document.getElementsByName('nameOfElement');\nelement = $(selector);" }, { "code": null, "e": 2328, "s": 2181, "text": "Example: This example illustrates the use of the getElementsByName() method to get the collection of all elements of a particular document by name" }, { "code": null, "e": 2333, "s": 2328, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to select an element by name with jQuery? </title></head> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to select an element by name with jQuery?</b> <p> The textbox below has the <b>name attribute 'address'.</b> <form> <textarea rows=\"4\" cols=\"40\" name=\"address\"></textarea> </form> </p> <p> The textbox below has the <b>name attribute 'area'.</b> <form> <input type=\"text\" name=\"area\"> </form> </p> <p> Click on the button to hide the input with the name 'address' </p> <button onclick=\"selectByName()\"> Click to hide the address input </button> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> function selectByName() { selector = document.getElementsByName('address'); element = $(selector); // hide the element element.hide(); } </script> </center></body> </html>", "e": 3556, "s": 2333, "text": null }, { "code": null, "e": 3564, "s": 3556, "text": "Output:" }, { "code": null, "e": 3598, "s": 3564, "text": "Getting the element by their name" }, { "code": null, "e": 3855, "s": 3598, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. Please refer to the jQuery Tutorial and jQuery Examples article for further details." }, { "code": null, "e": 3876, "s": 3855, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3893, "s": 3876, "text": "jQuery-Questions" }, { "code": null, "e": 3900, "s": 3893, "text": "Picked" }, { "code": null, "e": 3907, "s": 3900, "text": "JQuery" }, { "code": null, "e": 3924, "s": 3907, "text": "Web Technologies" }, { "code": null, "e": 4022, "s": 3924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4079, "s": 4022, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 4152, "s": 4079, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 4175, "s": 4152, "text": "jQuery | ajax() Method" }, { "code": null, "e": 4211, "s": 4175, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 4255, "s": 4211, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 4288, "s": 4255, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4350, "s": 4288, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4411, "s": 4350, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4461, "s": 4411, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Length of longest rod that can fit into a cuboid
09 Nov, 2021 Given the length, breadth, and height of a cuboid, the task is to find the length of the longest rod that can fit in a cuboid.Examples: Input: length = 12, breadth = 9, height = 8 Output: 17 Input: length = 22, breadth = 19, height = 8 Output: 30.1496 Explanation: In the figure GH = length, GF = breadth, FB= height The length of the longest rod is BH. Therefore to compute BH we can apply Pythagoras Theorem in Triangle BHF. From triangle HGF we can compute the length of FH. After getting the length of FH we can find the length of BH using Pythagoras theorem in triangle BHF. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to find the longest rod// that can fit in a cuboid#include <bits/stdc++.h>using namespace std; // Function to find the lengthdouble longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = sqrt(temp); return result;} // Driver codeint main(){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() function to // get the length of longest rod cout << longestRodInCuboid(length, breadth, height); return 0;} // Java program to find the longest// rod that can fit in a cuboidclass GFG{ // Function to find the lengthstatic double longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.sqrt(temp); return result;} // Driver Codepublic static void main(String[] args){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() // function to get the length // of longest rod System.out.println((int)longestRodInCuboid(length, breadth, height));}} // This code is contributed by ChitraNayal # Python 3 program to find the longest rod# that can fit in a cuboid # from math lib. import everythingfrom math import * # Function to find the lengthdef longestRodInCuboid(length, breadth, height) : # temporary variable to hold # the intermediate result temp = length * length + breadth * breadth + height * height # length of longest rod is calculated # using square root function result = sqrt(temp) return result # Driver Codeif __name__ == "__main__" : length, breadth, height = 12, 9, 8 # calling longestRodInCuboid() function to # get the length of longest rod print(longestRodInCuboid(length, breadth, height)) # This code is contributed by ANKITRAI1 // C# program to find the longest// rod that can fit in a cuboidusing System;class GFG{ // Function to find the lengthstatic double longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.Sqrt(temp); return result;} // Driver Codepublic static void Main(){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() // function to get the length // of longest rod Console.WriteLine((int)longestRodInCuboid(length, breadth, height));}} // This code is contributed by inder_verma.. <?php// PHP program to find the longest// rod that can fit in a cuboid // Function to find the lengthfunction longestRodInCuboid($length, $breadth, $height){ $result; $temp; // temporary variable to hold // the intermediate result $temp = $length * $length + $breadth * $breadth + $height * $height; // length of longest rod is // calculated using square // root function $result = sqrt($temp); return $result;} // Driver code $length = 12; $breadth = 9;$height = 8; // calling longestRodInCuboid()// function to get the length// of longest rodecho longestRodInCuboid($length, $breadth, $height); // This code is contributed// by inder_verma..?> <script> // JavaScript program to find the longest rod// that can fit in a cuboid // Function to find the lengthfunction longestRodInCuboid(length, breadth, height){ let result; let temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.sqrt(temp); return result;} // Driver code let length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() function to // get the length of longest rod document.write(longestRodInCuboid(length, breadth, height)); // This code is contributed by Surbhi Tyagi. </script> 17 Time Complexity: O(1) Auxiliary Space: O(1) ankthon ukasp inderDuMCA surbhityagi15 rohitkumarsinghcna Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum Manhattan distance between a distinct pair from N coordinates Total area of two overlapping rectangles Equation of circle when three points on the circle are given Orientation of 3 ordered points Program to find line passing through 2 Points Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Nov, 2021" }, { "code": null, "e": 166, "s": 28, "text": "Given the length, breadth, and height of a cuboid, the task is to find the length of the longest rod that can fit in a cuboid.Examples: " }, { "code": null, "e": 283, "s": 166, "text": "Input: length = 12, breadth = 9, height = 8\nOutput: 17\n\nInput: length = 22, breadth = 19, height = 8\nOutput: 30.1496" }, { "code": null, "e": 316, "s": 287, "text": "Explanation: In the figure " }, { "code": null, "e": 354, "s": 316, "text": "GH = length, GF = breadth, FB= height" }, { "code": null, "e": 516, "s": 354, "text": "The length of the longest rod is BH. Therefore to compute BH we can apply Pythagoras Theorem in Triangle BHF. From triangle HGF we can compute the length of FH. " }, { "code": null, "e": 619, "s": 516, "text": "After getting the length of FH we can find the length of BH using Pythagoras theorem in triangle BHF. " }, { "code": null, "e": 672, "s": 619, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 676, "s": 672, "text": "C++" }, { "code": null, "e": 681, "s": 676, "text": "Java" }, { "code": null, "e": 690, "s": 681, "text": "Python 3" }, { "code": null, "e": 693, "s": 690, "text": "C#" }, { "code": null, "e": 697, "s": 693, "text": "PHP" }, { "code": null, "e": 708, "s": 697, "text": "Javascript" }, { "code": "// C++ program to find the longest rod// that can fit in a cuboid#include <bits/stdc++.h>using namespace std; // Function to find the lengthdouble longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = sqrt(temp); return result;} // Driver codeint main(){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() function to // get the length of longest rod cout << longestRodInCuboid(length, breadth, height); return 0;}", "e": 1451, "s": 708, "text": null }, { "code": "// Java program to find the longest// rod that can fit in a cuboidclass GFG{ // Function to find the lengthstatic double longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.sqrt(temp); return result;} // Driver Codepublic static void main(String[] args){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() // function to get the length // of longest rod System.out.println((int)longestRodInCuboid(length, breadth, height));}} // This code is contributed by ChitraNayal", "e": 2356, "s": 1451, "text": null }, { "code": "# Python 3 program to find the longest rod# that can fit in a cuboid # from math lib. import everythingfrom math import * # Function to find the lengthdef longestRodInCuboid(length, breadth, height) : # temporary variable to hold # the intermediate result temp = length * length + breadth * breadth + height * height # length of longest rod is calculated # using square root function result = sqrt(temp) return result # Driver Codeif __name__ == \"__main__\" : length, breadth, height = 12, 9, 8 # calling longestRodInCuboid() function to # get the length of longest rod print(longestRodInCuboid(length, breadth, height)) # This code is contributed by ANKITRAI1", "e": 3058, "s": 2356, "text": null }, { "code": "// C# program to find the longest// rod that can fit in a cuboidusing System;class GFG{ // Function to find the lengthstatic double longestRodInCuboid(int length, int breadth, int height){ double result; int temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.Sqrt(temp); return result;} // Driver Codepublic static void Main(){ int length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() // function to get the length // of longest rod Console.WriteLine((int)longestRodInCuboid(length, breadth, height));}} // This code is contributed by inder_verma..", "e": 3957, "s": 3058, "text": null }, { "code": "<?php// PHP program to find the longest// rod that can fit in a cuboid // Function to find the lengthfunction longestRodInCuboid($length, $breadth, $height){ $result; $temp; // temporary variable to hold // the intermediate result $temp = $length * $length + $breadth * $breadth + $height * $height; // length of longest rod is // calculated using square // root function $result = sqrt($temp); return $result;} // Driver code $length = 12; $breadth = 9;$height = 8; // calling longestRodInCuboid()// function to get the length// of longest rodecho longestRodInCuboid($length, $breadth, $height); // This code is contributed// by inder_verma..?>", "e": 4735, "s": 3957, "text": null }, { "code": "<script> // JavaScript program to find the longest rod// that can fit in a cuboid // Function to find the lengthfunction longestRodInCuboid(length, breadth, height){ let result; let temp; // temporary variable to hold // the intermediate result temp = length * length + breadth * breadth + height * height; // length of longest rod is calculated // using square root function result = Math.sqrt(temp); return result;} // Driver code let length = 12, breadth = 9, height = 8; // calling longestRodInCuboid() function to // get the length of longest rod document.write(longestRodInCuboid(length, breadth, height)); // This code is contributed by Surbhi Tyagi. </script>", "e": 5492, "s": 4735, "text": null }, { "code": null, "e": 5495, "s": 5492, "text": "17" }, { "code": null, "e": 5519, "s": 5497, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5541, "s": 5519, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5549, "s": 5541, "text": "ankthon" }, { "code": null, "e": 5555, "s": 5549, "text": "ukasp" }, { "code": null, "e": 5566, "s": 5555, "text": "inderDuMCA" }, { "code": null, "e": 5580, "s": 5566, "text": "surbhityagi15" }, { "code": null, "e": 5599, "s": 5580, "text": "rohitkumarsinghcna" }, { "code": null, "e": 5609, "s": 5599, "text": "Geometric" }, { "code": null, "e": 5622, "s": 5609, "text": "Mathematical" }, { "code": null, "e": 5635, "s": 5622, "text": "Mathematical" }, { "code": null, "e": 5645, "s": 5635, "text": "Geometric" }, { "code": null, "e": 5743, "s": 5645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5813, "s": 5743, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 5854, "s": 5813, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 5915, "s": 5854, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 5947, "s": 5915, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 5993, "s": 5947, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 6023, "s": 5993, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 6066, "s": 6023, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6126, "s": 6066, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6141, "s": 6126, "text": "C++ Data Types" } ]
How to Obtain the Phone Number of the Android Phone Programmatically?
06 Jun, 2021 While creating an android app, many times we need authentication by mobile number. To enhance the user experience, we can auto-detect the mobile number in a mobile system. So let’s start an android project! We will create a button, when clicked it will get a mobile number and display it in TextView. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Create a TextView to display the mobile number. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/phone_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.149" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.292" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="#11FF01" android:onClick="GetNumber" android:text="Get Mobile Number" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.679" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.499" /> </androidx.constraintlayout.widget.ConstraintLayout> Note: android:backgroundTint used to change the color of the button. Step 3: Add permission in the manifest file Now about permission, we are doing detection using the ‘Telephony’ class. You should ask the user for 2 permissions Read phone stateRead Mobile Numbers Read phone state Read Mobile Numbers XML <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /> Add above code in manifest.xml file. Now let’s get toward the working of the app i.e. onclickListener of a button. Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. About telephony class: Enables the app to access information about the telephony services on the android device. We can determine telephony services and states, as well as access some types of subscriber information. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.content.pm.PackageManager;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Build;import android.os.Bundle;import android.telephony.TelephonyManager;import android.view.View;import android.widget.TextView; import androidx.annotation.RequiresApi;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import static android.Manifest.permission.READ_PHONE_NUMBERS;import static android.Manifest.permission.READ_PHONE_STATE;import static android.Manifest.permission.READ_SMS; public class MainActivity extends AppCompatActivity { TextView phone_number; @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionbar = getSupportActionBar(); actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#11FF01"))); // Binding views phone_number = findViewById(R.id.phone_number); } // Function will run after click to button public void GetNumber(View v) { if (ActivityCompat.checkSelfPermission(this, READ_SMS) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { // Permission check // Create obj of TelephonyManager and ask for current telephone service TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String phoneNumber = telephonyManager.getLine1Number(); phone_number.setText(phoneNumber); return; } else { // Ask for permission requestPermission(); } } private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, 100); } } public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 100: TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } String phoneNumber = telephonyManager.getLine1Number(); phone_number.setText(phoneNumber); break; default: throw new IllegalStateException("Unexpected value: " + requestCode); } }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 330, "s": 28, "text": "While creating an android app, many times we need authentication by mobile number. To enhance the user experience, we can auto-detect the mobile number in a mobile system. So let’s start an android project! We will create a button, when clicked it will get a mobile number and display it in TextView." }, { "code": null, "e": 359, "s": 330, "text": "Step 1: Create a New Project" }, { "code": null, "e": 521, "s": 359, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 569, "s": 521, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 759, "s": 569, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Create a TextView to display the mobile number. Below is the code for the activity_main.xml file." }, { "code": null, "e": 763, "s": 759, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/phone_number\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"18sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.149\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.292\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"#11FF01\" android:onClick=\"GetNumber\" android:text=\"Get Mobile Number\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.679\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.499\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2229, "s": 763, "text": null }, { "code": null, "e": 2299, "s": 2229, "text": "Note: android:backgroundTint used to change the color of the button. " }, { "code": null, "e": 2343, "s": 2299, "text": "Step 3: Add permission in the manifest file" }, { "code": null, "e": 2459, "s": 2343, "text": "Now about permission, we are doing detection using the ‘Telephony’ class. You should ask the user for 2 permissions" }, { "code": null, "e": 2495, "s": 2459, "text": "Read phone stateRead Mobile Numbers" }, { "code": null, "e": 2512, "s": 2495, "text": "Read phone state" }, { "code": null, "e": 2532, "s": 2512, "text": "Read Mobile Numbers" }, { "code": null, "e": 2536, "s": 2532, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.READ_PHONE_NUMBERS\" /><uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />", "e": 2679, "s": 2536, "text": null }, { "code": null, "e": 2795, "s": 2679, "text": "Add above code in manifest.xml file. Now let’s get toward the working of the app i.e. onclickListener of a button. " }, { "code": null, "e": 2843, "s": 2795, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 3250, "s": 2843, "text": "Go to the MainActivity.java file and refer to the following code. About telephony class: Enables the app to access information about the telephony services on the android device. We can determine telephony services and states, as well as access some types of subscriber information. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3255, "s": 3250, "text": "Java" }, { "code": "import android.content.Context;import android.content.pm.PackageManager;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Build;import android.os.Bundle;import android.telephony.TelephonyManager;import android.view.View;import android.widget.TextView; import androidx.annotation.RequiresApi;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import static android.Manifest.permission.READ_PHONE_NUMBERS;import static android.Manifest.permission.READ_PHONE_STATE;import static android.Manifest.permission.READ_SMS; public class MainActivity extends AppCompatActivity { TextView phone_number; @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionbar = getSupportActionBar(); actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(\"#11FF01\"))); // Binding views phone_number = findViewById(R.id.phone_number); } // Function will run after click to button public void GetNumber(View v) { if (ActivityCompat.checkSelfPermission(this, READ_SMS) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { // Permission check // Create obj of TelephonyManager and ask for current telephone service TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String phoneNumber = telephonyManager.getLine1Number(); phone_number.setText(phoneNumber); return; } else { // Ask for permission requestPermission(); } } private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, 100); } } public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 100: TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } String phoneNumber = telephonyManager.getLine1Number(); phone_number.setText(phoneNumber); break; default: throw new IllegalStateException(\"Unexpected value: \" + requestCode); } }}", "e": 6494, "s": 3255, "text": null }, { "code": null, "e": 6503, "s": 6494, "text": "Output: " }, { "code": null, "e": 6511, "s": 6503, "text": "Android" }, { "code": null, "e": 6516, "s": 6511, "text": "Java" }, { "code": null, "e": 6521, "s": 6516, "text": "Java" }, { "code": null, "e": 6529, "s": 6521, "text": "Android" } ]
What is chunk in Node.js ?
25 Apr, 2022 The data is a transfer from server to client for a particular request in the form of a stream. The stream contains chunks. A chunk is a fragment of the data that is sent by the client to server all chunks concepts to each other to make a buffer of the stream then the buffer is converted into meaningful data. In this article, we will discuss how to send chunks from the request body to the server. The request object is used for handling the chunks of data. Syntax: request.on('eventName',callback) Parameters: This function accepts the following two parameters: eventName: It is the name of the event that fired callback: It is the Callback function i.e Event handler of the particular event. Return type: The return type of this method is void. Example: Create an index.js file with the following code. index.js // Importing http librariesconst http = require('http'); // Creating a serverconst server = http.createServer((req, res) => { const url = req.url; const method = req.method; if (url === '/') { // Sending the response res.write('<html>'); res.write('<head><title>Enter Message</title><head>'); res.write(`<body><form action="/message" method="POST"> <input type="text" name="message"></input> <button type="submit">Send</button></form></body></html>`); res.write('</html>'); return res.end(); } // Handling different routes for different type request if (url === '/message' && method === 'POST') { const body = []; req.on('data', (chunk) => { // Storing the chunk data body.push(chunk); console.log(body) }); req.on('end', () => { // Parsing the chunk data const parsedBody = Buffer.concat(body).toString(); const message = parsedBody.split('=')[1]; // Printing the data console.log(message); }); res.statusCode = 302; res.setHeader('Location', '/'); return res.end(); }}); // Starting the serverserver.listen(3000); Run index.js file using below command: node index.js Now open a browser and go to http://localhost:3000, you will see the following output. Console Output: rkbhola5 Node.js-Buffer-module Node.js-Methods NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Apr, 2022" }, { "code": null, "e": 512, "s": 53, "text": "The data is a transfer from server to client for a particular request in the form of a stream. The stream contains chunks. A chunk is a fragment of the data that is sent by the client to server all chunks concepts to each other to make a buffer of the stream then the buffer is converted into meaningful data. In this article, we will discuss how to send chunks from the request body to the server. The request object is used for handling the chunks of data." }, { "code": null, "e": 520, "s": 512, "text": "Syntax:" }, { "code": null, "e": 553, "s": 520, "text": "request.on('eventName',callback)" }, { "code": null, "e": 617, "s": 553, "text": "Parameters: This function accepts the following two parameters:" }, { "code": null, "e": 667, "s": 617, "text": "eventName: It is the name of the event that fired" }, { "code": null, "e": 748, "s": 667, "text": "callback: It is the Callback function i.e Event handler of the particular event." }, { "code": null, "e": 801, "s": 748, "text": "Return type: The return type of this method is void." }, { "code": null, "e": 859, "s": 801, "text": "Example: Create an index.js file with the following code." }, { "code": null, "e": 868, "s": 859, "text": "index.js" }, { "code": "// Importing http librariesconst http = require('http'); // Creating a serverconst server = http.createServer((req, res) => { const url = req.url; const method = req.method; if (url === '/') { // Sending the response res.write('<html>'); res.write('<head><title>Enter Message</title><head>'); res.write(`<body><form action=\"/message\" method=\"POST\"> <input type=\"text\" name=\"message\"></input> <button type=\"submit\">Send</button></form></body></html>`); res.write('</html>'); return res.end(); } // Handling different routes for different type request if (url === '/message' && method === 'POST') { const body = []; req.on('data', (chunk) => { // Storing the chunk data body.push(chunk); console.log(body) }); req.on('end', () => { // Parsing the chunk data const parsedBody = Buffer.concat(body).toString(); const message = parsedBody.split('=')[1]; // Printing the data console.log(message); }); res.statusCode = 302; res.setHeader('Location', '/'); return res.end(); }}); // Starting the serverserver.listen(3000);", "e": 2127, "s": 868, "text": null }, { "code": null, "e": 2166, "s": 2127, "text": "Run index.js file using below command:" }, { "code": null, "e": 2180, "s": 2166, "text": "node index.js" }, { "code": null, "e": 2267, "s": 2180, "text": "Now open a browser and go to http://localhost:3000, you will see the following output." }, { "code": null, "e": 2283, "s": 2267, "text": "Console Output:" }, { "code": null, "e": 2292, "s": 2283, "text": "rkbhola5" }, { "code": null, "e": 2314, "s": 2292, "text": "Node.js-Buffer-module" }, { "code": null, "e": 2330, "s": 2314, "text": "Node.js-Methods" }, { "code": null, "e": 2347, "s": 2330, "text": "NodeJS-Questions" }, { "code": null, "e": 2354, "s": 2347, "text": "Picked" }, { "code": null, "e": 2362, "s": 2354, "text": "Node.js" }, { "code": null, "e": 2379, "s": 2362, "text": "Web Technologies" }, { "code": null, "e": 2477, "s": 2379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2509, "s": 2477, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2544, "s": 2509, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2614, "s": 2544, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2641, "s": 2614, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2666, "s": 2641, "text": "Mongoose find() Function" }, { "code": null, "e": 2728, "s": 2666, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2789, "s": 2728, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2839, "s": 2789, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2882, "s": 2839, "text": "How to fetch data from an API in ReactJS ?" } ]
How to sort HashSet in Java
11 Dec, 2018 Given a HashSet in Java, the task is to sort this HashSet. Examples: Input: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks] Output: [For, ForGeeks, Geeks, GeeksforGeeks] Input: HashSet: [2, 5, 3, 1, 4] Output: [1, 2, 3, 4, 5] The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type. Below is the implementation of the above approach: Program 1: By Converting HashSet to List. // Java program to sort a HashSet import java.util.*; public class GFG { public static void main(String args[]) { // Creating a HashSet HashSet<String> set = new HashSet<String>(); // Adding elements into HashSet using add() set.add("geeks"); set.add("practice"); set.add("contribute"); set.add("ide"); System.out.println("Original HashSet: " + set); // Sorting HashSet using List List<String> list = new ArrayList<String>(set); Collections.sort(list); // Print the sorted elements of the HashSet System.out.println("HashSet elements " + "in sorted order " + "using List: " + list); }} Original HashSet: [practice, geeks, contribute, ide] HashSet elements in sorted order using List: [contribute, geeks, ide, practice] Program 2: By Converting HashSet to TreeSet. // Java program to sort a HashSet import java.util.*; public class GFG { public static void main(String args[]) { // Creating a HashSet HashSet<String> set = new HashSet<String>(); // Adding elements into HashSet using add() set.add("geeks"); set.add("practice"); set.add("contribute"); set.add("ide"); System.out.println("Original HashSet: " + set); // Sorting HashSet using TreeSet TreeSet<String> treeSet = new TreeSet<String>(set); // Print the sorted elements of the HashSet System.out.println("HashSet elements " + "in sorted order " + "using TreeSet: " + treeSet); }} Original HashSet: [practice, geeks, contribute, ide] HashSet elements in sorted order using TreeSet: [contribute, geeks, ide, practice] Java-Collections java-hashset Java-Set-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2018" }, { "code": null, "e": 113, "s": 54, "text": "Given a HashSet in Java, the task is to sort this HashSet." }, { "code": null, "e": 123, "s": 113, "text": "Examples:" }, { "code": null, "e": 282, "s": 123, "text": "Input: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks]\nOutput: [For, ForGeeks, Geeks, GeeksforGeeks]\n\nInput: HashSet: [2, 5, 3, 1, 4]\nOutput: [1, 2, 3, 4, 5] \n" }, { "code": null, "e": 537, "s": 282, "text": "The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time." }, { "code": null, "e": 647, "s": 537, "text": "It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible." }, { "code": null, "e": 821, "s": 647, "text": "However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type." }, { "code": null, "e": 872, "s": 821, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 914, "s": 872, "text": "Program 1: By Converting HashSet to List." }, { "code": "// Java program to sort a HashSet import java.util.*; public class GFG { public static void main(String args[]) { // Creating a HashSet HashSet<String> set = new HashSet<String>(); // Adding elements into HashSet using add() set.add(\"geeks\"); set.add(\"practice\"); set.add(\"contribute\"); set.add(\"ide\"); System.out.println(\"Original HashSet: \" + set); // Sorting HashSet using List List<String> list = new ArrayList<String>(set); Collections.sort(list); // Print the sorted elements of the HashSet System.out.println(\"HashSet elements \" + \"in sorted order \" + \"using List: \" + list); }}", "e": 1714, "s": 914, "text": null }, { "code": null, "e": 1848, "s": 1714, "text": "Original HashSet: [practice, geeks, contribute, ide]\nHashSet elements in sorted order using List: [contribute, geeks, ide, practice]\n" }, { "code": null, "e": 1893, "s": 1848, "text": "Program 2: By Converting HashSet to TreeSet." }, { "code": "// Java program to sort a HashSet import java.util.*; public class GFG { public static void main(String args[]) { // Creating a HashSet HashSet<String> set = new HashSet<String>(); // Adding elements into HashSet using add() set.add(\"geeks\"); set.add(\"practice\"); set.add(\"contribute\"); set.add(\"ide\"); System.out.println(\"Original HashSet: \" + set); // Sorting HashSet using TreeSet TreeSet<String> treeSet = new TreeSet<String>(set); // Print the sorted elements of the HashSet System.out.println(\"HashSet elements \" + \"in sorted order \" + \"using TreeSet: \" + treeSet); }}", "e": 2677, "s": 1893, "text": null }, { "code": null, "e": 2814, "s": 2677, "text": "Original HashSet: [practice, geeks, contribute, ide]\nHashSet elements in sorted order using TreeSet: [contribute, geeks, ide, practice]\n" }, { "code": null, "e": 2831, "s": 2814, "text": "Java-Collections" }, { "code": null, "e": 2844, "s": 2831, "text": "java-hashset" }, { "code": null, "e": 2862, "s": 2844, "text": "Java-Set-Programs" }, { "code": null, "e": 2867, "s": 2862, "text": "Java" }, { "code": null, "e": 2872, "s": 2867, "text": "Java" }, { "code": null, "e": 2889, "s": 2872, "text": "Java-Collections" }, { "code": null, "e": 2987, "s": 2889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3002, "s": 2987, "text": "Arrays in Java" }, { "code": null, "e": 3046, "s": 3002, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3082, "s": 3046, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3133, "s": 3082, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3158, "s": 3133, "text": "Reverse a string in Java" }, { "code": null, "e": 3180, "s": 3158, "text": "For-each loop in Java" }, { "code": null, "e": 3211, "s": 3180, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3230, "s": 3211, "text": "Interfaces in Java" }, { "code": null, "e": 3260, "s": 3230, "text": "HashMap in Java with Examples" } ]
Sum of first n term of Series 3, 5, 9, 17, 33....
27 Apr, 2021 Given n, we need to find sum of first n terms of the series represented as Sn = 3 + 5 + 9 + 17 + 33 ... upto nExamples: Input : 2 Output : 8 3 + 5 = 8 Input : 5 Output : 67 3 + 5 + 9 + 17 + 33 = 67 Let, the nth term be denoted by tn. This problem can easily be solved by splitting each term as follows : Sn = 3 + 5 + 9 + 17 + 33...... Sn = (2+1) + (4+1) + (8+1) + (16+1) +...... Sn = (2+1) + (2*2+1) + (2*2*2+1) + (2*2*2*2+1) +......+ ((2*2*2..unto n times) + 1) We observed that the nth term can be written in terms of powers of 2 and 1. Hence, the sum of first n terms is given as follows: Sn = (2+1) + (4+1) + (8+1) + (16+1) +......+ upto n terms Sn = (1 + 1 + 1 + 1 + ...unto n terms) + (2 + 4 + 8 + 16 + ...upto nth power of 2) In above formula, 2 + 4 + 8 + 16.... is a G.P. It’s sum of first n terms is given by 2*(2^n-1)/(2-1) = 2^(n+1) – 2 (using G.P. formula) Sn = n + 2*(2^n – 1) Sn = 2^(n+1) + n -2 C++ Java Python C# PHP Javascript // C++ program to find sum of first n terms#include <bits/stdc++.h>using namespace std; int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (pow(2, n + 1) + n - 2);} // Driver codeint main(){ // number of terms to be included in sum int n = 4; // find the Sn cout << "Sum = " << calculateSum(n); return 0;} // Java program to find// sum of first n termsimport java.util.*; class GFG{static int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return ((int)Math.pow(2, n + 1) + n - 2);} // Driver Codepublic static void main(String args[]){ // number of terms to // be included in sum int n = 4; // find the Sn System.out.println("Sum = " + calculateSum(n));}} // This code is contributed// by Kirti_Mangal # Python program to find sum# of n terms of the seriesdef calculateSum(n): return (2**(n + 1) + n - 2) # Driver Code # number of terms for the sumn = 4 # find the Snprint("Sum =", calculateSum(n)) # This code is contributed# by Surendra_Gangwar //C# program to find// sum of first n termsusing System; class GFG{static int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return ((int)Math.Pow(2, n + 1) + n - 2);} // Driver Codepublic static void Main(){ // number of terms to // be included in sum int n = 4; // find the Sn Console.WriteLine("Sum = " + calculateSum(n));}} // This code is contributed// by inder_verma.. <?php// PHP program to find sum// of first n termsfunction calculateSum( $n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (pow(2, $n + 1) + $n - 2);} // Driver code // number of terms to be// included in sum$n = 4; // find the Snecho "Sum = " , calculateSum($n); // This code is contributed// by inder_verma..?> <script>// Java script program to find// sum of first n terms function calculateSum( n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (Math.pow(2, n + 1) + n - 2);} // Driver Code // number of terms to // be included in sum let n = 4; // find the Sn document.write("Sum = " + calculateSum(n)); // This code is contributed by mohan pavan </script> Sum = 34 Kirti_Mangal SURENDRA_GANGWAR inderDuMCA shubham_singh pulamolusaimohan series series-sum C++ Programs Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Apr, 2021" }, { "code": null, "e": 174, "s": 52, "text": "Given n, we need to find sum of first n terms of the series represented as Sn = 3 + 5 + 9 + 17 + 33 ... upto nExamples: " }, { "code": null, "e": 253, "s": 174, "text": "Input : 2\nOutput : 8\n3 + 5 = 8\n\nInput : 5\nOutput : 67\n3 + 5 + 9 + 17 + 33 = 67" }, { "code": null, "e": 362, "s": 255, "text": "Let, the nth term be denoted by tn. This problem can easily be solved by splitting each term as follows : " }, { "code": null, "e": 521, "s": 362, "text": "Sn = 3 + 5 + 9 + 17 + 33...... Sn = (2+1) + (4+1) + (8+1) + (16+1) +...... Sn = (2+1) + (2*2+1) + (2*2*2+1) + (2*2*2*2+1) +......+ ((2*2*2..unto n times) + 1)" }, { "code": null, "e": 651, "s": 521, "text": "We observed that the nth term can be written in terms of powers of 2 and 1. Hence, the sum of first n terms is given as follows: " }, { "code": null, "e": 969, "s": 651, "text": "Sn = (2+1) + (4+1) + (8+1) + (16+1) +......+ upto n terms Sn = (1 + 1 + 1 + 1 + ...unto n terms) + (2 + 4 + 8 + 16 + ...upto nth power of 2) In above formula, 2 + 4 + 8 + 16.... is a G.P. It’s sum of first n terms is given by 2*(2^n-1)/(2-1) = 2^(n+1) – 2 (using G.P. formula) Sn = n + 2*(2^n – 1) Sn = 2^(n+1) + n -2" }, { "code": null, "e": 975, "s": 971, "text": "C++" }, { "code": null, "e": 980, "s": 975, "text": "Java" }, { "code": null, "e": 987, "s": 980, "text": "Python" }, { "code": null, "e": 990, "s": 987, "text": "C#" }, { "code": null, "e": 994, "s": 990, "text": "PHP" }, { "code": null, "e": 1005, "s": 994, "text": "Javascript" }, { "code": "// C++ program to find sum of first n terms#include <bits/stdc++.h>using namespace std; int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (pow(2, n + 1) + n - 2);} // Driver codeint main(){ // number of terms to be included in sum int n = 4; // find the Sn cout << \"Sum = \" << calculateSum(n); return 0;}", "e": 1345, "s": 1005, "text": null }, { "code": "// Java program to find// sum of first n termsimport java.util.*; class GFG{static int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return ((int)Math.pow(2, n + 1) + n - 2);} // Driver Codepublic static void main(String args[]){ // number of terms to // be included in sum int n = 4; // find the Sn System.out.println(\"Sum = \" + calculateSum(n));}} // This code is contributed// by Kirti_Mangal", "e": 1811, "s": 1345, "text": null }, { "code": "# Python program to find sum# of n terms of the seriesdef calculateSum(n): return (2**(n + 1) + n - 2) # Driver Code # number of terms for the sumn = 4 # find the Snprint(\"Sum =\", calculateSum(n)) # This code is contributed# by Surendra_Gangwar", "e": 2060, "s": 1811, "text": null }, { "code": "//C# program to find// sum of first n termsusing System; class GFG{static int calculateSum(int n){ // Sn = n*(4*n*n + 6*n - 1)/3 return ((int)Math.Pow(2, n + 1) + n - 2);} // Driver Codepublic static void Main(){ // number of terms to // be included in sum int n = 4; // find the Sn Console.WriteLine(\"Sum = \" + calculateSum(n));}} // This code is contributed// by inder_verma..", "e": 2503, "s": 2060, "text": null }, { "code": "<?php// PHP program to find sum// of first n termsfunction calculateSum( $n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (pow(2, $n + 1) + $n - 2);} // Driver code // number of terms to be// included in sum$n = 4; // find the Snecho \"Sum = \" , calculateSum($n); // This code is contributed// by inder_verma..?>", "e": 2814, "s": 2503, "text": null }, { "code": "<script>// Java script program to find// sum of first n terms function calculateSum( n){ // Sn = n*(4*n*n + 6*n - 1)/3 return (Math.pow(2, n + 1) + n - 2);} // Driver Code // number of terms to // be included in sum let n = 4; // find the Sn document.write(\"Sum = \" + calculateSum(n)); // This code is contributed by mohan pavan </script>", "e": 3219, "s": 2814, "text": null }, { "code": null, "e": 3228, "s": 3219, "text": "Sum = 34" }, { "code": null, "e": 3243, "s": 3230, "text": "Kirti_Mangal" }, { "code": null, "e": 3260, "s": 3243, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 3271, "s": 3260, "text": "inderDuMCA" }, { "code": null, "e": 3285, "s": 3271, "text": "shubham_singh" }, { "code": null, "e": 3302, "s": 3285, "text": "pulamolusaimohan" }, { "code": null, "e": 3309, "s": 3302, "text": "series" }, { "code": null, "e": 3320, "s": 3309, "text": "series-sum" }, { "code": null, "e": 3333, "s": 3320, "text": "C++ Programs" }, { "code": null, "e": 3346, "s": 3333, "text": "Mathematical" }, { "code": null, "e": 3359, "s": 3346, "text": "Mathematical" }, { "code": null, "e": 3366, "s": 3359, "text": "series" } ]
PostgreSQL – Record type variable
01 Feb, 2021 PostgreSQL uses record type variables which simply act as placeholders for rows of a result set, similar to a row type variable. However, unlike row type variables, they do not have a predefined structure. Their structure is only determined after assigning a row to them. A record type variable also can change its structure after it is reassigned to another row. We can declare a record type variable by simply using a variable name followed by the record keyword. Syntax: variable_name record; We can use the dot notation (.) to access any field from the record type variable. It is important to note that we must assign a record type variable before accessing its contents else, we will get an error. Syntax: record_variable.field_name; First, we create a sample table using the below commands to perform examples: CREATE TABLE employees ( employee_id serial PRIMARY KEY, full_name VARCHAR NOT NULL, manager_id INT ); Then we insert data into our employee table as follows: INSERT INTO employees ( employee_id, full_name, manager_id ) VALUES (1, 'M.S Dhoni', NULL), (2, 'Sachin Tendulkar', 1), (3, 'R. Sharma', 1), (4, 'S. Raina', 1), (5, 'B. Kumar', 1), (6, 'Y. Singh', 2), (7, 'Virender Sehwag ', 2), (8, 'Ajinkya Rahane', 2), (9, 'Shikhar Dhawan', 2), (10, 'Mohammed Shami', 3), (11, 'Shreyas Iyer', 3), (12, 'Mayank Agarwal', 3), (13, 'K. L. Rahul', 3), (14, 'Hardik Pandya', 4), (15, 'Dinesh Karthik', 4), (16, 'Jasprit Bumrah', 7), (17, 'Kuldeep Yadav', 7), (18, 'Yuzvendra Chahal', 8), (19, 'Rishabh Pant', 8), (20, 'Sanju Samson', 8); The table is: Example 1: The following query shows how we can use record type variables in conjecture with the select into statement. do $$ declare rec1 record; begin -- select the employee select employee_id,full_name,manager_id into rec1 from employees where employee_id = 13; raise notice '% - %(Manager id=%)', rec1.employee_id, rec1.full_name, rec1.manager_id; end; $$ language plpgsql; Output: In this example, we followed the following steps: We first declared the record type variable rec1 in the declaration area. We then used the select into the statement to select a row from the table employees into the variable rec1 whose employee id is 13. We then used the dot notation to access the contents of the variable rec1 and then print the information out Example 2: The following query shows how we can use record type variables in conjecture with the for loop statement. do $$ declare rec1 record; begin for rec1 in select employee_id, full_name from employees where employee_id > 12 order by employee_id loop raise notice '% - %', rec1.employee_id, rec1.full_name; end loop; end; $$; Output: This example shows how we can reassign a record type variable. In this example, we followed the following steps: We first declared a record type variable rec1 in the declaration area. We then used the for loop statement to iterate over the contents of the employees table. In each iteration, we assigned a new row to the record type variable rec1. We then used the dot notation to access the contents of the variable rec1 and then print the information out for each iteration. Picked postgreSQL-managing-table Technical Scripter 2020 PostgreSQL Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - IF Statement PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Rename Table PostgreSQL - Variables PostgreSQL - Joins PostgreSQL - ARRAY_AGG() Function PostgreSQL - REPLACE Function PostgreSQL - Introduction to Stored Procedures
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 392, "s": 28, "text": "PostgreSQL uses record type variables which simply act as placeholders for rows of a result set, similar to a row type variable. However, unlike row type variables, they do not have a predefined structure. Their structure is only determined after assigning a row to them. A record type variable also can change its structure after it is reassigned to another row." }, { "code": null, "e": 494, "s": 392, "text": "We can declare a record type variable by simply using a variable name followed by the record keyword." }, { "code": null, "e": 524, "s": 494, "text": "Syntax:\nvariable_name record;" }, { "code": null, "e": 732, "s": 524, "text": "We can use the dot notation (.) to access any field from the record type variable. It is important to note that we must assign a record type variable before accessing its contents else, we will get an error." }, { "code": null, "e": 768, "s": 732, "text": "Syntax:\nrecord_variable.field_name;" }, { "code": null, "e": 846, "s": 768, "text": "First, we create a sample table using the below commands to perform examples:" }, { "code": null, "e": 949, "s": 846, "text": "CREATE TABLE employees (\nemployee_id serial PRIMARY KEY,\nfull_name VARCHAR NOT NULL,\nmanager_id INT\n);" }, { "code": null, "e": 1005, "s": 949, "text": "Then we insert data into our employee table as follows:" }, { "code": null, "e": 1574, "s": 1005, "text": "INSERT INTO employees (\nemployee_id,\nfull_name,\nmanager_id\n)\nVALUES\n(1, 'M.S Dhoni', NULL),\n(2, 'Sachin Tendulkar', 1),\n(3, 'R. Sharma', 1),\n(4, 'S. Raina', 1),\n(5, 'B. Kumar', 1),\n(6, 'Y. Singh', 2),\n(7, 'Virender Sehwag ', 2),\n(8, 'Ajinkya Rahane', 2),\n(9, 'Shikhar Dhawan', 2),\n(10, 'Mohammed Shami', 3),\n(11, 'Shreyas Iyer', 3),\n(12, 'Mayank Agarwal', 3),\n(13, 'K. L. Rahul', 3),\n(14, 'Hardik Pandya', 4),\n(15, 'Dinesh Karthik', 4),\n(16, 'Jasprit Bumrah', 7),\n(17, 'Kuldeep Yadav', 7),\n(18, 'Yuzvendra Chahal', 8),\n(19, 'Rishabh Pant', 8),\n(20, 'Sanju Samson', 8);" }, { "code": null, "e": 1588, "s": 1574, "text": "The table is:" }, { "code": null, "e": 1599, "s": 1588, "text": "Example 1:" }, { "code": null, "e": 1708, "s": 1599, "text": "The following query shows how we can use record type variables in conjecture with the select into statement." }, { "code": null, "e": 1976, "s": 1708, "text": "do\n$$\ndeclare\nrec1 record;\nbegin\n-- select the employee \nselect employee_id,full_name,manager_id\ninto rec1\nfrom employees\nwhere employee_id = 13;\n \nraise notice '% - %(Manager id=%)', rec1.employee_id, rec1.full_name, rec1.manager_id; \n \nend;\n$$\nlanguage plpgsql;" }, { "code": null, "e": 1984, "s": 1976, "text": "Output:" }, { "code": null, "e": 2034, "s": 1984, "text": "In this example, we followed the following steps:" }, { "code": null, "e": 2107, "s": 2034, "text": "We first declared the record type variable rec1 in the declaration area." }, { "code": null, "e": 2239, "s": 2107, "text": "We then used the select into the statement to select a row from the table employees into the variable rec1 whose employee id is 13." }, { "code": null, "e": 2348, "s": 2239, "text": "We then used the dot notation to access the contents of the variable rec1 and then print the information out" }, { "code": null, "e": 2359, "s": 2348, "text": "Example 2:" }, { "code": null, "e": 2465, "s": 2359, "text": "The following query shows how we can use record type variables in conjecture with the for loop statement." }, { "code": null, "e": 2692, "s": 2465, "text": "do\n$$\ndeclare\nrec1 record;\nbegin\nfor rec1 in select employee_id, full_name \n from employees \n where employee_id > 12\n order by employee_id\nloop\n raise notice '% - %', rec1.employee_id, rec1.full_name; \nend loop;\nend;\n$$;" }, { "code": null, "e": 2700, "s": 2692, "text": "Output:" }, { "code": null, "e": 2763, "s": 2700, "text": "This example shows how we can reassign a record type variable." }, { "code": null, "e": 2813, "s": 2763, "text": "In this example, we followed the following steps:" }, { "code": null, "e": 2884, "s": 2813, "text": "We first declared a record type variable rec1 in the declaration area." }, { "code": null, "e": 3048, "s": 2884, "text": "We then used the for loop statement to iterate over the contents of the employees table. In each iteration, we assigned a new row to the record type variable rec1." }, { "code": null, "e": 3177, "s": 3048, "text": "We then used the dot notation to access the contents of the variable rec1 and then print the information out for each iteration." }, { "code": null, "e": 3184, "s": 3177, "text": "Picked" }, { "code": null, "e": 3210, "s": 3184, "text": "postgreSQL-managing-table" }, { "code": null, "e": 3234, "s": 3210, "text": "Technical Scripter 2020" }, { "code": null, "e": 3245, "s": 3234, "text": "PostgreSQL" }, { "code": null, "e": 3264, "s": 3245, "text": "Technical Scripter" }, { "code": null, "e": 3362, "s": 3264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3388, "s": 3362, "text": "PostgreSQL - IF Statement" }, { "code": null, "e": 3411, "s": 3388, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 3451, "s": 3411, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 3489, "s": 3451, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 3515, "s": 3489, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 3538, "s": 3515, "text": "PostgreSQL - Variables" }, { "code": null, "e": 3557, "s": 3538, "text": "PostgreSQL - Joins" }, { "code": null, "e": 3591, "s": 3557, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 3621, "s": 3591, "text": "PostgreSQL - REPLACE Function" } ]
Group Factor Levels in R
14 Sep, 2021 In this article, we will be looking at the approach to group factor level using the base functions of the R Programming language. In this approach to group factor levels, the user has to simply call the levels() functions with the required parameters as required by the user, and then it will be leading to the new factor level as specified by the user in other words we will be merging two-factor levels into one category in the R programming language. Levels() function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute. Syntax: levels(x) levels(x) <- value Parameters: x: an object, for example, a factor. value: A valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels. Example: In this example, we will be creating an initial factor of some elements in the string data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language. R gfg <- factor(c("a","b","c","d","c","a"))gfg gfg1 <- gfg levels(gfg1) <- c("a", "b", "b","b") gfg1 Output: > gfg [1] a b c d c a Levels: a b c d > gfg1 [1] a b b b b a Levels: a b Example: In this example, we will be creating an initial factor of some elements in the integer data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language. R gfg <- factor(c(1,2,3,4,5,1,1,3,3,3,3))gfg gfg1 <- gfg levels(gfg1) <- c(1,5,5,5,5) gfg1 Output: > gfg [1] 1 2 3 4 5 1 1 3 3 3 3 Levels: 1 2 3 4 5 > gfg1 [1] 1 5 5 5 5 1 1 5 5 5 5 Levels: 1 5 Picked R-Factors 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? How to import an Excel File into R ? Replace Specific Characters in String in R Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 158, "s": 28, "text": "In this article, we will be looking at the approach to group factor level using the base functions of the R Programming language." }, { "code": null, "e": 482, "s": 158, "text": "In this approach to group factor levels, the user has to simply call the levels() functions with the required parameters as required by the user, and then it will be leading to the new factor level as specified by the user in other words we will be merging two-factor levels into one category in the R programming language." }, { "code": null, "e": 653, "s": 482, "text": "Levels() function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute." }, { "code": null, "e": 661, "s": 653, "text": "Syntax:" }, { "code": null, "e": 671, "s": 661, "text": "levels(x)" }, { "code": null, "e": 690, "s": 671, "text": "levels(x) <- value" }, { "code": null, "e": 702, "s": 690, "text": "Parameters:" }, { "code": null, "e": 739, "s": 702, "text": "x: an object, for example, a factor." }, { "code": null, "e": 981, "s": 739, "text": "value: A valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels." }, { "code": null, "e": 1205, "s": 981, "text": "Example: In this example, we will be creating an initial factor of some elements in the string data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language." }, { "code": null, "e": 1207, "s": 1205, "text": "R" }, { "code": "gfg <- factor(c(\"a\",\"b\",\"c\",\"d\",\"c\",\"a\"))gfg gfg1 <- gfg levels(gfg1) <- c(\"a\", \"b\", \"b\",\"b\") gfg1", "e": 1348, "s": 1207, "text": null }, { "code": null, "e": 1356, "s": 1348, "text": "Output:" }, { "code": null, "e": 1429, "s": 1356, "text": "> gfg\n[1] a b c d c a\nLevels: a b c d\n> gfg1\n[1] a b b b b a\nLevels: a b" }, { "code": null, "e": 1654, "s": 1429, "text": "Example: In this example, we will be creating an initial factor of some elements in the integer data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language." }, { "code": null, "e": 1656, "s": 1654, "text": "R" }, { "code": "gfg <- factor(c(1,2,3,4,5,1,1,3,3,3,3))gfg gfg1 <- gfg levels(gfg1) <- c(1,5,5,5,5) gfg1", "e": 1787, "s": 1656, "text": null }, { "code": null, "e": 1795, "s": 1787, "text": "Output:" }, { "code": null, "e": 1899, "s": 1795, "text": "> gfg\n [1] 1 2 3 4 5 1 1 3 3 3 3\nLevels: 1 2 3 4 5 \n> gfg1 \n [1] 1 5 5 5 5 1 1 5 5 5 5\nLevels: 1 5" }, { "code": null, "e": 1906, "s": 1899, "text": "Picked" }, { "code": null, "e": 1916, "s": 1906, "text": "R-Factors" }, { "code": null, "e": 1927, "s": 1916, "text": "R Language" }, { "code": null, "e": 2025, "s": 1927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2077, "s": 2025, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2135, "s": 2077, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2170, "s": 2135, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2208, "s": 2170, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2225, "s": 2208, "text": "R - if statement" }, { "code": null, "e": 2262, "s": 2225, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2311, "s": 2262, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2348, "s": 2311, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 2391, "s": 2348, "text": "Replace Specific Characters in String in R" } ]
Unix / Linux - Useful Commands
This quick guide lists commands, including a syntax and a brief description. For more detail, use − $man command These commands allow you to create directories and handle files. cat Displays File Contents cd Changes Directory to dirname chgrp Changes file group chmod Changes permissions cp Copies source file into destination file Determines file type find Finds files grep Searches files for regular expressions head Displays first few lines of a file ln Creates softlink on oldname ls Displays information about file type mkdir Creates a new directory dirname more Displays data in paginated form mv Moves (Renames) an oldname to newname pwd Prints current working directory rm Removes (Deletes) filename rmdir Deletes an existing directory provided it is empty tail Prints last few lines in a file touch Updates access and modification time of a file The contents of files can be compared and altered with the following commands. awk Pattern scanning and processing language cmp Compares the contents of two files comm Compares sorted data cut Cuts out selected fields of each line of a file diff Differential file comparator expand Expands tabs to spaces join Joins files on some common field perl Data manipulation language sed Stream text editor sort Sorts file data split Splits file into smaller files tr Translates characters uniq Reports repeated lines in a file wc Counts words, lines, and characters vi Opens vi text editor vim Opens vim text editor fmt Simple text formatter spell Checks text for spelling error ispell Checks text for spelling error emacs GNU project Emacs ex, edit Line editor emacs GNU project Emacs Files may be compressed to save space. Compressed files can be created and examined. compress Compresses files gunzip Helps uncompress gzipped files gzip GNU alternative compression method uncompress Helps uncompress files unzip List, test and extract compressed files in a ZIP archive zcat Cat a compressed file zcmp Compares compressed files zdiff Compares compressed files zmore File perusal filter for crt viewing of compressed text Various Unix manuals and documentation are available on-line. The following Shell commands give information − apropos Locates commands by keyword lookup info Displays command information pages online man Displays manual pages online whatis Searches the whatis database for complete words yelp GNOME help viewer These following commands are used to send and receive files from a local Unix hosts to the remote host around the world. ftp File transfer program rcp Remote file copy rlogin Remote login to a Unix host rsh Remote shell tftp Trivial file transfer program telnet Makes terminal connection to another host ssh Secures shell terminal or command connection scp Secures shell remote file copy sftp Secures shell file transfer program Some of these commands may be restricted at your computer for security reasons. The Unix systems support on-screen messages to other users and world-wide electronic mail − evolution GUI mail handling tool on Linux mail Simple send or read mail program mesg Permits or denies messages parcel Sends files to another user pine Vdu-based mail utility talk Talks to another user write Writes message to another user The following programming tools and languages are available based on what you have installed on your Unix. dbx Sun debugger gdb GNU debugger make Maintains program groups and compile programs nm Prints program's name list size Prints program's sizes strip Removes symbol table and relocation bits cb C program beautifier cc ANSI C compiler for Suns SPARC systems ctrace C program debugger gcc GNU ANSI C Compiler indent Indent and format C program source bc Interactive arithmetic language processor gcl GNU Common Lisp perl General purpose language php Web page embedded language py Python language interpreter asp Web page embedded language CC C++ compiler for Suns SPARC systems g++ GNU C++ Compiler javac JAVA compiler appletvieweir JAVA applet viewer netbeans Java integrated development environment on Linux sqlplus Runs the Oracle SQL interpreter sqlldr Runs the Oracle SQL data loader mysql Runs the mysql SQL interpreter These commands list or alter information about the system − chfn Changes your finger information chgrp Changes the group ownership of a file chown Changes owner date Prints the date determin Automatically finds terminal type du Prints amount of disk usage echo Echo arguments to the standard options exit Quits the system finger Prints information about logged-in users groupadd Creates a user group groups Show group memberships homequota Shows quota and file usage iostat Reports I/O statistics kill Sends a signal to a process last Shows last logins of users logout Logs off Unix lun Lists user names or login ID netstat Shows network status passwd Changes user password passwd Changes your login password printenv Displays value of a shell variable ps Displays the status of current processes ps Prints process status statistics quota -v Displays disk usage and limits reset Resets terminal mode script Keeps script of terminal session script Saves the output of a command or process setenv Sets environment variables stty Sets terminal options time Helps time a command top Displays all system processes tset Sets terminal mode tty Prints current terminal name umask Show the permissions that are given to view files by default uname Displays name of the current system uptime Gets the system up time useradd Creates a user account users Prints names of logged in users vmstat Reports virtual memory statistics w Shows what logged in users are doing who Lists logged in users
[ { "code": null, "e": 2981, "s": 2881, "text": "This quick guide lists commands, including a syntax and a brief description. For more detail, use −" }, { "code": null, "e": 2995, "s": 2981, "text": "$man command\n" }, { "code": null, "e": 3060, "s": 2995, "text": "These commands allow you to create directories and handle files." }, { "code": null, "e": 3064, "s": 3060, "text": "cat" }, { "code": null, "e": 3087, "s": 3064, "text": "Displays File Contents" }, { "code": null, "e": 3090, "s": 3087, "text": "cd" }, { "code": null, "e": 3119, "s": 3090, "text": "Changes Directory to dirname" }, { "code": null, "e": 3125, "s": 3119, "text": "chgrp" }, { "code": null, "e": 3144, "s": 3125, "text": "Changes file group" }, { "code": null, "e": 3150, "s": 3144, "text": "chmod" }, { "code": null, "e": 3170, "s": 3150, "text": "Changes permissions" }, { "code": null, "e": 3173, "s": 3170, "text": "cp" }, { "code": null, "e": 3209, "s": 3173, "text": "Copies source file into destination" }, { "code": null, "e": 3214, "s": 3209, "text": "file" }, { "code": null, "e": 3235, "s": 3214, "text": "Determines file type" }, { "code": null, "e": 3240, "s": 3235, "text": "find" }, { "code": null, "e": 3252, "s": 3240, "text": "Finds files" }, { "code": null, "e": 3257, "s": 3252, "text": "grep" }, { "code": null, "e": 3296, "s": 3257, "text": "Searches files for regular expressions" }, { "code": null, "e": 3301, "s": 3296, "text": "head" }, { "code": null, "e": 3336, "s": 3301, "text": "Displays first few lines of a file" }, { "code": null, "e": 3339, "s": 3336, "text": "ln" }, { "code": null, "e": 3367, "s": 3339, "text": "Creates softlink on oldname" }, { "code": null, "e": 3370, "s": 3367, "text": "ls" }, { "code": null, "e": 3407, "s": 3370, "text": "Displays information about file type" }, { "code": null, "e": 3413, "s": 3407, "text": "mkdir" }, { "code": null, "e": 3445, "s": 3413, "text": "Creates a new directory dirname" }, { "code": null, "e": 3450, "s": 3445, "text": "more" }, { "code": null, "e": 3482, "s": 3450, "text": "Displays data in paginated form" }, { "code": null, "e": 3485, "s": 3482, "text": "mv" }, { "code": null, "e": 3523, "s": 3485, "text": "Moves (Renames) an oldname to newname" }, { "code": null, "e": 3527, "s": 3523, "text": "pwd" }, { "code": null, "e": 3560, "s": 3527, "text": "Prints current working directory" }, { "code": null, "e": 3563, "s": 3560, "text": "rm" }, { "code": null, "e": 3590, "s": 3563, "text": "Removes (Deletes) filename" }, { "code": null, "e": 3596, "s": 3590, "text": "rmdir" }, { "code": null, "e": 3647, "s": 3596, "text": "Deletes an existing directory provided it is empty" }, { "code": null, "e": 3652, "s": 3647, "text": "tail" }, { "code": null, "e": 3684, "s": 3652, "text": "Prints last few lines in a file" }, { "code": null, "e": 3690, "s": 3684, "text": "touch" }, { "code": null, "e": 3737, "s": 3690, "text": "Updates access and modification time of a file" }, { "code": null, "e": 3816, "s": 3737, "text": "The contents of files can be compared and altered with the following commands." }, { "code": null, "e": 3820, "s": 3816, "text": "awk" }, { "code": null, "e": 3861, "s": 3820, "text": "Pattern scanning and processing language" }, { "code": null, "e": 3865, "s": 3861, "text": "cmp" }, { "code": null, "e": 3900, "s": 3865, "text": "Compares the contents of two files" }, { "code": null, "e": 3905, "s": 3900, "text": "comm" }, { "code": null, "e": 3926, "s": 3905, "text": "Compares sorted data" }, { "code": null, "e": 3930, "s": 3926, "text": "cut" }, { "code": null, "e": 3978, "s": 3930, "text": "Cuts out selected fields of each line of a file" }, { "code": null, "e": 3983, "s": 3978, "text": "diff" }, { "code": null, "e": 4012, "s": 3983, "text": "Differential file comparator" }, { "code": null, "e": 4019, "s": 4012, "text": "expand" }, { "code": null, "e": 4042, "s": 4019, "text": "Expands tabs to spaces" }, { "code": null, "e": 4047, "s": 4042, "text": "join" }, { "code": null, "e": 4080, "s": 4047, "text": "Joins files on some common field" }, { "code": null, "e": 4085, "s": 4080, "text": "perl" }, { "code": null, "e": 4112, "s": 4085, "text": "Data manipulation language" }, { "code": null, "e": 4116, "s": 4112, "text": "sed" }, { "code": null, "e": 4135, "s": 4116, "text": "Stream text editor" }, { "code": null, "e": 4140, "s": 4135, "text": "sort" }, { "code": null, "e": 4156, "s": 4140, "text": "Sorts file data" }, { "code": null, "e": 4162, "s": 4156, "text": "split" }, { "code": null, "e": 4193, "s": 4162, "text": "Splits file into smaller files" }, { "code": null, "e": 4196, "s": 4193, "text": "tr" }, { "code": null, "e": 4218, "s": 4196, "text": "Translates characters" }, { "code": null, "e": 4223, "s": 4218, "text": "uniq" }, { "code": null, "e": 4256, "s": 4223, "text": "Reports repeated lines in a file" }, { "code": null, "e": 4259, "s": 4256, "text": "wc" }, { "code": null, "e": 4295, "s": 4259, "text": "Counts words, lines, and characters" }, { "code": null, "e": 4298, "s": 4295, "text": "vi" }, { "code": null, "e": 4319, "s": 4298, "text": "Opens vi text editor" }, { "code": null, "e": 4323, "s": 4319, "text": "vim" }, { "code": null, "e": 4345, "s": 4323, "text": "Opens vim text editor" }, { "code": null, "e": 4349, "s": 4345, "text": "fmt" }, { "code": null, "e": 4371, "s": 4349, "text": "Simple text formatter" }, { "code": null, "e": 4377, "s": 4371, "text": "spell" }, { "code": null, "e": 4408, "s": 4377, "text": "Checks text for spelling error" }, { "code": null, "e": 4415, "s": 4408, "text": "ispell" }, { "code": null, "e": 4446, "s": 4415, "text": "Checks text for spelling error" }, { "code": null, "e": 4452, "s": 4446, "text": "emacs" }, { "code": null, "e": 4470, "s": 4452, "text": "GNU project Emacs" }, { "code": null, "e": 4479, "s": 4470, "text": "ex, edit" }, { "code": null, "e": 4491, "s": 4479, "text": "Line editor" }, { "code": null, "e": 4497, "s": 4491, "text": "emacs" }, { "code": null, "e": 4515, "s": 4497, "text": "GNU project Emacs" }, { "code": null, "e": 4600, "s": 4515, "text": "Files may be compressed to save space. Compressed files can be created and examined." }, { "code": null, "e": 4609, "s": 4600, "text": "compress" }, { "code": null, "e": 4626, "s": 4609, "text": "Compresses files" }, { "code": null, "e": 4633, "s": 4626, "text": "gunzip" }, { "code": null, "e": 4664, "s": 4633, "text": "Helps uncompress gzipped files" }, { "code": null, "e": 4669, "s": 4664, "text": "gzip" }, { "code": null, "e": 4704, "s": 4669, "text": "GNU alternative compression method" }, { "code": null, "e": 4715, "s": 4704, "text": "uncompress" }, { "code": null, "e": 4738, "s": 4715, "text": "Helps uncompress files" }, { "code": null, "e": 4744, "s": 4738, "text": "unzip" }, { "code": null, "e": 4801, "s": 4744, "text": "List, test and extract compressed files in a ZIP archive" }, { "code": null, "e": 4806, "s": 4801, "text": "zcat" }, { "code": null, "e": 4828, "s": 4806, "text": "Cat a compressed file" }, { "code": null, "e": 4833, "s": 4828, "text": "zcmp" }, { "code": null, "e": 4859, "s": 4833, "text": "Compares compressed files" }, { "code": null, "e": 4865, "s": 4859, "text": "zdiff" }, { "code": null, "e": 4891, "s": 4865, "text": "Compares compressed files" }, { "code": null, "e": 4897, "s": 4891, "text": "zmore" }, { "code": null, "e": 4952, "s": 4897, "text": "File perusal filter for crt viewing of compressed text" }, { "code": null, "e": 5062, "s": 4952, "text": "Various Unix manuals and documentation are available on-line. The following Shell commands give information −" }, { "code": null, "e": 5070, "s": 5062, "text": "apropos" }, { "code": null, "e": 5105, "s": 5070, "text": "Locates commands by keyword lookup" }, { "code": null, "e": 5110, "s": 5105, "text": "info" }, { "code": null, "e": 5152, "s": 5110, "text": "Displays command information pages online" }, { "code": null, "e": 5156, "s": 5152, "text": "man" }, { "code": null, "e": 5185, "s": 5156, "text": "Displays manual pages online" }, { "code": null, "e": 5192, "s": 5185, "text": "whatis" }, { "code": null, "e": 5240, "s": 5192, "text": "Searches the whatis database for complete words" }, { "code": null, "e": 5245, "s": 5240, "text": "yelp" }, { "code": null, "e": 5263, "s": 5245, "text": "GNOME help viewer" }, { "code": null, "e": 5384, "s": 5263, "text": "These following commands are used to send and receive files from a local Unix hosts to the remote host around the world." }, { "code": null, "e": 5388, "s": 5384, "text": "ftp" }, { "code": null, "e": 5410, "s": 5388, "text": "File transfer program" }, { "code": null, "e": 5414, "s": 5410, "text": "rcp" }, { "code": null, "e": 5431, "s": 5414, "text": "Remote file copy" }, { "code": null, "e": 5438, "s": 5431, "text": "rlogin" }, { "code": null, "e": 5466, "s": 5438, "text": "Remote login to a Unix host" }, { "code": null, "e": 5470, "s": 5466, "text": "rsh" }, { "code": null, "e": 5483, "s": 5470, "text": "Remote shell" }, { "code": null, "e": 5488, "s": 5483, "text": "tftp" }, { "code": null, "e": 5518, "s": 5488, "text": "Trivial file transfer program" }, { "code": null, "e": 5525, "s": 5518, "text": "telnet" }, { "code": null, "e": 5567, "s": 5525, "text": "Makes terminal connection to another host" }, { "code": null, "e": 5571, "s": 5567, "text": "ssh" }, { "code": null, "e": 5616, "s": 5571, "text": "Secures shell terminal or command connection" }, { "code": null, "e": 5620, "s": 5616, "text": "scp" }, { "code": null, "e": 5651, "s": 5620, "text": "Secures shell remote file copy" }, { "code": null, "e": 5656, "s": 5651, "text": "sftp" }, { "code": null, "e": 5692, "s": 5656, "text": "Secures shell file transfer program" }, { "code": null, "e": 5772, "s": 5692, "text": "Some of these commands may be restricted at your computer for security reasons." }, { "code": null, "e": 5864, "s": 5772, "text": "The Unix systems support on-screen messages to other users and world-wide electronic mail −" }, { "code": null, "e": 5874, "s": 5864, "text": "evolution" }, { "code": null, "e": 5906, "s": 5874, "text": "GUI mail handling tool on Linux" }, { "code": null, "e": 5911, "s": 5906, "text": "mail" }, { "code": null, "e": 5944, "s": 5911, "text": "Simple send or read mail program" }, { "code": null, "e": 5949, "s": 5944, "text": "mesg" }, { "code": null, "e": 5976, "s": 5949, "text": "Permits or denies messages" }, { "code": null, "e": 5983, "s": 5976, "text": "parcel" }, { "code": null, "e": 6011, "s": 5983, "text": "Sends files to another user" }, { "code": null, "e": 6016, "s": 6011, "text": "pine" }, { "code": null, "e": 6039, "s": 6016, "text": "Vdu-based mail utility" }, { "code": null, "e": 6044, "s": 6039, "text": "talk" }, { "code": null, "e": 6066, "s": 6044, "text": "Talks to another user" }, { "code": null, "e": 6072, "s": 6066, "text": "write" }, { "code": null, "e": 6103, "s": 6072, "text": "Writes message to another user" }, { "code": null, "e": 6210, "s": 6103, "text": "The following programming tools and languages are available based on what you have installed on your Unix." }, { "code": null, "e": 6214, "s": 6210, "text": "dbx" }, { "code": null, "e": 6227, "s": 6214, "text": "Sun debugger" }, { "code": null, "e": 6231, "s": 6227, "text": "gdb" }, { "code": null, "e": 6244, "s": 6231, "text": "GNU debugger" }, { "code": null, "e": 6249, "s": 6244, "text": "make" }, { "code": null, "e": 6295, "s": 6249, "text": "Maintains program groups and compile programs" }, { "code": null, "e": 6298, "s": 6295, "text": "nm" }, { "code": null, "e": 6325, "s": 6298, "text": "Prints program's name list" }, { "code": null, "e": 6330, "s": 6325, "text": "size" }, { "code": null, "e": 6353, "s": 6330, "text": "Prints program's sizes" }, { "code": null, "e": 6359, "s": 6353, "text": "strip" }, { "code": null, "e": 6400, "s": 6359, "text": "Removes symbol table and relocation bits" }, { "code": null, "e": 6403, "s": 6400, "text": "cb" }, { "code": null, "e": 6424, "s": 6403, "text": "C program beautifier" }, { "code": null, "e": 6427, "s": 6424, "text": "cc" }, { "code": null, "e": 6466, "s": 6427, "text": "ANSI C compiler for Suns SPARC systems" }, { "code": null, "e": 6473, "s": 6466, "text": "ctrace" }, { "code": null, "e": 6492, "s": 6473, "text": "C program debugger" }, { "code": null, "e": 6496, "s": 6492, "text": "gcc" }, { "code": null, "e": 6516, "s": 6496, "text": "GNU ANSI C Compiler" }, { "code": null, "e": 6523, "s": 6516, "text": "indent" }, { "code": null, "e": 6558, "s": 6523, "text": "Indent and format C program source" }, { "code": null, "e": 6561, "s": 6558, "text": "bc" }, { "code": null, "e": 6603, "s": 6561, "text": "Interactive arithmetic language processor" }, { "code": null, "e": 6607, "s": 6603, "text": "gcl" }, { "code": null, "e": 6623, "s": 6607, "text": "GNU Common Lisp" }, { "code": null, "e": 6628, "s": 6623, "text": "perl" }, { "code": null, "e": 6653, "s": 6628, "text": "General purpose language" }, { "code": null, "e": 6657, "s": 6653, "text": "php" }, { "code": null, "e": 6684, "s": 6657, "text": "Web page embedded language" }, { "code": null, "e": 6687, "s": 6684, "text": "py" }, { "code": null, "e": 6715, "s": 6687, "text": "Python language interpreter" }, { "code": null, "e": 6719, "s": 6715, "text": "asp" }, { "code": null, "e": 6746, "s": 6719, "text": "Web page embedded language" }, { "code": null, "e": 6749, "s": 6746, "text": "CC" }, { "code": null, "e": 6785, "s": 6749, "text": "C++ compiler for Suns SPARC systems" }, { "code": null, "e": 6789, "s": 6785, "text": "g++" }, { "code": null, "e": 6806, "s": 6789, "text": "GNU C++ Compiler" }, { "code": null, "e": 6812, "s": 6806, "text": "javac" }, { "code": null, "e": 6826, "s": 6812, "text": "JAVA compiler" }, { "code": null, "e": 6840, "s": 6826, "text": "appletvieweir" }, { "code": null, "e": 6859, "s": 6840, "text": "JAVA applet viewer" }, { "code": null, "e": 6868, "s": 6859, "text": "netbeans" }, { "code": null, "e": 6917, "s": 6868, "text": "Java integrated development environment on Linux" }, { "code": null, "e": 6925, "s": 6917, "text": "sqlplus" }, { "code": null, "e": 6957, "s": 6925, "text": "Runs the Oracle SQL interpreter" }, { "code": null, "e": 6964, "s": 6957, "text": "sqlldr" }, { "code": null, "e": 6996, "s": 6964, "text": "Runs the Oracle SQL data loader" }, { "code": null, "e": 7002, "s": 6996, "text": "mysql" }, { "code": null, "e": 7033, "s": 7002, "text": "Runs the mysql SQL interpreter" }, { "code": null, "e": 7093, "s": 7033, "text": "These commands list or alter information about the system −" }, { "code": null, "e": 7098, "s": 7093, "text": "chfn" }, { "code": null, "e": 7130, "s": 7098, "text": "Changes your finger information" }, { "code": null, "e": 7136, "s": 7130, "text": "chgrp" }, { "code": null, "e": 7174, "s": 7136, "text": "Changes the group ownership of a file" }, { "code": null, "e": 7180, "s": 7174, "text": "chown" }, { "code": null, "e": 7194, "s": 7180, "text": "Changes owner" }, { "code": null, "e": 7199, "s": 7194, "text": "date" }, { "code": null, "e": 7215, "s": 7199, "text": "Prints the date" }, { "code": null, "e": 7224, "s": 7215, "text": "determin" }, { "code": null, "e": 7258, "s": 7224, "text": "Automatically finds terminal type" }, { "code": null, "e": 7261, "s": 7258, "text": "du" }, { "code": null, "e": 7289, "s": 7261, "text": "Prints amount of disk usage" }, { "code": null, "e": 7294, "s": 7289, "text": "echo" }, { "code": null, "e": 7333, "s": 7294, "text": "Echo arguments to the standard options" }, { "code": null, "e": 7338, "s": 7333, "text": "exit" }, { "code": null, "e": 7355, "s": 7338, "text": "Quits the system" }, { "code": null, "e": 7362, "s": 7355, "text": "finger" }, { "code": null, "e": 7403, "s": 7362, "text": "Prints information about logged-in users" }, { "code": null, "e": 7412, "s": 7403, "text": "groupadd" }, { "code": null, "e": 7433, "s": 7412, "text": "Creates a user group" }, { "code": null, "e": 7440, "s": 7433, "text": "groups" }, { "code": null, "e": 7463, "s": 7440, "text": "Show group memberships" }, { "code": null, "e": 7473, "s": 7463, "text": "homequota" }, { "code": null, "e": 7500, "s": 7473, "text": "Shows quota and file usage" }, { "code": null, "e": 7507, "s": 7500, "text": "iostat" }, { "code": null, "e": 7530, "s": 7507, "text": "Reports I/O statistics" }, { "code": null, "e": 7535, "s": 7530, "text": "kill" }, { "code": null, "e": 7563, "s": 7535, "text": "Sends a signal to a process" }, { "code": null, "e": 7568, "s": 7563, "text": "last" }, { "code": null, "e": 7595, "s": 7568, "text": "Shows last logins of users" }, { "code": null, "e": 7602, "s": 7595, "text": "logout" }, { "code": null, "e": 7616, "s": 7602, "text": "Logs off Unix" }, { "code": null, "e": 7620, "s": 7616, "text": "lun" }, { "code": null, "e": 7649, "s": 7620, "text": "Lists user names or login ID" }, { "code": null, "e": 7657, "s": 7649, "text": "netstat" }, { "code": null, "e": 7678, "s": 7657, "text": "Shows network status" }, { "code": null, "e": 7685, "s": 7678, "text": "passwd" }, { "code": null, "e": 7707, "s": 7685, "text": "Changes user password" }, { "code": null, "e": 7714, "s": 7707, "text": "passwd" }, { "code": null, "e": 7742, "s": 7714, "text": "Changes your login password" }, { "code": null, "e": 7751, "s": 7742, "text": "printenv" }, { "code": null, "e": 7786, "s": 7751, "text": "Displays value of a shell variable" }, { "code": null, "e": 7789, "s": 7786, "text": "ps" }, { "code": null, "e": 7830, "s": 7789, "text": "Displays the status of current processes" }, { "code": null, "e": 7833, "s": 7830, "text": "ps" }, { "code": null, "e": 7866, "s": 7833, "text": "Prints process status statistics" }, { "code": null, "e": 7875, "s": 7866, "text": "quota -v" }, { "code": null, "e": 7906, "s": 7875, "text": "Displays disk usage and limits" }, { "code": null, "e": 7912, "s": 7906, "text": "reset" }, { "code": null, "e": 7933, "s": 7912, "text": "Resets terminal mode" }, { "code": null, "e": 7940, "s": 7933, "text": "script" }, { "code": null, "e": 7973, "s": 7940, "text": "Keeps script of terminal session" }, { "code": null, "e": 7980, "s": 7973, "text": "script" }, { "code": null, "e": 8021, "s": 7980, "text": "Saves the output of a command or process" }, { "code": null, "e": 8028, "s": 8021, "text": "setenv" }, { "code": null, "e": 8055, "s": 8028, "text": "Sets environment variables" }, { "code": null, "e": 8060, "s": 8055, "text": "stty" }, { "code": null, "e": 8082, "s": 8060, "text": "Sets terminal options" }, { "code": null, "e": 8087, "s": 8082, "text": "time" }, { "code": null, "e": 8108, "s": 8087, "text": "Helps time a command" }, { "code": null, "e": 8112, "s": 8108, "text": "top" }, { "code": null, "e": 8142, "s": 8112, "text": "Displays all system processes" }, { "code": null, "e": 8147, "s": 8142, "text": "tset" }, { "code": null, "e": 8166, "s": 8147, "text": "Sets terminal mode" }, { "code": null, "e": 8170, "s": 8166, "text": "tty" }, { "code": null, "e": 8199, "s": 8170, "text": "Prints current terminal name" }, { "code": null, "e": 8205, "s": 8199, "text": "umask" }, { "code": null, "e": 8266, "s": 8205, "text": "Show the permissions that are given to view files by default" }, { "code": null, "e": 8272, "s": 8266, "text": "uname" }, { "code": null, "e": 8308, "s": 8272, "text": "Displays name of the current system" }, { "code": null, "e": 8315, "s": 8308, "text": "uptime" }, { "code": null, "e": 8339, "s": 8315, "text": "Gets the system up time" }, { "code": null, "e": 8347, "s": 8339, "text": "useradd" }, { "code": null, "e": 8370, "s": 8347, "text": "Creates a user account" }, { "code": null, "e": 8376, "s": 8370, "text": "users" }, { "code": null, "e": 8408, "s": 8376, "text": "Prints names of logged in users" }, { "code": null, "e": 8415, "s": 8408, "text": "vmstat" }, { "code": null, "e": 8449, "s": 8415, "text": "Reports virtual memory statistics" }, { "code": null, "e": 8451, "s": 8449, "text": "w" }, { "code": null, "e": 8488, "s": 8451, "text": "Shows what logged in users are doing" }, { "code": null, "e": 8492, "s": 8488, "text": "who" } ]
Remove a cookie using PHP
31 Jul, 2021 Cookie: A Cookie is a small file sent by the server to preserve stateful information for a user. It is stored on the client’s computer and sent to the server every time the user makes a request for the same page. To create cookies you can set the cookie by using the setcookie() function of the PHP. Syntax: setcookie(name, value, expire, path, domain, secure, httponly) Parameters: This function accepts seven parameters as mentioned above and described below: name: The name of the cookie. value: The value you want to store in the cookie. expire-time: It is the number of seconds until the cookie will be kept on the user’s machine by the browser. After that, it will automatically be deleted. If not set then the cookie will be preserved by browser until it is open. path: It determines for which directories cookie will valid. If you want to access it in all directories then put it on “/”, i.e. the cookie is accessible in the entire domain. Otherwise, the cookie will be limited to the subdirectory. domain: It is used to define the access hierarchy for the cookie. For example, if you set this to “yourdomain.com”, it will be accessible via all the subdomains also. but if it set to “sub.yourdomain.com”, it will be accessible by “sub.yourdomain.com” and its subdomains. secure: It determines how the cookie will be sent, via HTTP or HTTPS. If set to true then the cookie will be sent via HTTPS only, otherwise, it will be sent via HTTP. Its default value is false. httponly: If it set to true, the cookie is accessible only either via HTTP or HTTPS. That means the client code (like Javascript) can not access the cookie. Out of the above parameters, only the first two parameters are mandatory. Others are optional parameters. If you want to preserve the cookie, then provide the expire-time parameter. Note: It is stored in the global array named $_COOKIE. Creating a Cookie: As mentioned earlier, we can set cookies by using the function setcookie(). Example: PHP <!DOCTYPE html> <?php$cookie_name = "gfg";$cookie_value = "GeeksforGeeks"; // 86400 = 1 daysetcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/"); ?> <html><body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> </body> </html> Output: Cookie 'gfg' is set! Value is: GeeksforGeeks Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time. Syntax: setcookie(name, time() - 3600); Example: PHP <!DOCTYPE html><?php // Set the expiration date to one hour agosetcookie("gfg", "", time() - 3600);?> <html> <body> <?php echo "Cookie 'gfg' is deleted."; ?> </body> </html> Output: Cookie 'gfg' is deleted. Note: The setcookie() function must appear before the <html> tag. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. simmytarika5 Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 241, "s": 28, "text": "Cookie: A Cookie is a small file sent by the server to preserve stateful information for a user. It is stored on the client’s computer and sent to the server every time the user makes a request for the same page." }, { "code": null, "e": 328, "s": 241, "text": "To create cookies you can set the cookie by using the setcookie() function of the PHP." }, { "code": null, "e": 337, "s": 328, "text": "Syntax: " }, { "code": null, "e": 400, "s": 337, "text": "setcookie(name, value, expire, path, domain, secure, httponly)" }, { "code": null, "e": 493, "s": 400, "text": "Parameters: This function accepts seven parameters as mentioned above and described below: " }, { "code": null, "e": 523, "s": 493, "text": "name: The name of the cookie." }, { "code": null, "e": 573, "s": 523, "text": "value: The value you want to store in the cookie." }, { "code": null, "e": 802, "s": 573, "text": "expire-time: It is the number of seconds until the cookie will be kept on the user’s machine by the browser. After that, it will automatically be deleted. If not set then the cookie will be preserved by browser until it is open." }, { "code": null, "e": 1038, "s": 802, "text": "path: It determines for which directories cookie will valid. If you want to access it in all directories then put it on “/”, i.e. the cookie is accessible in the entire domain. Otherwise, the cookie will be limited to the subdirectory." }, { "code": null, "e": 1310, "s": 1038, "text": "domain: It is used to define the access hierarchy for the cookie. For example, if you set this to “yourdomain.com”, it will be accessible via all the subdomains also. but if it set to “sub.yourdomain.com”, it will be accessible by “sub.yourdomain.com” and its subdomains." }, { "code": null, "e": 1505, "s": 1310, "text": "secure: It determines how the cookie will be sent, via HTTP or HTTPS. If set to true then the cookie will be sent via HTTPS only, otherwise, it will be sent via HTTP. Its default value is false." }, { "code": null, "e": 1662, "s": 1505, "text": "httponly: If it set to true, the cookie is accessible only either via HTTP or HTTPS. That means the client code (like Javascript) can not access the cookie." }, { "code": null, "e": 1844, "s": 1662, "text": "Out of the above parameters, only the first two parameters are mandatory. Others are optional parameters. If you want to preserve the cookie, then provide the expire-time parameter." }, { "code": null, "e": 1899, "s": 1844, "text": "Note: It is stored in the global array named $_COOKIE." }, { "code": null, "e": 1996, "s": 1899, "text": "Creating a Cookie: As mentioned earlier, we can set cookies by using the function setcookie(). " }, { "code": null, "e": 2006, "s": 1996, "text": "Example: " }, { "code": null, "e": 2010, "s": 2006, "text": "PHP" }, { "code": "<!DOCTYPE html> <?php$cookie_name = \"gfg\";$cookie_value = \"GeeksforGeeks\"; // 86400 = 1 daysetcookie($cookie_name, $cookie_value, time() + (86400 * 15), \"/\"); ?> <html><body> <?php if(!isset($_COOKIE[$cookie_name])) { echo \"Cookie named '\" . $cookie_name . \"' is not set!\"; } else { echo \"Cookie '\" . $cookie_name . \"' is set!<br>\"; echo \"Value is: \" . $_COOKIE[$cookie_name]; } ?> </body> </html>", "e": 2459, "s": 2010, "text": null }, { "code": null, "e": 2468, "s": 2459, "text": "Output: " }, { "code": null, "e": 2513, "s": 2468, "text": "Cookie 'gfg' is set!\nValue is: GeeksforGeeks" }, { "code": null, "e": 2816, "s": 2513, "text": "Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time. " }, { "code": null, "e": 2825, "s": 2816, "text": "Syntax: " }, { "code": null, "e": 2857, "s": 2825, "text": "setcookie(name, time() - 3600);" }, { "code": null, "e": 2867, "s": 2857, "text": "Example: " }, { "code": null, "e": 2871, "s": 2867, "text": "PHP" }, { "code": "<!DOCTYPE html><?php // Set the expiration date to one hour agosetcookie(\"gfg\", \"\", time() - 3600);?> <html> <body> <?php echo \"Cookie 'gfg' is deleted.\"; ?> </body> </html>", "e": 3061, "s": 2871, "text": null }, { "code": null, "e": 3070, "s": 3061, "text": "Output: " }, { "code": null, "e": 3095, "s": 3070, "text": "Cookie 'gfg' is deleted." }, { "code": null, "e": 3162, "s": 3095, "text": "Note: The setcookie() function must appear before the <html> tag. " }, { "code": null, "e": 3331, "s": 3162, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 3344, "s": 3331, "text": "simmytarika5" }, { "code": null, "e": 3351, "s": 3344, "text": "Picked" }, { "code": null, "e": 3355, "s": 3351, "text": "PHP" }, { "code": null, "e": 3368, "s": 3355, "text": "PHP Programs" }, { "code": null, "e": 3385, "s": 3368, "text": "Web Technologies" }, { "code": null, "e": 3412, "s": 3385, "text": "Web technologies Questions" }, { "code": null, "e": 3416, "s": 3412, "text": "PHP" }, { "code": null, "e": 3514, "s": 3416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3564, "s": 3514, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3604, "s": 3564, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3665, "s": 3604, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3715, "s": 3665, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 3760, "s": 3715, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3810, "s": 3760, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3850, "s": 3810, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3911, "s": 3850, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3963, "s": 3911, "text": "How to call PHP function on the click of a Button ?" } ]
Running Docker Containers as Non-Root User
05 Nov, 2020 By default, Docker Containers run as Root Users. Now, if you are running applications inside Docker Containers, you have access to all the root privileges. This poses a great security threat when you deploy applications on large scale inside Docker Containers. Because if somehow your application gets hacked by external users, other applications running inside the Containers would also be a huge risk. Moreover, if your Docker Container is part of a network, then the whole network has the risk of getting hacked. To avoid this, you need to make sure that you run the Docker Containers as non-root users. In this article, we will discuss two different ways using which you can create and add non-root users inside Docker Containers. You can add users using the -u option along with useradd. You can then use the USER instruction to switch the user. Consider the Dockerfile below. FROM ubuntu RUN useradd -u 1234 my-user USER my-user The above Dockerfile pulls the Ubuntu base image and creates a user with ID 1234 and name my-user. It then switches to the new user using the USER instruction. Now, to build the Image, use the Docker Build command. sudo docker build -t nonroot-demo . Use the Docker Run command to run the container. sudo docker run -it nonroot-demo bash You can see that the user has been changed to the non-root user that we created in the Dockerfile. To create a Docker group, you can use the following command. sudo groupadd docker If there is already a docker group, you will get the following output – Now, to create a non-root user and add it to the docker group, you can use the following command. sudo useradd -G docker <user-name> After that, you can assign a password to the user using the following command. sudo passwd user To change a user’s primary group, use this command. sudo usermod -aG docker <non-root user> Restart the Docker service. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Fuzzy Logic | Introduction Game Playing in Artificial Intelligence Artificial Intelligence - Temporal Logic Difference between Backward and Forward Chaining. Markov Decision Process Getting Started with System Design Basics of API Testing Using Postman Web Mining Python | Implementation of Polynomial Regression ML | What is Machine Learning ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2020" }, { "code": null, "e": 635, "s": 28, "text": "By default, Docker Containers run as Root Users. Now, if you are running applications inside Docker Containers, you have access to all the root privileges. This poses a great security threat when you deploy applications on large scale inside Docker Containers. Because if somehow your application gets hacked by external users, other applications running inside the Containers would also be a huge risk. Moreover, if your Docker Container is part of a network, then the whole network has the risk of getting hacked. To avoid this, you need to make sure that you run the Docker Containers as non-root users." }, { "code": null, "e": 763, "s": 635, "text": "In this article, we will discuss two different ways using which you can create and add non-root users inside Docker Containers." }, { "code": null, "e": 910, "s": 763, "text": "You can add users using the -u option along with useradd. You can then use the USER instruction to switch the user. Consider the Dockerfile below." }, { "code": null, "e": 964, "s": 910, "text": "FROM ubuntu\nRUN useradd -u 1234 my-user\nUSER my-user\n" }, { "code": null, "e": 1124, "s": 964, "text": "The above Dockerfile pulls the Ubuntu base image and creates a user with ID 1234 and name my-user. It then switches to the new user using the USER instruction." }, { "code": null, "e": 1179, "s": 1124, "text": "Now, to build the Image, use the Docker Build command." }, { "code": null, "e": 1216, "s": 1179, "text": "sudo docker build -t nonroot-demo .\n" }, { "code": null, "e": 1265, "s": 1216, "text": "Use the Docker Run command to run the container." }, { "code": null, "e": 1304, "s": 1265, "text": "sudo docker run -it nonroot-demo bash\n" }, { "code": null, "e": 1403, "s": 1304, "text": "You can see that the user has been changed to the non-root user that we created in the Dockerfile." }, { "code": null, "e": 1464, "s": 1403, "text": "To create a Docker group, you can use the following command." }, { "code": null, "e": 1486, "s": 1464, "text": "sudo groupadd docker\n" }, { "code": null, "e": 1559, "s": 1486, "text": "If there is already a docker group, you will get the following output – " }, { "code": null, "e": 1657, "s": 1559, "text": "Now, to create a non-root user and add it to the docker group, you can use the following command." }, { "code": null, "e": 1693, "s": 1657, "text": "sudo useradd -G docker <user-name>\n" }, { "code": null, "e": 1772, "s": 1693, "text": "After that, you can assign a password to the user using the following command." }, { "code": null, "e": 1790, "s": 1772, "text": "sudo passwd user\n" }, { "code": null, "e": 1842, "s": 1790, "text": "To change a user’s primary group, use this command." }, { "code": null, "e": 1883, "s": 1842, "text": "sudo usermod -aG docker <non-root user>\n" }, { "code": null, "e": 1911, "s": 1883, "text": "Restart the Docker service." }, { "code": null, "e": 1928, "s": 1911, "text": "Docker Container" }, { "code": null, "e": 1934, "s": 1928, "text": "linux" }, { "code": null, "e": 1960, "s": 1934, "text": "Advanced Computer Subject" }, { "code": null, "e": 2058, "s": 1960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2085, "s": 2058, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 2125, "s": 2085, "text": "Game Playing in Artificial Intelligence" }, { "code": null, "e": 2166, "s": 2125, "text": "Artificial Intelligence - Temporal Logic" }, { "code": null, "e": 2216, "s": 2166, "text": "Difference between Backward and Forward Chaining." }, { "code": null, "e": 2240, "s": 2216, "text": "Markov Decision Process" }, { "code": null, "e": 2275, "s": 2240, "text": "Getting Started with System Design" }, { "code": null, "e": 2311, "s": 2275, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 2322, "s": 2311, "text": "Web Mining" }, { "code": null, "e": 2371, "s": 2322, "text": "Python | Implementation of Polynomial Regression" } ]
How to place background image using ::before pseudo selectors in CSS ?
14 Dec, 2020 Given a web page and the task is to place the background image on web page using ::before pseudo selector. The ::before pseudo selector is used to place something before the content of the selected items. Syntax: .container::before{ content: ''; background: url(image file); position:absolute; top:0px; left:0px; } Approach: The ::before pseudo selector places the background image before the selected element and if the selected element has a background color associated with it, we can use the z-index property to make the background image visible. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to place the background image using ::before pseudo selectors ? </title> <style> * { margin: 0px; padding: 0px; } body { text-align: center; } h1 { color: green; } .container { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; color: black; font-weight: bold; font-size: 2rem; } .container::before { content: ''; background: url('bg.png') no-repeat center center/cover; position: absolute; opacity: 0.3; top: 0px; left: 0px; width: 100vw; height: 100vh; z-index: -1; } span { font-size: 2em; } </style></head> <body> <div class="container"> GeeksforGeeks<br><br> How to place background image using ::before pseudo selectors ? </div></body> </html> Output: Image Reference: https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200212230557/How-To-Become-A-Web-Developer-in-2020-A-Complete-Guide.png CSS-Misc HTML-Misc Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Dec, 2020" }, { "code": null, "e": 161, "s": 54, "text": "Given a web page and the task is to place the background image on web page using ::before pseudo selector." }, { "code": null, "e": 260, "s": 161, "text": "The ::before pseudo selector is used to place something before the content of the selected items. " }, { "code": null, "e": 268, "s": 260, "text": "Syntax:" }, { "code": null, "e": 390, "s": 268, "text": ".container::before{\n content: '';\n background: url(image file);\n position:absolute;\n top:0px;\n left:0px;\n}" }, { "code": null, "e": 628, "s": 390, "text": "Approach: The ::before pseudo selector places the background image before the selected element and if the selected element has a background color associated with it, we can use the z-index property to make the background image visible. " }, { "code": null, "e": 637, "s": 628, "text": "Example:" }, { "code": null, "e": 642, "s": 637, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to place the background image using ::before pseudo selectors ? </title> <style> * { margin: 0px; padding: 0px; } body { text-align: center; } h1 { color: green; } .container { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; color: black; font-weight: bold; font-size: 2rem; } .container::before { content: ''; background: url('bg.png') no-repeat center center/cover; position: absolute; opacity: 0.3; top: 0px; left: 0px; width: 100vw; height: 100vh; z-index: -1; } span { font-size: 2em; } </style></head> <body> <div class=\"container\"> GeeksforGeeks<br><br> How to place background image using ::before pseudo selectors ? </div></body> </html>", "e": 1912, "s": 642, "text": null }, { "code": null, "e": 1920, "s": 1912, "text": "Output:" }, { "code": null, "e": 2066, "s": 1920, "text": "Image Reference: https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200212230557/How-To-Become-A-Web-Developer-in-2020-A-Complete-Guide.png" }, { "code": null, "e": 2075, "s": 2066, "text": "CSS-Misc" }, { "code": null, "e": 2085, "s": 2075, "text": "HTML-Misc" }, { "code": null, "e": 2109, "s": 2085, "text": "Technical Scripter 2020" }, { "code": null, "e": 2113, "s": 2109, "text": "CSS" }, { "code": null, "e": 2118, "s": 2113, "text": "HTML" }, { "code": null, "e": 2137, "s": 2118, "text": "Technical Scripter" }, { "code": null, "e": 2154, "s": 2137, "text": "Web Technologies" }, { "code": null, "e": 2181, "s": 2154, "text": "Web technologies Questions" }, { "code": null, "e": 2186, "s": 2181, "text": "HTML" }, { "code": null, "e": 2284, "s": 2186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2323, "s": 2284, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2362, "s": 2323, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2401, "s": 2362, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2438, "s": 2401, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2467, "s": 2438, "text": "Form validation using jQuery" }, { "code": null, "e": 2491, "s": 2467, "text": "REST API (Introduction)" }, { "code": null, "e": 2544, "s": 2491, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2604, "s": 2544, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2665, "s": 2604, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Tensorflow.js tf.data.Dataset class .prefetch() Method
22 Apr, 2022 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.data.Dataset class .prefetch() function is used to produce a dataset that prefetches the specified elements from this given dataset. Syntax: prefetch (bufferSize) Parameters: This function accepts a parameter which is illustrated below: bufferSize: It is an integer value that specifies the number of elements to be prefetched. Return Value: It returns a dataset of elements. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Calling the .prefetch() function over// the specified dataset of some elementsconst a = tf.data.array([5, 10, 15, 20]).prefetch(4); // Getting the dataset of prefetched elementsawait a.forEachAsync(a => console.log(a)); Output: 5 10 15 20 Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Specifying a dataset of some elementsconst a = tf.data.array(["a", "b", "c", "d", "e"]); // Calling the .prefetch() function over// the above dataset along with the // batch of size 2const b = a.batch(2)const c = b.prefetch(2) // Getting the dataset of prefetched elementsawait c.forEachAsync(c => console.log(c)); Output: Tensor ['a', 'b'] Tensor ['c', 'd'] Tensor ['e'] Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.prefetch arorakashish0911 Picked Tensorflow.js TensorFlow.js-Classes TensorFlow.js-Data JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2022" }, { "code": null, "e": 194, "s": 28, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 334, "s": 194, "text": "The tf.data.Dataset class .prefetch() function is used to produce a dataset that prefetches the specified elements from this given dataset." }, { "code": null, "e": 342, "s": 334, "text": "Syntax:" }, { "code": null, "e": 364, "s": 342, "text": "prefetch (bufferSize)" }, { "code": null, "e": 438, "s": 364, "text": "Parameters: This function accepts a parameter which is illustrated below:" }, { "code": null, "e": 529, "s": 438, "text": "bufferSize: It is an integer value that specifies the number of elements to be prefetched." }, { "code": null, "e": 577, "s": 529, "text": "Return Value: It returns a dataset of elements." }, { "code": null, "e": 588, "s": 577, "text": "Example 1:" }, { "code": null, "e": 599, "s": 588, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Calling the .prefetch() function over// the specified dataset of some elementsconst a = tf.data.array([5, 10, 15, 20]).prefetch(4); // Getting the dataset of prefetched elementsawait a.forEachAsync(a => console.log(a));", "e": 901, "s": 599, "text": null }, { "code": null, "e": 909, "s": 901, "text": "Output:" }, { "code": null, "e": 920, "s": 909, "text": "5\n10\n15\n20" }, { "code": null, "e": 931, "s": 920, "text": "Example 2:" }, { "code": null, "e": 942, "s": 931, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Specifying a dataset of some elementsconst a = tf.data.array([\"a\", \"b\", \"c\", \"d\", \"e\"]); // Calling the .prefetch() function over// the above dataset along with the // batch of size 2const b = a.batch(2)const c = b.prefetch(2) // Getting the dataset of prefetched elementsawait c.forEachAsync(c => console.log(c));", "e": 1340, "s": 942, "text": null }, { "code": null, "e": 1348, "s": 1340, "text": "Output:" }, { "code": null, "e": 1409, "s": 1348, "text": "Tensor\n ['a', 'b']\nTensor\n ['c', 'd']\nTensor\n ['e']" }, { "code": null, "e": 1483, "s": 1409, "text": "Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.prefetch" }, { "code": null, "e": 1500, "s": 1483, "text": "arorakashish0911" }, { "code": null, "e": 1507, "s": 1500, "text": "Picked" }, { "code": null, "e": 1521, "s": 1507, "text": "Tensorflow.js" }, { "code": null, "e": 1543, "s": 1521, "text": "TensorFlow.js-Classes" }, { "code": null, "e": 1562, "s": 1543, "text": "TensorFlow.js-Data" }, { "code": null, "e": 1573, "s": 1562, "text": "JavaScript" }, { "code": null, "e": 1590, "s": 1573, "text": "Web Technologies" }, { "code": null, "e": 1688, "s": 1590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1749, "s": 1688, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1789, "s": 1749, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1831, "s": 1789, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1872, "s": 1831, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1894, "s": 1872, "text": "JavaScript | Promises" }, { "code": null, "e": 1927, "s": 1894, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1989, "s": 1927, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2050, "s": 1989, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2100, "s": 2050, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Prime Implicant chart for minimizing Cyclic Boolean functions
10 Jun, 2021 Prerequisite – K-Map (Karnaugh Map), Implicants in K-Map A functions is said to be a Cyclic Boolean Function if there is no Essential prime Implicant in its respective K-Map. Properties of Cyclic functions: Every prime Implicant is of same size. Every minterm is covered by at least two prime Implicants (which means no essential prime Implicants). Having no essential prime Implicants means that there exist more than one minimized Solution / Expression for such functions, which will further be realized using digital circuits. For a cyclic function we can have two minimal forms with no overlapping of prime Implicants. Example: Find the minimal expression for the following function. f(w, x, y, z) = (0, 2, 4, 5, 10, 11, 13, 15) As we can see in the above K-Map that there exist no essential prime Implicants. Here we can use prime Implicant chart to solve it easily. Steps to solve above function using prime Implicant chart: Step-1: Draw prime Implicant chart as below.The horizontal entries denote the given minterms which are mapped against all prime Implicants (vertically).The square boxes are crossed (‘x’) whenever a prime Implicant covers a particular minterm in K-Map. For example ‘WXZ’ prime Implicant is covering 13 and 15 therefore the corresponding squares are crossed(denoted by ‘x’). Note that, A, B, C, D .., are variables used to denote all the prime Implicants. For example ‘WXZ’ prime Implicant is covering 13 and 15 therefore the corresponding squares are crossed(denoted by ‘x’). Note that, A, B, C, D .., are variables used to denote all the prime Implicants. Step-2: Arbitrarily choose any prime Implicant; check () the prime Implicant and the corresponding covered minterms as well. Now delete the row of the prime Implicant and corresponding columns of its minterms. In our example prime Implicant A is chosen which is covering minterms 2 and 10. Therefore. delete the row of A and the columns of 2 and 10. The arbitrarily chosen Prime Implicant (in our example A) must be present in the final minimal expression. In our example prime Implicant A is chosen which is covering minterms 2 and 10. Therefore. delete the row of A and the columns of 2 and 10. The arbitrarily chosen Prime Implicant (in our example A) must be present in the final minimal expression. Step-3: Find all such prime Implicant which are being covered by other prime Implicant completely and remove their corresponding rows (since these are non essential prime Implicants.). In our example H is covering {0, 4} and B is covering {0} it means H is covering all the minterms that are covered by B, so delete B. Similarly D is covering C completely, so delete C. In our example H is covering {0, 4} and B is covering {0} it means H is covering all the minterms that are covered by B, so delete B. Similarly D is covering C completely, so delete C. Step-4: Now follow the standard procedure of prime Implicant chart mentioned in the sub steps given below: Find the minterm which is covered by only one prime Implicant. Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. Find the minterm which is covered by only one prime Implicant. Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. Find the minterm which is covered by only one prime Implicant. Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. Example-2: find the minimal expression for the following cyclic function. f(x, y, z) = (0, 1, 2, 5, 6, 7) Step-1: Draw prime Implicant chart. Step-2: A is chosen arbitrarily.Now the row of A and the columns of the corresponding minterms (0 and 2) are deleted. Step-3: Since B and F are completely covered by C and E respectively hence deleting prime Implicants B and F . Step-4: Now follow the standard procedure of prime Implicant chart mentioned in Example-1. Minterm 1 is covered by prime Implicant C only therefore check () C along with all the minterms which are covered by it (1 and 5). Minterm 6 is covered by prime Implicant E only therefore check () E along with all the minterms which are covered by it (6 and 7). Now since all the min terms (1, 5, 6, 7) are checked() therefore stop the procedure. Final Minimal Expression: A + C + E ManasChhabra2 sooda367 Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Latches in Digital Logic Digital to Analog Conversion Introduction of Sequential Circuits Half Subtractor in Digital Logic Ring Counter in Digital Logic Representation of Negative Binary Numbers Properties of Boolean Algebra Restoring Division Algorithm For Unsigned Integer
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2021" }, { "code": null, "e": 228, "s": 52, "text": "Prerequisite – K-Map (Karnaugh Map), Implicants in K-Map A functions is said to be a Cyclic Boolean Function if there is no Essential prime Implicant in its respective K-Map. " }, { "code": null, "e": 262, "s": 228, "text": "Properties of Cyclic functions: " }, { "code": null, "e": 301, "s": 262, "text": "Every prime Implicant is of same size." }, { "code": null, "e": 404, "s": 301, "text": "Every minterm is covered by at least two prime Implicants (which means no essential prime Implicants)." }, { "code": null, "e": 585, "s": 404, "text": "Having no essential prime Implicants means that there exist more than one minimized Solution / Expression for such functions, which will further be realized using digital circuits." }, { "code": null, "e": 678, "s": 585, "text": "For a cyclic function we can have two minimal forms with no overlapping of prime Implicants." }, { "code": null, "e": 745, "s": 678, "text": "Example: Find the minimal expression for the following function. " }, { "code": null, "e": 791, "s": 745, "text": "f(w, x, y, z) = (0, 2, 4, 5, 10, 11, 13, 15) " }, { "code": null, "e": 933, "s": 793, "text": "As we can see in the above K-Map that there exist no essential prime Implicants. Here we can use prime Implicant chart to solve it easily. " }, { "code": null, "e": 993, "s": 933, "text": "Steps to solve above function using prime Implicant chart: " }, { "code": null, "e": 1451, "s": 995, "text": "Step-1: Draw prime Implicant chart as below.The horizontal entries denote the given minterms which are mapped against all prime Implicants (vertically).The square boxes are crossed (‘x’) whenever a prime Implicant covers a particular minterm in K-Map. For example ‘WXZ’ prime Implicant is covering 13 and 15 therefore the corresponding squares are crossed(denoted by ‘x’). Note that, A, B, C, D .., are variables used to denote all the prime Implicants. " }, { "code": null, "e": 1573, "s": 1451, "text": "For example ‘WXZ’ prime Implicant is covering 13 and 15 therefore the corresponding squares are crossed(denoted by ‘x’). " }, { "code": null, "e": 1655, "s": 1573, "text": "Note that, A, B, C, D .., are variables used to denote all the prime Implicants. " }, { "code": null, "e": 2118, "s": 1659, "text": "Step-2: Arbitrarily choose any prime Implicant; check () the prime Implicant and the corresponding covered minterms as well. Now delete the row of the prime Implicant and corresponding columns of its minterms. In our example prime Implicant A is chosen which is covering minterms 2 and 10. Therefore. delete the row of A and the columns of 2 and 10. The arbitrarily chosen Prime Implicant (in our example A) must be present in the final minimal expression. " }, { "code": null, "e": 2366, "s": 2118, "text": "In our example prime Implicant A is chosen which is covering minterms 2 and 10. Therefore. delete the row of A and the columns of 2 and 10. The arbitrarily chosen Prime Implicant (in our example A) must be present in the final minimal expression. " }, { "code": null, "e": 2744, "s": 2372, "text": "Step-3: Find all such prime Implicant which are being covered by other prime Implicant completely and remove their corresponding rows (since these are non essential prime Implicants.). In our example H is covering {0, 4} and B is covering {0} it means H is covering all the minterms that are covered by B, so delete B. Similarly D is covering C completely, so delete C. " }, { "code": null, "e": 2930, "s": 2744, "text": "In our example H is covering {0, 4} and B is covering {0} it means H is covering all the minterms that are covered by B, so delete B. Similarly D is covering C completely, so delete C. " }, { "code": null, "e": 3329, "s": 2936, "text": "Step-4: Now follow the standard procedure of prime Implicant chart mentioned in the sub steps given below: Find the minterm which is covered by only one prime Implicant. Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. " }, { "code": null, "e": 3615, "s": 3329, "text": "Find the minterm which is covered by only one prime Implicant. Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. " }, { "code": null, "e": 3680, "s": 3615, "text": "Find the minterm which is covered by only one prime Implicant. " }, { "code": null, "e": 3821, "s": 3682, "text": "Check () that minterm, its corresponding prime Implicant and all other minterms which are covered by that corresponding prime Implicant. " }, { "code": null, "e": 3907, "s": 3823, "text": "If all the minterms are checked () stop the procedure, otherwise goto sub-step-1. " }, { "code": null, "e": 3983, "s": 3907, "text": "Example-2: find the minimal expression for the following cyclic function. " }, { "code": null, "e": 4016, "s": 3983, "text": "f(x, y, z) = (0, 1, 2, 5, 6, 7) " }, { "code": null, "e": 4055, "s": 4018, "text": "Step-1: Draw prime Implicant chart. " }, { "code": null, "e": 4176, "s": 4057, "text": "Step-2: A is chosen arbitrarily.Now the row of A and the columns of the corresponding minterms (0 and 2) are deleted. " }, { "code": null, "e": 4292, "s": 4180, "text": "Step-3: Since B and F are completely covered by C and E respectively hence deleting prime Implicants B and F . " }, { "code": null, "e": 4386, "s": 4294, "text": "Step-4: Now follow the standard procedure of prime Implicant chart mentioned in Example-1. " }, { "code": null, "e": 4518, "s": 4386, "text": "Minterm 1 is covered by prime Implicant C only therefore check () C along with all the minterms which are covered by it (1 and 5). " }, { "code": null, "e": 4650, "s": 4518, "text": "Minterm 6 is covered by prime Implicant E only therefore check () E along with all the minterms which are covered by it (6 and 7). " }, { "code": null, "e": 4738, "s": 4652, "text": "Now since all the min terms (1, 5, 6, 7) are checked() therefore stop the procedure. " }, { "code": null, "e": 4778, "s": 4740, "text": "Final Minimal Expression: A + C + E " }, { "code": null, "e": 4794, "s": 4780, "text": "ManasChhabra2" }, { "code": null, "e": 4803, "s": 4794, "text": "sooda367" }, { "code": null, "e": 4838, "s": 4803, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 4936, "s": 4838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4976, "s": 4936, "text": "Introduction to memory and memory units" }, { "code": null, "e": 5005, "s": 4976, "text": "Analog to Digital Conversion" }, { "code": null, "e": 5030, "s": 5005, "text": "Latches in Digital Logic" }, { "code": null, "e": 5059, "s": 5030, "text": "Digital to Analog Conversion" }, { "code": null, "e": 5095, "s": 5059, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 5128, "s": 5095, "text": "Half Subtractor in Digital Logic" }, { "code": null, "e": 5158, "s": 5128, "text": "Ring Counter in Digital Logic" }, { "code": null, "e": 5200, "s": 5158, "text": "Representation of Negative Binary Numbers" }, { "code": null, "e": 5230, "s": 5200, "text": "Properties of Boolean Algebra" } ]
Nagarro Interview Experience for Software Engineer
29 Apr, 2021 I have 2-3 years of Experience in Java/Spring MVC/REST. I participated in Nagarro’s drive-in in March 2021 via referral from a friend. It was a tremendous experience I got from some series of coding tests and interviews. Nagarro is one of the leading industries of today’s era. It is a CMMI level 5 company that focuses more on growth and innovation. Interview IQ Test: 40 questions in 15 minutes (No negative marking)MCQ Test: Technical questions (Questions on AWS, Java-spring, Hibernate, Java-8 streams)Coding Round: On Mettle, need to solve 3 questions in 90 minutes Technical Discussion: First round of technical discussion 1:1. Mostly basics and a few algorithms and data structure related questions Technical Discussion: The second round of technical discussions: application level and in-depth questions of the stream you into. IQ Test: 40 questions in 15 minutes (No negative marking) MCQ Test: Technical questions (Questions on AWS, Java-spring, Hibernate, Java-8 streams) Coding Round: On Mettle, need to solve 3 questions in 90 minutes Technical Discussion: First round of technical discussion 1:1. Mostly basics and a few algorithms and data structure related questions Technical Discussion: The second round of technical discussions: application level and in-depth questions of the stream you into. Round 1(Aptitude Round): First round was conducted on the 2nd March. It had 2 sections, one was about data structures consisted 15 questions and the other section had 15 aptitude questions. I did all of these questions. There was a negative marking for each wrong question in the aptitude. The next day, I got a mail about the next round which was a coding round. Round 2(Coding on Mettle) String are given need to convert it into JavaVaribale and vice-versaFor example- if a given string is: this_is_variableOutput- thisVariable (need to replace _ with empty and next character to _ need to be Capital letter)Find Element in Given array greater than n/2 timesFind character frequency in alphabetical order.ex: "aaddcbb" o/p: "a2b2c1d2" String are given need to convert it into JavaVaribale and vice-versaFor example- if a given string is: this_is_variableOutput- thisVariable (need to replace _ with empty and next character to _ need to be Capital letter) Find Element in Given array greater than n/2 times Find character frequency in alphabetical order.ex: "aaddcbb" o/p: "a2b2c1d2" ex: "aaddcbb" o/p: "a2b2c1d2" Round 3: It was a Technical round on teams for 30 mins slot reserved for me. lambda expressionsPrime numbers 1-50(using streams also)Marker interfaceSpring annotations@Controller@Bean@Component@RestControllerDifference b/w @RestController and @Controller.equals() and hashcode contractDifference between HashMap and HashSetCallable interface2,3 input / output ques related to springtry/catch with resourcesWhat are predicatesHow can we implement our own functional interfaces in javaWhat are streamsDifference between streams and collectionsDifference between filter and map in streamsif we put. @Component annotation on Controller, Service and Repository layer will it work? lambda expressions Prime numbers 1-50(using streams also) Marker interface Spring annotations@Controller@Bean@Component@RestController Difference b/w @RestController and @Controller .equals() and hashcode contract Difference between HashMap and HashSet Callable interface 2,3 input / output ques related to spring try/catch with resources What are predicates How can we implement our own functional interfaces in java What are streams Difference between streams and collections Difference between filter and map in streams if we put. @Component annotation on Controller, Service and Repository layer will it work? On the same day, I got a mail that two interviews will be conducted, technical interview followed by HR interview. On 8th March, my interview was scheduled. It was again an elimination round. Round 4(Technical Interview): The interview started with my introduction. Then there was a discussion on approaches I gave in the coding round. #Interview ques Difference between ArrayList and LinkedListDifference between sleep()and wait()Difference between race condition and deadlockWhy we use synchronized on the block when we can use it on the method Why we use serialization How we validate path in java classnotfound vs classdefinitionnotfoundCount num of zeroes in the binary representation of a number Checked and unchecked exceptions Given ArrayList get unique elements and maintain the order A real-life example of LinkedList Cloning concept in java Ways to create an object in java Does applying synchronized on a method solve the race condition problem?Worked on Azure? What all we need to consume REST APIs provided by third-party service Difference between ArrayList and LinkedList Difference between sleep()and wait() Difference between race condition and deadlock Why we use synchronized on the block when we can use it on the method Why we use serialization How we validate path in java classnotfound vs classdefinitionnotfound Count num of zeroes in the binary representation of a number Checked and unchecked exceptions Given ArrayList get unique elements and maintain the order A real-life example of LinkedList Cloning concept in java Ways to create an object in java Does applying synchronized on a method solve the race condition problem? Worked on Azure? What all we need to consume REST APIs provided by third-party service I answered all the questions they asked. On the same day in the evening, I got a call for my HR round. Round 5(HR Interview): HR interview lasted for only 6 min. The interviewer asked me a few questions including- Why Nagarro?Reason for a job change?Any offers in hand?Where do you see yourself in the next 5 years?Preferred location? Why Nagarro? Reason for a job change? Any offers in hand? Where do you see yourself in the next 5 years? Preferred location? I want to thank GeeksforGeeks for this amazing interview experience section which helped me prepare for Nagarro. Also, thank you GeeksforGeeks for these amazing DSA resources which helped me prepare for the coding round and helped me improve my problem-solving skills. To everyone preparing for the Nagarro interview, prepare well DSA, OOPs, projects, and read more interview experiences, so you are better able to prepare. All the best!! Marketing Nagarro Interview Experiences Nagarro Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Google Interview Questions Write It Up: Share Your Interview Experiences Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Google SWE Interview Experience (Google Online Coding Challenge) 2022 Nagarro Interview Experience Tiger Analytics Interview Experience for Data Analyst (On-Campus) Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2021" }, { "code": null, "e": 405, "s": 54, "text": "I have 2-3 years of Experience in Java/Spring MVC/REST. I participated in Nagarro’s drive-in in March 2021 via referral from a friend. It was a tremendous experience I got from some series of coding tests and interviews. Nagarro is one of the leading industries of today’s era. It is a CMMI level 5 company that focuses more on growth and innovation." }, { "code": null, "e": 415, "s": 405, "text": "Interview" }, { "code": null, "e": 894, "s": 415, "text": "IQ Test: 40 questions in 15 minutes (No negative marking)MCQ Test: Technical questions (Questions on AWS, Java-spring, Hibernate, Java-8 streams)Coding Round: On Mettle, need to solve 3 questions in 90 minutes Technical Discussion: First round of technical discussion 1:1. Mostly basics and a few algorithms and data structure related questions Technical Discussion: The second round of technical discussions: application level and in-depth questions of the stream you into." }, { "code": null, "e": 953, "s": 894, "text": "IQ Test: 40 questions in 15 minutes (No negative marking)" }, { "code": null, "e": 1043, "s": 953, "text": "MCQ Test: Technical questions (Questions on AWS, Java-spring, Hibernate, Java-8 streams)" }, { "code": null, "e": 1110, "s": 1043, "text": "Coding Round: On Mettle, need to solve 3 questions in 90 minutes " }, { "code": null, "e": 1247, "s": 1110, "text": "Technical Discussion: First round of technical discussion 1:1. Mostly basics and a few algorithms and data structure related questions " }, { "code": null, "e": 1377, "s": 1247, "text": "Technical Discussion: The second round of technical discussions: application level and in-depth questions of the stream you into." }, { "code": null, "e": 1447, "s": 1377, "text": "Round 1(Aptitude Round): First round was conducted on the 2nd March. " }, { "code": null, "e": 1668, "s": 1447, "text": "It had 2 sections, one was about data structures consisted 15 questions and the other section had 15 aptitude questions. I did all of these questions. There was a negative marking for each wrong question in the aptitude." }, { "code": null, "e": 1742, "s": 1668, "text": "The next day, I got a mail about the next round which was a coding round." }, { "code": null, "e": 1768, "s": 1742, "text": "Round 2(Coding on Mettle)" }, { "code": null, "e": 2117, "s": 1768, "text": "String are given need to convert it into JavaVaribale and vice-versaFor example- if a given string is: this_is_variableOutput- thisVariable (need to replace _ with empty and next character to _ need to be Capital letter)Find Element in Given array greater than n/2 timesFind character frequency in alphabetical order.ex: \"aaddcbb\"\no/p: \"a2b2c1d2\"" }, { "code": null, "e": 2340, "s": 2117, "text": "String are given need to convert it into JavaVaribale and vice-versaFor example- if a given string is: this_is_variableOutput- thisVariable (need to replace _ with empty and next character to _ need to be Capital letter)" }, { "code": null, "e": 2391, "s": 2340, "text": "Find Element in Given array greater than n/2 times" }, { "code": null, "e": 2468, "s": 2391, "text": "Find character frequency in alphabetical order.ex: \"aaddcbb\"\no/p: \"a2b2c1d2\"" }, { "code": null, "e": 2498, "s": 2468, "text": "ex: \"aaddcbb\"\no/p: \"a2b2c1d2\"" }, { "code": null, "e": 2575, "s": 2498, "text": "Round 3: It was a Technical round on teams for 30 mins slot reserved for me." }, { "code": null, "e": 3174, "s": 2575, "text": "lambda expressionsPrime numbers 1-50(using streams also)Marker interfaceSpring annotations@Controller@Bean@Component@RestControllerDifference b/w @RestController and @Controller.equals() and hashcode contractDifference between HashMap and HashSetCallable interface2,3 input / output ques related to springtry/catch with resourcesWhat are predicatesHow can we implement our own functional interfaces in javaWhat are streamsDifference between streams and collectionsDifference between filter and map in streamsif we put. @Component annotation on Controller, Service and Repository layer will it work?" }, { "code": null, "e": 3193, "s": 3174, "text": "lambda expressions" }, { "code": null, "e": 3232, "s": 3193, "text": "Prime numbers 1-50(using streams also)" }, { "code": null, "e": 3249, "s": 3232, "text": "Marker interface" }, { "code": null, "e": 3309, "s": 3249, "text": "Spring annotations@Controller@Bean@Component@RestController" }, { "code": null, "e": 3356, "s": 3309, "text": "Difference b/w @RestController and @Controller" }, { "code": null, "e": 3388, "s": 3356, "text": ".equals() and hashcode contract" }, { "code": null, "e": 3427, "s": 3388, "text": "Difference between HashMap and HashSet" }, { "code": null, "e": 3446, "s": 3427, "text": "Callable interface" }, { "code": null, "e": 3488, "s": 3446, "text": "2,3 input / output ques related to spring" }, { "code": null, "e": 3513, "s": 3488, "text": "try/catch with resources" }, { "code": null, "e": 3533, "s": 3513, "text": "What are predicates" }, { "code": null, "e": 3592, "s": 3533, "text": "How can we implement our own functional interfaces in java" }, { "code": null, "e": 3609, "s": 3592, "text": "What are streams" }, { "code": null, "e": 3652, "s": 3609, "text": "Difference between streams and collections" }, { "code": null, "e": 3697, "s": 3652, "text": "Difference between filter and map in streams" }, { "code": null, "e": 3788, "s": 3697, "text": "if we put. @Component annotation on Controller, Service and Repository layer will it work?" }, { "code": null, "e": 3903, "s": 3788, "text": "On the same day, I got a mail that two interviews will be conducted, technical interview followed by HR interview." }, { "code": null, "e": 3980, "s": 3903, "text": "On 8th March, my interview was scheduled. It was again an elimination round." }, { "code": null, "e": 4124, "s": 3980, "text": "Round 4(Technical Interview): The interview started with my introduction. Then there was a discussion on approaches I gave in the coding round." }, { "code": null, "e": 4140, "s": 4124, "text": "#Interview ques" }, { "code": null, "e": 4842, "s": 4140, "text": "Difference between ArrayList and LinkedListDifference between sleep()and wait()Difference between race condition and deadlockWhy we use synchronized on the block when we can use it on the method Why we use serialization How we validate path in java classnotfound vs classdefinitionnotfoundCount num of zeroes in the binary representation of a number Checked and unchecked exceptions Given ArrayList get unique elements and maintain the order A real-life example of LinkedList Cloning concept in java Ways to create an object in java Does applying synchronized on a method solve the race condition problem?Worked on Azure? What all we need to consume REST APIs provided by third-party service" }, { "code": null, "e": 4886, "s": 4842, "text": "Difference between ArrayList and LinkedList" }, { "code": null, "e": 4923, "s": 4886, "text": "Difference between sleep()and wait()" }, { "code": null, "e": 4970, "s": 4923, "text": "Difference between race condition and deadlock" }, { "code": null, "e": 5042, "s": 4970, "text": "Why we use synchronized on the block when we can use it on the method " }, { "code": null, "e": 5069, "s": 5042, "text": "Why we use serialization " }, { "code": null, "e": 5100, "s": 5069, "text": "How we validate path in java " }, { "code": null, "e": 5141, "s": 5100, "text": "classnotfound vs classdefinitionnotfound" }, { "code": null, "e": 5204, "s": 5141, "text": "Count num of zeroes in the binary representation of a number " }, { "code": null, "e": 5239, "s": 5204, "text": "Checked and unchecked exceptions " }, { "code": null, "e": 5300, "s": 5239, "text": "Given ArrayList get unique elements and maintain the order " }, { "code": null, "e": 5336, "s": 5300, "text": "A real-life example of LinkedList " }, { "code": null, "e": 5362, "s": 5336, "text": "Cloning concept in java " }, { "code": null, "e": 5397, "s": 5362, "text": "Ways to create an object in java " }, { "code": null, "e": 5470, "s": 5397, "text": "Does applying synchronized on a method solve the race condition problem?" }, { "code": null, "e": 5489, "s": 5470, "text": "Worked on Azure? " }, { "code": null, "e": 5559, "s": 5489, "text": "What all we need to consume REST APIs provided by third-party service" }, { "code": null, "e": 5662, "s": 5559, "text": "I answered all the questions they asked. On the same day in the evening, I got a call for my HR round." }, { "code": null, "e": 5773, "s": 5662, "text": "Round 5(HR Interview): HR interview lasted for only 6 min. The interviewer asked me a few questions including-" }, { "code": null, "e": 5894, "s": 5773, "text": "Why Nagarro?Reason for a job change?Any offers in hand?Where do you see yourself in the next 5 years?Preferred location?" }, { "code": null, "e": 5907, "s": 5894, "text": "Why Nagarro?" }, { "code": null, "e": 5932, "s": 5907, "text": "Reason for a job change?" }, { "code": null, "e": 5952, "s": 5932, "text": "Any offers in hand?" }, { "code": null, "e": 5999, "s": 5952, "text": "Where do you see yourself in the next 5 years?" }, { "code": null, "e": 6019, "s": 5999, "text": "Preferred location?" }, { "code": null, "e": 6288, "s": 6019, "text": "I want to thank GeeksforGeeks for this amazing interview experience section which helped me prepare for Nagarro. Also, thank you GeeksforGeeks for these amazing DSA resources which helped me prepare for the coding round and helped me improve my problem-solving skills." }, { "code": null, "e": 6458, "s": 6288, "text": "To everyone preparing for the Nagarro interview, prepare well DSA, OOPs, projects, and read more interview experiences, so you are better able to prepare. All the best!!" }, { "code": null, "e": 6468, "s": 6458, "text": "Marketing" }, { "code": null, "e": 6476, "s": 6468, "text": "Nagarro" }, { "code": null, "e": 6498, "s": 6476, "text": "Interview Experiences" }, { "code": null, "e": 6506, "s": 6498, "text": "Nagarro" }, { "code": null, "e": 6604, "s": 6506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6642, "s": 6604, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 6698, "s": 6642, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 6725, "s": 6698, "text": "Google Interview Questions" }, { "code": null, "e": 6771, "s": 6725, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 6844, "s": 6771, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 6882, "s": 6844, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 6952, "s": 6882, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 6981, "s": 6952, "text": "Nagarro Interview Experience" }, { "code": null, "e": 7047, "s": 6981, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" } ]
C# | Check if OrderedDictionary collection contains a specific key - GeeksforGeeks
01 Feb, 2019 OrderedDictionary.Contains(Object) method is used to check whether the OrderedDictionary collection contains a specific key or not. Syntax: public bool Contains (object key); Here, key is the key to locate in the OrderedDictionary collection. Return Value: This method returns True if the OrderedDictionary collection contains an element with the specified key, otherwise, False. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to check if OrderedDictionary// collection contains a specific keyusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // Checking if OrderedDictionary // collection contains a specific key Console.WriteLine(myDict.Contains("Key6")); }} Output: False Example 2: // C# code to check if OrderedDictionary// collection contains a specific keyusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // Displaying the key/value pairs in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + " --> " + de.Value); // Checking if OrderedDictionary collection // contains a specific key if (myDict.Contains("key4")) myDict.Remove("key4"); // Displaying the key/value pairs in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + " --> " + de.Value); }} Output: key1 --> value1 key2 --> value2 key3 --> value3 key4 --> value4 key5 --> value5 key1 --> value1 key2 --> value2 key3 --> value3 key5 --> value5 Note: Using the Item[Object] property can return a null value if the key does not exist or if the key is null. Use the Contains method to determine if a specific key exists in the OrderedDictionary collection. Reference:https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary.contains?view=netframework-4.7.2 CSharp-method CSharp-Specialized-Namespace CSharp-Specialized-OrderedDictionary C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Constructors C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Data Types Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
[ { "code": null, "e": 24680, "s": 24652, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24812, "s": 24680, "text": "OrderedDictionary.Contains(Object) method is used to check whether the OrderedDictionary collection contains a specific key or not." }, { "code": null, "e": 24820, "s": 24812, "text": "Syntax:" }, { "code": null, "e": 24856, "s": 24820, "text": "public bool Contains (object key);\n" }, { "code": null, "e": 24924, "s": 24856, "text": "Here, key is the key to locate in the OrderedDictionary collection." }, { "code": null, "e": 25061, "s": 24924, "text": "Return Value: This method returns True if the OrderedDictionary collection contains an element with the specified key, otherwise, False." }, { "code": null, "e": 25141, "s": 25061, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25152, "s": 25141, "text": "Example 1:" }, { "code": "// C# code to check if OrderedDictionary// collection contains a specific keyusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add(\"key1\", \"value1\"); myDict.Add(\"key2\", \"value2\"); myDict.Add(\"key3\", \"value3\"); myDict.Add(\"key4\", \"value4\"); myDict.Add(\"key5\", \"value5\"); // Checking if OrderedDictionary // collection contains a specific key Console.WriteLine(myDict.Contains(\"Key6\")); }}", "e": 25859, "s": 25152, "text": null }, { "code": null, "e": 25867, "s": 25859, "text": "Output:" }, { "code": null, "e": 25874, "s": 25867, "text": "False\n" }, { "code": null, "e": 25885, "s": 25874, "text": "Example 2:" }, { "code": "// C# code to check if OrderedDictionary// collection contains a specific keyusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add(\"key1\", \"value1\"); myDict.Add(\"key2\", \"value2\"); myDict.Add(\"key3\", \"value3\"); myDict.Add(\"key4\", \"value4\"); myDict.Add(\"key5\", \"value5\"); // Displaying the key/value pairs in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + \" --> \" + de.Value); // Checking if OrderedDictionary collection // contains a specific key if (myDict.Contains(\"key4\")) myDict.Remove(\"key4\"); // Displaying the key/value pairs in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + \" --> \" + de.Value); }}", "e": 26925, "s": 25885, "text": null }, { "code": null, "e": 26933, "s": 26925, "text": "Output:" }, { "code": null, "e": 27078, "s": 26933, "text": "key1 --> value1\nkey2 --> value2\nkey3 --> value3\nkey4 --> value4\nkey5 --> value5\nkey1 --> value1\nkey2 --> value2\nkey3 --> value3\nkey5 --> value5\n" }, { "code": null, "e": 27288, "s": 27078, "text": "Note: Using the Item[Object] property can return a null value if the key does not exist or if the key is null. Use the Contains method to determine if a specific key exists in the OrderedDictionary collection." }, { "code": null, "e": 27424, "s": 27288, "text": "Reference:https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary.contains?view=netframework-4.7.2" }, { "code": null, "e": 27438, "s": 27424, "text": "CSharp-method" }, { "code": null, "e": 27467, "s": 27438, "text": "CSharp-Specialized-Namespace" }, { "code": null, "e": 27504, "s": 27467, "text": "CSharp-Specialized-OrderedDictionary" }, { "code": null, "e": 27507, "s": 27504, "text": "C#" }, { "code": null, "e": 27605, "s": 27507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27614, "s": 27605, "text": "Comments" }, { "code": null, "e": 27627, "s": 27614, "text": "Old Comments" }, { "code": null, "e": 27650, "s": 27627, "text": "C# | Method Overriding" }, { "code": null, "e": 27672, "s": 27650, "text": "C# | Class and Object" }, { "code": null, "e": 27712, "s": 27672, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27735, "s": 27712, "text": "Extension Method in C#" }, { "code": null, "e": 27753, "s": 27735, "text": "C# | Constructors" }, { "code": null, "e": 27768, "s": 27753, "text": "C# | Delegates" }, { "code": null, "e": 27799, "s": 27768, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27845, "s": 27799, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27861, "s": 27845, "text": "C# | Data Types" } ]
journalctl Command in Linux with Examples - GeeksforGeeks
10 Feb, 2022 journalctl command in Linux is used to view systemd, kernel and journal logs. The logs are presented in the following way: -- Logs begin at [date_time_stamp], end at [dat_time_stamp] [date_time_stamp] [host_name] kernel: It displays the paginated output, hence it is a bit easy to navigate through a lot of logs. It prints the log in the chronological order with the oldest first. 1. To display all logs $journalctl It displays all the logs in the paginated view. 2. To reverse the order or to display the new entries first. $journalctl -r This will display the logs in the chronological order with the newest first. 3. To display only a few log entries $journalctl -n 2 This will display just 2 log entries. 4. To get log entries containing a specific keyword. $journalctl | grep Centaur This will display all the entries containing the word Centaur in them. 5. To display priority specific log entries. $journalctl -p warning It displays all log entries with priority as a warning. 6. To print verbose customized output. $journalctl -o verbose This will display the formatted output in verbose mode. 7. To display the boots of the system. $journalctl --list-boots To display all the boots of the system. 8. To display journalctl help. $journalctl --help The above command will display the help section of the journalctl command. rkbhola5 linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24089, "s": 24058, "text": " \n10 Feb, 2022\n" }, { "code": null, "e": 24212, "s": 24089, "text": "journalctl command in Linux is used to view systemd, kernel and journal logs. The logs are presented in the following way:" }, { "code": null, "e": 24311, "s": 24212, "text": "-- Logs begin at [date_time_stamp], end at [dat_time_stamp]\n[date_time_stamp] [host_name] kernel:\n" }, { "code": null, "e": 24471, "s": 24311, "text": "It displays the paginated output, hence it is a bit easy to navigate through a lot of logs. It prints the log in the chronological order with the oldest first." }, { "code": null, "e": 24494, "s": 24471, "text": "1. To display all logs" }, { "code": null, "e": 24507, "s": 24494, "text": "$journalctl\n" }, { "code": null, "e": 24555, "s": 24507, "text": "It displays all the logs in the paginated view." }, { "code": null, "e": 24616, "s": 24555, "text": "2. To reverse the order or to display the new entries first." }, { "code": null, "e": 24632, "s": 24616, "text": "$journalctl -r\n" }, { "code": null, "e": 24709, "s": 24632, "text": "This will display the logs in the chronological order with the newest first." }, { "code": null, "e": 24746, "s": 24709, "text": "3. To display only a few log entries" }, { "code": null, "e": 24764, "s": 24746, "text": "$journalctl -n 2\n" }, { "code": null, "e": 24802, "s": 24764, "text": "This will display just 2 log entries." }, { "code": null, "e": 24855, "s": 24802, "text": "4. To get log entries containing a specific keyword." }, { "code": null, "e": 24883, "s": 24855, "text": "$journalctl | grep Centaur\n" }, { "code": null, "e": 24954, "s": 24883, "text": "This will display all the entries containing the word Centaur in them." }, { "code": null, "e": 24999, "s": 24954, "text": "5. To display priority specific log entries." }, { "code": null, "e": 25023, "s": 24999, "text": "$journalctl -p warning\n" }, { "code": null, "e": 25079, "s": 25023, "text": "It displays all log entries with priority as a warning." }, { "code": null, "e": 25118, "s": 25079, "text": "6. To print verbose customized output." }, { "code": null, "e": 25142, "s": 25118, "text": "$journalctl -o verbose\n" }, { "code": null, "e": 25198, "s": 25142, "text": "This will display the formatted output in verbose mode." }, { "code": null, "e": 25237, "s": 25198, "text": "7. To display the boots of the system." }, { "code": null, "e": 25263, "s": 25237, "text": "$journalctl --list-boots\n" }, { "code": null, "e": 25303, "s": 25263, "text": "To display all the boots of the system." }, { "code": null, "e": 25334, "s": 25303, "text": "8. To display journalctl help." }, { "code": null, "e": 25354, "s": 25334, "text": "$journalctl --help\n" }, { "code": null, "e": 25429, "s": 25354, "text": "The above command will display the help section of the journalctl command." }, { "code": null, "e": 25438, "s": 25429, "text": "rkbhola5" }, { "code": null, "e": 25454, "s": 25438, "text": "\nlinux-command\n" }, { "code": null, "e": 25478, "s": 25454, "text": "\nLinux-system-commands\n" }, { "code": null, "e": 25491, "s": 25478, "text": "\nLinux-Unix\n" }, { "code": null, "e": 25696, "s": 25491, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 25722, "s": 25696, "text": "Thread functions in C/C++" }, { "code": null, "e": 25759, "s": 25722, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25793, "s": 25759, "text": "mv command in Linux with examples" }, { "code": null, "e": 25828, "s": 25793, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25854, "s": 25828, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25891, "s": 25854, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25931, "s": 25891, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 25960, "s": 25931, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26002, "s": 25960, "text": "Named Pipe or FIFO with example C program" } ]
Get first and last elements of a list in Python
There may be situation when you need to get the first and last element of the list. The tricky part here is you have to keep track of the length of the list while finding out these elements from the lists. Below are the approaches which we can use to achieve this. But of course all the approaches involve using the index of the elements in the list. In any list the first element is assigned index value 0 and the last element can be considered as a value -1. So we apply these index values to the list directly and get the desired result. Live Demo Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) print("The first element of the list : ",Alist[0]) print("The last element of the list : ",Alist[-1]) Running the above code gives us the following result − The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] The first element of the list : Sun The last element of the list : Thu List slicing is another method in which we directly refer to the positions of elements using the slicing technique using colons. The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input. Live Demo Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) first_last = Alist[::len(Alist)-1] print(first_last) Running the above code gives us the following result − The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] ['Sun', 'Thu'] We can also use a for loop with in operator giving the index values as 0 and -1. Live Demo Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) first_last = [Alist[n] for n in (0,-1)] print(first_last) Running the above code gives us the following result − The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] ['Sun', 'Thu']
[ { "code": null, "e": 1413, "s": 1062, "text": "There may be situation when you need to get the first and last element of the list. The tricky part here is you have to keep track of the length of the list while finding out these elements from the lists. Below are the approaches which we can use to achieve this. But of course all the approaches involve using the index of the elements in the list." }, { "code": null, "e": 1603, "s": 1413, "text": "In any list the first element is assigned index value 0 and the last element can be considered as a value -1. So we apply these index values to the list directly and get the desired result." }, { "code": null, "e": 1614, "s": 1603, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1614, "text": "Alist = ['Sun','Mon','Tue','Wed','Thu']\nprint(\"The given list : \",Alist)\n\nprint(\"The first element of the list : \",Alist[0])\nprint(\"The last element of the list : \",Alist[-1])" }, { "code": null, "e": 1845, "s": 1790, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1969, "s": 1845, "text": "The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu']\nThe first element of the list : Sun\nThe last element of the list : Thu" }, { "code": null, "e": 2251, "s": 1969, "text": "List slicing is another method in which we directly refer to the positions of elements using the slicing technique using colons. The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input." }, { "code": null, "e": 2262, "s": 2251, "text": " Live Demo" }, { "code": null, "e": 2389, "s": 2262, "text": "Alist = ['Sun','Mon','Tue','Wed','Thu']\nprint(\"The given list : \",Alist)\n\nfirst_last = Alist[::len(Alist)-1]\nprint(first_last)" }, { "code": null, "e": 2444, "s": 2389, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2512, "s": 2444, "text": "The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu']\n['Sun', 'Thu']" }, { "code": null, "e": 2593, "s": 2512, "text": "We can also use a for loop with in operator giving the index values as 0 and -1." }, { "code": null, "e": 2604, "s": 2593, "text": " Live Demo" }, { "code": null, "e": 2736, "s": 2604, "text": "Alist = ['Sun','Mon','Tue','Wed','Thu']\nprint(\"The given list : \",Alist)\n\nfirst_last = [Alist[n] for n in (0,-1)]\nprint(first_last)" }, { "code": null, "e": 2791, "s": 2736, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2859, "s": 2791, "text": "The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu']\n['Sun', 'Thu']" } ]
PHPunit | assertNotEquals() Function - GeeksforGeeks
31 Jul, 2019 The assertNotEquals() function is a builtin function in PHPUnit and is used to assert the actual obtained value to be not-equals to expected value. This assertion will return true in the case if the expected value is not-equals to actual value else returns false. In case of true the asserted test case got passed else test case got failed. Syntax: assertNotEquals( mixed $expected, mixed $actual, string $message = '' ) Parameters: This function accepts three parameters as shown in the above syntax. The parameters are described below: $expected: This parameter is of any type which represent the expected data. $actual: This parameter is of any type which represent the actual data. $message: This parameter takes string value. When the testcase got failed this string message got displayed as error message. Below programs illustrate the assertNotEquals() function in PHPUnit: Program 1: <?phpuse PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testNegativeTestcaseForAssertNotEquals() { $expected = "geeks"; $actual = "geeks"; // Assert function to test whether expected // value is unequal to actual or not $this->assertNotEquals( $expected, $actual, "actual value is equals to expected" ); }} ?> Output: PHPUnit 8.2.5 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time: 67 ms, Memory: 10.00 MB There was 1 failure: 1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertNotEquals actual value is equals to expected Failed asserting that 'geeks' is not equal to 'geeks'. /home/shivam/Documents/geeks/phpunit/abc.php:15 FAILURES! Tests: 1, Assertions: 1, Failures: 1. Program 2: <?phpuse PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testPositiveTestcaseForAssertNotEquals() { $expected = "geeks"; $actual = "Geeks"; // Assert function to test whether expected // value is unequal to actual or not $this->assertNotEquals( $expected, $actual, "actual value is not equals to expected" ); }} ?> Output: PHPUnit 8.2.5 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 67 ms, Memory: 10.00 MB OK (1 test, 1 assertion) Note: To run testcases with phpunit follow steps from here. Also, assertNotEquals() is supported by phpunit 7 and above. PHP-function PHP-PHPUnit PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24334, "s": 24306, "text": "\n31 Jul, 2019" }, { "code": null, "e": 24675, "s": 24334, "text": "The assertNotEquals() function is a builtin function in PHPUnit and is used to assert the actual obtained value to be not-equals to expected value. This assertion will return true in the case if the expected value is not-equals to actual value else returns false. In case of true the asserted test case got passed else test case got failed." }, { "code": null, "e": 24683, "s": 24675, "text": "Syntax:" }, { "code": null, "e": 24756, "s": 24683, "text": "assertNotEquals( mixed $expected, mixed $actual, string $message = '' )\n" }, { "code": null, "e": 24873, "s": 24756, "text": "Parameters: This function accepts three parameters as shown in the above syntax. The parameters are described below:" }, { "code": null, "e": 24949, "s": 24873, "text": "$expected: This parameter is of any type which represent the expected data." }, { "code": null, "e": 25021, "s": 24949, "text": "$actual: This parameter is of any type which represent the actual data." }, { "code": null, "e": 25147, "s": 25021, "text": "$message: This parameter takes string value. When the testcase got failed this string message got displayed as error message." }, { "code": null, "e": 25216, "s": 25147, "text": "Below programs illustrate the assertNotEquals() function in PHPUnit:" }, { "code": null, "e": 25227, "s": 25216, "text": "Program 1:" }, { "code": "<?phpuse PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testNegativeTestcaseForAssertNotEquals() { $expected = \"geeks\"; $actual = \"geeks\"; // Assert function to test whether expected // value is unequal to actual or not $this->assertNotEquals( $expected, $actual, \"actual value is equals to expected\" ); }} ?>", "e": 25667, "s": 25227, "text": null }, { "code": null, "e": 25675, "s": 25667, "text": "Output:" }, { "code": null, "e": 26118, "s": 25675, "text": "PHPUnit 8.2.5 by Sebastian Bergmann and contributors.\n\nF 1 / 1 (100%)\n\nTime: 67 ms, Memory: 10.00 MB\n\nThere was 1 failure:\n\n1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertNotEquals\nactual value is equals to expected\nFailed asserting that 'geeks' is not equal to 'geeks'.\n\n/home/shivam/Documents/geeks/phpunit/abc.php:15\n\nFAILURES!\nTests: 1, Assertions: 1, Failures: 1.\n" }, { "code": null, "e": 26129, "s": 26118, "text": "Program 2:" }, { "code": "<?phpuse PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testPositiveTestcaseForAssertNotEquals() { $expected = \"geeks\"; $actual = \"Geeks\"; // Assert function to test whether expected // value is unequal to actual or not $this->assertNotEquals( $expected, $actual, \"actual value is not equals to expected\" ); }} ?>", "e": 26573, "s": 26129, "text": null }, { "code": null, "e": 26581, "s": 26573, "text": "Output:" }, { "code": null, "e": 26775, "s": 26581, "text": "PHPUnit 8.2.5 by Sebastian Bergmann and contributors.\n\n. 1 / 1 (100%)\n\nTime: 67 ms, Memory: 10.00 MB\n\nOK (1 test, 1 assertion)\n" }, { "code": null, "e": 26896, "s": 26775, "text": "Note: To run testcases with phpunit follow steps from here. Also, assertNotEquals() is supported by phpunit 7 and above." }, { "code": null, "e": 26909, "s": 26896, "text": "PHP-function" }, { "code": null, "e": 26921, "s": 26909, "text": "PHP-PHPUnit" }, { "code": null, "e": 26925, "s": 26921, "text": "PHP" }, { "code": null, "e": 26942, "s": 26925, "text": "Web Technologies" }, { "code": null, "e": 26946, "s": 26942, "text": "PHP" }, { "code": null, "e": 27044, "s": 26946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27053, "s": 27044, "text": "Comments" }, { "code": null, "e": 27066, "s": 27053, "text": "Old Comments" }, { "code": null, "e": 27116, "s": 27066, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27156, "s": 27116, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27217, "s": 27156, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27267, "s": 27217, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27294, "s": 27267, "text": "Comparing two dates in PHP" }, { "code": null, "e": 27327, "s": 27294, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27369, "s": 27327, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27412, "s": 27369, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27474, "s": 27412, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
AWK - User Defined Functions
Functions are basic building blocks of a program. AWK allows us to define our own functions. A large program can be divided into functions and each function can be written/tested independently. It provides re-usability of code. Given below is the general format of a user-defined function − function function_name(argument1, argument2, ...) { function body } In this syntax, the function_name is the name of the user-defined function. Function name should begin with a letter and the rest of the characters can be any combination of numbers, alphabetic characters, or underscore. AWK's reserve words cannot be used as function names. Functions can accept multiple arguments separated by comma. Arguments are not mandatory. You can also create a user-defined function without any argument. function body consists of one or more AWK statements. Let us write two functions that calculate the minimum and the maximum number and call these functions from another function called main. The functions.awk file contains − # Returns minimum number function find_min(num1, num2){ if (num1 < num2) return num1 return num2 } # Returns maximum number function find_max(num1, num2){ if (num1 > num2) return num1 return num2 } # Main function function main(num1, num2){ # Find minimum number result = find_min(10, 20) print "Minimum =", result # Find maximum number result = find_max(10, 20) print "Maximum =", result } # Script execution starts here BEGIN { main(10, 20) } On executing this code, you get the following result − Minimum = 10 Maximum = 20 Print Add Notes Bookmark this page
[ { "code": null, "e": 2085, "s": 1857, "text": "Functions are basic building blocks of a program. AWK allows us to define our own functions. A large program can be divided into functions and each function can be written/tested independently. It provides re-usability of code." }, { "code": null, "e": 2148, "s": 2085, "text": "Given below is the general format of a user-defined function −" }, { "code": null, "e": 2221, "s": 2148, "text": "function function_name(argument1, argument2, ...) { \n function body\n}\n" }, { "code": null, "e": 2496, "s": 2221, "text": "In this syntax, the function_name is the name of the user-defined function. Function name should begin with a letter and the rest of the characters can be any combination of numbers, alphabetic characters, or underscore. AWK's reserve words cannot be used as function names." }, { "code": null, "e": 2651, "s": 2496, "text": "Functions can accept multiple arguments separated by comma. Arguments are not mandatory. You can also create a user-defined function without any argument." }, { "code": null, "e": 2705, "s": 2651, "text": "function body consists of one or more AWK statements." }, { "code": null, "e": 2876, "s": 2705, "text": "Let us write two functions that calculate the minimum and the maximum number and call these functions from another function called main. The functions.awk file contains −" }, { "code": null, "e": 3363, "s": 2876, "text": "# Returns minimum number\nfunction find_min(num1, num2){\n if (num1 < num2)\n return num1\n return num2\n}\n# Returns maximum number\nfunction find_max(num1, num2){\n if (num1 > num2)\n return num1\n return num2\n}\n# Main function\nfunction main(num1, num2){\n # Find minimum number\n result = find_min(10, 20)\n print \"Minimum =\", result\n \n # Find maximum number\n result = find_max(10, 20)\n print \"Maximum =\", result\n}\n# Script execution starts here\nBEGIN {\n main(10, 20)\n}" }, { "code": null, "e": 3418, "s": 3363, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3445, "s": 3418, "text": "Minimum = 10\nMaximum = 20\n" }, { "code": null, "e": 3452, "s": 3445, "text": " Print" }, { "code": null, "e": 3463, "s": 3452, "text": " Add Notes" } ]
How to Use the Reddit API in Python | Towards Data Science
Reddit is a huge ecosystem brimming with data that is readily available at our very fingertips. As a data-minded person, I wanted to take advantage of this and perform some analysis using this vast repository of open-source data. Initially, it turned out that getting to grip with Reddit’s API wasn’t as clear-cut as expected — despite being a straightforward process; it can be a little confusing at first. So, after figuring everything out, I wrote this article — which I hope will help a few of you to get familiar with using the Reddit API in Python. We will cover: > Getting Access> Making Requests - Reading the Data - Streaming New Posts> Parameters If you prefer video, I cover everything from this article here too: First, we need access. Unlike most popular services, the Reddit API was somewhat difficult to figure out initially. There are several steps: 1. Go to App Preferences and click create another app... at the bottom. 2. Fill out the required details, make sure to select script — and click create app. 3. make a note of the personal use script and secret tokens: 4. Request a temporary OAuth token from Reddit. We need our username and password for this: 5. Add headers=headers to every request. The OAuth token will expire after ~2 hours, and a new one will need to be requested. Now we have everything set up — we can begin making requests. If we want to start pulling Reddit data, our first stop could be to begin reading the top posts in our selected subreddits. Let’s start with /r/Python. We can retrieve the most popular posts with GET /r/subreddit/hot like so: We return a lot of data, so let’s filter for something more readable. Each post can be accessed by looping through each item in res.json()['data']['children']. Each post’s title is stored inside 'title', an item inside the 'data' dictionary — so, we print the title of every post like this: We can use the same approach to build a dataframe containing basic information about the post. In particular, it may be useful to pull the title, date-time, content, and reactions to a post. We can modify our code very slightly to return all of the most recent posts instead. Providing us with a stream of posts as they’re made in real-time. If we look at the API documentation here, we can see that GET /r/subreddit/new it provides the functionality we need. All we need to do us change our get request from /r/python/hot to /r/python/new: And with that, we have built two methods for scraping data from any subreddit — and we can use essentially the same code for any other method too! But there is more. There are a few parameters that we can add to our queries. The most relevant for scraping data are: limit — the maximum number of items to return. before/after — used to specify that we only want to search for posts that are before or after another. The limit parameter is pretty self-explanatory. We pass a number to specify that we would like to receive no more than this number of items. Where applicable, the limit is set to 25 by default. We can pump this up to a maximum value of 100 items. Next up are the before and after parameters. These both work in the same way — we pass a post fullname, and the API will then retrieve items that are either before or after that post. Confusingly, after means further back in time, whereas before means more recently in time. So, if we take item t3_k3vndz at 13:21: before gives us t3_k3vsri at 13:30. after gives us t3_k3usna at 12:21. All we need now is to find the fullname of our items. Back in the Reddit API docs, this section explains exactly what we need. We first need to identify what type of item we are working with. In our example, we have been extracting posts on the /r/Python subreddit. These posts are classified as links — as they do, in fact, link to the post itself. Rather than guessing what type of item we are returning from the API — we simply check. The type for our returned posts is provided in the items 'kind' key: Likewise, the ID is provided in our response too. Within the data dictionary, we have an 'id' key. We concatenate these two parts together to create a fullname: Now that we have a method for building fullnames — we can enhance our data collection to travel further back in time. To do this, we: Request the 100 newest posts, storing the response in df.Get the fullname of the oldest post in df.Request the 100 posts that were published after our fullname.Append our new posts to df.Repeat steps 2–4 until satisfied! Request the 100 newest posts, storing the response in df. Get the fullname of the oldest post in df. Request the 100 posts that were published after our fullname. Append our new posts to df. Repeat steps 2–4 until satisfied! With that, we have built a tool for extracting huge amounts of what can be incredibly valuable data from Reddit. The full script for this tool is here: Once we have set up our API authentication and made a few requests, it becomes much easier to understand how to interact with the API. The Reddit API documentation is simple, which makes it very easy to understand — I would definitely recommend scrolling through to see what can be done with it. An alternative is to use the Python PRAW library — a purpose-built library for interacting with the Reddit API. If you’re not too comfortable with requests or would simply appreciate the added layer of abstraction, check it out! That is all for this introduction to using the Reddit API in Python! I hope it has been useful — if you have any questions or feedback, let me know via Twitter or in the comments below. Thanks for reading! Reddit API Docs 🤖 NLP With Transformers Course
[ { "code": null, "e": 402, "s": 172, "text": "Reddit is a huge ecosystem brimming with data that is readily available at our very fingertips. As a data-minded person, I wanted to take advantage of this and perform some analysis using this vast repository of open-source data." }, { "code": null, "e": 580, "s": 402, "text": "Initially, it turned out that getting to grip with Reddit’s API wasn’t as clear-cut as expected — despite being a straightforward process; it can be a little confusing at first." }, { "code": null, "e": 742, "s": 580, "text": "So, after figuring everything out, I wrote this article — which I hope will help a few of you to get familiar with using the Reddit API in Python. We will cover:" }, { "code": null, "e": 831, "s": 742, "text": "> Getting Access> Making Requests - Reading the Data - Streaming New Posts> Parameters" }, { "code": null, "e": 899, "s": 831, "text": "If you prefer video, I cover everything from this article here too:" }, { "code": null, "e": 1040, "s": 899, "text": "First, we need access. Unlike most popular services, the Reddit API was somewhat difficult to figure out initially. There are several steps:" }, { "code": null, "e": 1112, "s": 1040, "text": "1. Go to App Preferences and click create another app... at the bottom." }, { "code": null, "e": 1197, "s": 1112, "text": "2. Fill out the required details, make sure to select script — and click create app." }, { "code": null, "e": 1258, "s": 1197, "text": "3. make a note of the personal use script and secret tokens:" }, { "code": null, "e": 1350, "s": 1258, "text": "4. Request a temporary OAuth token from Reddit. We need our username and password for this:" }, { "code": null, "e": 1476, "s": 1350, "text": "5. Add headers=headers to every request. The OAuth token will expire after ~2 hours, and a new one will need to be requested." }, { "code": null, "e": 1662, "s": 1476, "text": "Now we have everything set up — we can begin making requests. If we want to start pulling Reddit data, our first stop could be to begin reading the top posts in our selected subreddits." }, { "code": null, "e": 1764, "s": 1662, "text": "Let’s start with /r/Python. We can retrieve the most popular posts with GET /r/subreddit/hot like so:" }, { "code": null, "e": 1924, "s": 1764, "text": "We return a lot of data, so let’s filter for something more readable. Each post can be accessed by looping through each item in res.json()['data']['children']." }, { "code": null, "e": 2055, "s": 1924, "text": "Each post’s title is stored inside 'title', an item inside the 'data' dictionary — so, we print the title of every post like this:" }, { "code": null, "e": 2246, "s": 2055, "text": "We can use the same approach to build a dataframe containing basic information about the post. In particular, it may be useful to pull the title, date-time, content, and reactions to a post." }, { "code": null, "e": 2397, "s": 2246, "text": "We can modify our code very slightly to return all of the most recent posts instead. Providing us with a stream of posts as they’re made in real-time." }, { "code": null, "e": 2596, "s": 2397, "text": "If we look at the API documentation here, we can see that GET /r/subreddit/new it provides the functionality we need. All we need to do us change our get request from /r/python/hot to /r/python/new:" }, { "code": null, "e": 2743, "s": 2596, "text": "And with that, we have built two methods for scraping data from any subreddit — and we can use essentially the same code for any other method too!" }, { "code": null, "e": 2862, "s": 2743, "text": "But there is more. There are a few parameters that we can add to our queries. The most relevant for scraping data are:" }, { "code": null, "e": 2909, "s": 2862, "text": "limit — the maximum number of items to return." }, { "code": null, "e": 3012, "s": 2909, "text": "before/after — used to specify that we only want to search for posts that are before or after another." }, { "code": null, "e": 3153, "s": 3012, "text": "The limit parameter is pretty self-explanatory. We pass a number to specify that we would like to receive no more than this number of items." }, { "code": null, "e": 3259, "s": 3153, "text": "Where applicable, the limit is set to 25 by default. We can pump this up to a maximum value of 100 items." }, { "code": null, "e": 3443, "s": 3259, "text": "Next up are the before and after parameters. These both work in the same way — we pass a post fullname, and the API will then retrieve items that are either before or after that post." }, { "code": null, "e": 3574, "s": 3443, "text": "Confusingly, after means further back in time, whereas before means more recently in time. So, if we take item t3_k3vndz at 13:21:" }, { "code": null, "e": 3610, "s": 3574, "text": "before gives us t3_k3vsri at 13:30." }, { "code": null, "e": 3645, "s": 3610, "text": "after gives us t3_k3usna at 12:21." }, { "code": null, "e": 3772, "s": 3645, "text": "All we need now is to find the fullname of our items. Back in the Reddit API docs, this section explains exactly what we need." }, { "code": null, "e": 3995, "s": 3772, "text": "We first need to identify what type of item we are working with. In our example, we have been extracting posts on the /r/Python subreddit. These posts are classified as links — as they do, in fact, link to the post itself." }, { "code": null, "e": 4152, "s": 3995, "text": "Rather than guessing what type of item we are returning from the API — we simply check. The type for our returned posts is provided in the items 'kind' key:" }, { "code": null, "e": 4313, "s": 4152, "text": "Likewise, the ID is provided in our response too. Within the data dictionary, we have an 'id' key. We concatenate these two parts together to create a fullname:" }, { "code": null, "e": 4431, "s": 4313, "text": "Now that we have a method for building fullnames — we can enhance our data collection to travel further back in time." }, { "code": null, "e": 4447, "s": 4431, "text": "To do this, we:" }, { "code": null, "e": 4668, "s": 4447, "text": "Request the 100 newest posts, storing the response in df.Get the fullname of the oldest post in df.Request the 100 posts that were published after our fullname.Append our new posts to df.Repeat steps 2–4 until satisfied!" }, { "code": null, "e": 4726, "s": 4668, "text": "Request the 100 newest posts, storing the response in df." }, { "code": null, "e": 4769, "s": 4726, "text": "Get the fullname of the oldest post in df." }, { "code": null, "e": 4831, "s": 4769, "text": "Request the 100 posts that were published after our fullname." }, { "code": null, "e": 4859, "s": 4831, "text": "Append our new posts to df." }, { "code": null, "e": 4893, "s": 4859, "text": "Repeat steps 2–4 until satisfied!" }, { "code": null, "e": 5045, "s": 4893, "text": "With that, we have built a tool for extracting huge amounts of what can be incredibly valuable data from Reddit. The full script for this tool is here:" }, { "code": null, "e": 5180, "s": 5045, "text": "Once we have set up our API authentication and made a few requests, it becomes much easier to understand how to interact with the API." }, { "code": null, "e": 5341, "s": 5180, "text": "The Reddit API documentation is simple, which makes it very easy to understand — I would definitely recommend scrolling through to see what can be done with it." }, { "code": null, "e": 5570, "s": 5341, "text": "An alternative is to use the Python PRAW library — a purpose-built library for interacting with the Reddit API. If you’re not too comfortable with requests or would simply appreciate the added layer of abstraction, check it out!" }, { "code": null, "e": 5756, "s": 5570, "text": "That is all for this introduction to using the Reddit API in Python! I hope it has been useful — if you have any questions or feedback, let me know via Twitter or in the comments below." }, { "code": null, "e": 5776, "s": 5756, "text": "Thanks for reading!" }, { "code": null, "e": 5792, "s": 5776, "text": "Reddit API Docs" } ]
LCASE() or LOWER() Functions in MySQL - GeeksforGeeks
03 Sep, 2020 1. LCASE() :The LCASE() function used to convert a text to lower-case. This function is a similar to the LOWER() function. Syntax : SELECT LCASE(text) Example : SELECT LCASE("Reading on GEEKSFORGEEKS is FUN") AS LowerText; Output – 2. LOWER() :Syntax : SELECT LOWER(text) Example : SELECT LOWER("Studying on GeeksForGeeks is FUN") AS LowerText; Output – DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database SQL | Views CTE in SQL Difference between DELETE, DROP and TRUNCATE How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DDL and DML in DBMS SQL Interview Questions What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
[ { "code": null, "e": 23609, "s": 23581, "text": "\n03 Sep, 2020" }, { "code": null, "e": 23732, "s": 23609, "text": "1. LCASE() :The LCASE() function used to convert a text to lower-case. This function is a similar to the LOWER() function." }, { "code": null, "e": 23741, "s": 23732, "text": "Syntax :" }, { "code": null, "e": 23760, "s": 23741, "text": "SELECT LCASE(text)" }, { "code": null, "e": 23770, "s": 23760, "text": "Example :" }, { "code": null, "e": 23833, "s": 23770, "text": "SELECT LCASE(\"Reading on GEEKSFORGEEKS is FUN\") AS LowerText; " }, { "code": null, "e": 23842, "s": 23833, "text": "Output –" }, { "code": null, "e": 23863, "s": 23842, "text": "2. LOWER() :Syntax :" }, { "code": null, "e": 23882, "s": 23863, "text": "SELECT LOWER(text)" }, { "code": null, "e": 23892, "s": 23882, "text": "Example :" }, { "code": null, "e": 23956, "s": 23892, "text": "SELECT LOWER(\"Studying on GeeksForGeeks is FUN\") AS LowerText; " }, { "code": null, "e": 23965, "s": 23956, "text": "Output –" }, { "code": null, "e": 23974, "s": 23965, "text": "DBMS-SQL" }, { "code": null, "e": 23980, "s": 23974, "text": "mysql" }, { "code": null, "e": 23984, "s": 23980, "text": "SQL" }, { "code": null, "e": 23988, "s": 23984, "text": "SQL" }, { "code": null, "e": 24086, "s": 23988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24095, "s": 24086, "text": "Comments" }, { "code": null, "e": 24108, "s": 24095, "text": "Old Comments" }, { "code": null, "e": 24139, "s": 24108, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 24151, "s": 24139, "text": "SQL | Views" }, { "code": null, "e": 24162, "s": 24151, "text": "CTE in SQL" }, { "code": null, "e": 24207, "s": 24162, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 24273, "s": 24207, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 24288, "s": 24273, "text": "SQL | GROUP BY" }, { "code": null, "e": 24327, "s": 24288, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 24351, "s": 24327, "text": "SQL Interview Questions" }, { "code": null, "e": 24383, "s": 24351, "text": "What is Temporary Table in SQL?" } ]
How to display message from a stored procedure?
To display message from stored procedure on the basis of conditions, let us use IF-ELSE condition − mysql> DELIMITER // mysql> CREATE PROCEDURE showMessage(value int,Name varchar(20)) BEGIN IF(value > 100) then SELECT CONCAT("HELLO"," ",Name); ELSE SELECT CONCAT("BYE"," ",Name); END IF; END // Query OK, 0 rows affected (0.18 sec) mysql> DELIMITER ; Case 1 − Call the stored procedure using CALL command, when value is more than 100 − call showMessage(200,'John'); This will produce the following output − +--------------------------+ | CONCAT("HELLO"," ",Name) | +--------------------------+ | HELLO John | +--------------------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected, 1 warning (0.02 sec) Case 2 − When the value is less than 100, a difference message will be visible since ELSE condition will execute − mysql> call showMessage(10,'John'); This will produce the following output − +------------------------+ | CONCAT("BYE"," ",Name) | +------------------------+ | BYE John | +------------------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
[ { "code": null, "e": 1162, "s": 1062, "text": "To display message from stored procedure on the basis of conditions, let us use IF-ELSE condition −" }, { "code": null, "e": 1464, "s": 1162, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE showMessage(value int,Name varchar(20))\n BEGIN\n IF(value > 100) then\n SELECT CONCAT(\"HELLO\",\" \",Name);\n ELSE\n SELECT CONCAT(\"BYE\",\" \",Name);\n END IF;\n END\n //\nQuery OK, 0 rows affected (0.18 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1549, "s": 1464, "text": "Case 1 − Call the stored procedure using CALL command, when value is more than 100 −" }, { "code": null, "e": 1579, "s": 1549, "text": "call showMessage(200,'John');" }, { "code": null, "e": 1620, "s": 1579, "text": "This will produce the following output −" }, { "code": null, "e": 1837, "s": 1620, "text": "+--------------------------+\n| CONCAT(\"HELLO\",\" \",Name) |\n+--------------------------+\n| HELLO John |\n+--------------------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected, 1 warning (0.02 sec)" }, { "code": null, "e": 1952, "s": 1837, "text": "Case 2 − When the value is less than 100, a difference message will be visible since ELSE condition will execute −" }, { "code": null, "e": 1988, "s": 1952, "text": "mysql> call showMessage(10,'John');" }, { "code": null, "e": 2029, "s": 1988, "text": "This will produce the following output −" }, { "code": null, "e": 2225, "s": 2029, "text": "+------------------------+\n| CONCAT(\"BYE\",\" \",Name) |\n+------------------------+\n| BYE John |\n+------------------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.01 sec)" } ]
C program to find Fibonacci series for a given number
Fibonacci Series is a sequence of numbers obtained by adding the two previous numbers. Fibonacci series starts from two numbers f0 & f1. The initial values of fo & f1 can be taken 0, 1 or 1, 1 Fibonacci series satisfies the following conditions − fn = fn-1 + fn-2 Refer to the algorithm for the Fibonacci series. START Step 1: Read integer variable a,b,c at run time Step 2: Initialize a=0 and b=0 Step 3: Compute c=a+b Step 4: Print c Step 5: Set a=b, b=c Step 6: Repeat 3 to 5 for n times STOP Following is the C program for the Fibonacci series using While Loop − Live Demo #include <stdio.h> int main(){ int number, i = 0, Next, first = 0, second = 1; printf("\n Please Enter the Range Number: "); scanf("%d",&number); while(i < number){ if(i <= 1){ Next = i; } else{ Next = first + second; first = second; second = Next; } printf("%d \t", Next); i++; } return 0; } When the above program is executed, it produces the following result − Please Enter the Range Number: 6 0 1 1 2 3 5
[ { "code": null, "e": 1149, "s": 1062, "text": "Fibonacci Series is a sequence of numbers obtained by adding the two previous numbers." }, { "code": null, "e": 1199, "s": 1149, "text": "Fibonacci series starts from two numbers f0 & f1." }, { "code": null, "e": 1309, "s": 1199, "text": "The initial values of fo & f1 can be taken 0, 1 or 1, 1\nFibonacci series satisfies the following conditions −" }, { "code": null, "e": 1326, "s": 1309, "text": "fn = fn-1 + fn-2" }, { "code": null, "e": 1375, "s": 1326, "text": "Refer to the algorithm for the Fibonacci series." }, { "code": null, "e": 1558, "s": 1375, "text": "START\nStep 1: Read integer variable a,b,c at run time\nStep 2: Initialize a=0 and b=0\nStep 3: Compute c=a+b\nStep 4: Print c\nStep 5: Set a=b, b=c\nStep 6: Repeat 3 to 5 for n times\nSTOP" }, { "code": null, "e": 1629, "s": 1558, "text": "Following is the C program for the Fibonacci series using While Loop −" }, { "code": null, "e": 1640, "s": 1629, "text": " Live Demo" }, { "code": null, "e": 2023, "s": 1640, "text": "#include <stdio.h>\nint main(){\n int number, i = 0, Next, first = 0, second = 1;\n printf(\"\\n Please Enter the Range Number: \");\n scanf(\"%d\",&number);\n while(i < number){\n if(i <= 1){\n Next = i;\n }\n else{\n Next = first + second;\n first = second;\n second = Next;\n }\n printf(\"%d \\t\", Next);\n i++;\n }\n return 0;\n}" }, { "code": null, "e": 2094, "s": 2023, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2139, "s": 2094, "text": "Please Enter the Range Number: 6\n0 1 1 2 3 5" } ]
JavaScript - Date getDate() Method
Javascript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31. Its syntax is as follows − Date.getDate() Returns today's date and time. <html> <head> <title>JavaScript getDate Method</title> </head> <body> <script type = "text/javascript"> var dt = new Date("December 25, 1995 23:15:00"); document.write("getDate() : " + dt.getDate() ); </script> </body> </html> 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2640, "s": 2466, "text": "Javascript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31." }, { "code": null, "e": 2667, "s": 2640, "text": "Its syntax is as follows −" }, { "code": null, "e": 2683, "s": 2667, "text": "Date.getDate()\n" }, { "code": null, "e": 2714, "s": 2683, "text": "Returns today's date and time." }, { "code": null, "e": 3003, "s": 2714, "text": "<html>\n <head>\n <title>JavaScript getDate Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date(\"December 25, 1995 23:15:00\");\n document.write(\"getDate() : \" + dt.getDate() ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3038, "s": 3003, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3052, "s": 3038, "text": " Anadi Sharma" }, { "code": null, "e": 3086, "s": 3052, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3100, "s": 3086, "text": " Lets Kode It" }, { "code": null, "e": 3135, "s": 3100, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3152, "s": 3135, "text": " Frahaan Hussain" }, { "code": null, "e": 3187, "s": 3152, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3204, "s": 3187, "text": " Frahaan Hussain" }, { "code": null, "e": 3237, "s": 3204, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3265, "s": 3237, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3299, "s": 3265, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3327, "s": 3299, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3334, "s": 3327, "text": " Print" }, { "code": null, "e": 3345, "s": 3334, "text": " Add Notes" } ]
How to insert new row at a certain index in a table in jQuery ? - GeeksforGeeks
28 Jun, 2019 Given an HTML document containing a table. The task is to insert a new row in that table at a certain index using JQuery. Approach: Store the table column value <td> element into the variable. Then use eq() and after() method to insert the row in a table. Example 1: In this example, the row is inserted at index 1 (hardcoded). <!DOCTYPE HTML> <html> <head> <title> Insert new row at a certain index in a table using jQuery </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = "color:green;" > GeeksForGeeks </h1> <strong> Click on the button to insert a new row in the table </strong> <br><br> <table> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = "row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> </table> <br> <button onclick = "Geeks()"> Click here </button> <!-- Script to insert new row in a table --> <script> function Geeks() { var html = "<td>Geek_2</td><td>GeeksForGeeks</td><th>Geek_id_2</th>"; $('table > tbody > tr').eq(1).after(html); } </script> </center> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, the row is inserted at index provided by the user. <!DOCTYPE HTML> <html> <head> <title> Insert new row at a certain index in a table using jQuery </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = "color:green;" > GeeksForGeeks </h1> <strong> Click on the button to insert a new row in the table </strong> <br><br> <table> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = "row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> </table> <br> <button onclick = "Geeks()"> Click here </button> <!-- Script to insert new row in a table --> <script> function Geeks() { var i = 2; var html = "<td>Geek_2</td><td>GeeksForGeeks</td><th>Geek_id_2</th>"; $('table > tbody > tr').eq(i - 1).after(html); } </script> </center> </body> </html> Output: Before clicking on the button: After clicking on the button: jQuery-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to Use the JavaScript Fetch API to Get Data? Difference Between PUT and PATCH Request Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24369, "s": 24341, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24491, "s": 24369, "text": "Given an HTML document containing a table. The task is to insert a new row in that table at a certain index using JQuery." }, { "code": null, "e": 24501, "s": 24491, "text": "Approach:" }, { "code": null, "e": 24562, "s": 24501, "text": "Store the table column value <td> element into the variable." }, { "code": null, "e": 24625, "s": 24562, "text": "Then use eq() and after() method to insert the row in a table." }, { "code": null, "e": 24697, "s": 24625, "text": "Example 1: In this example, the row is inserted at index 1 (hardcoded)." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Insert new row at a certain index in a table using jQuery </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <strong> Click on the button to insert a new row in the table </strong> <br><br> <table> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = \"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> </table> <br> <button onclick = \"Geeks()\"> Click here </button> <!-- Script to insert new row in a table --> <script> function Geeks() { var html = \"<td>Geek_2</td><td>GeeksForGeeks</td><th>Geek_id_2</th>\"; $('table > tbody > tr').eq(1).after(html); } </script> </center> </body> </html> ", "e": 26639, "s": 24697, "text": null }, { "code": null, "e": 26647, "s": 26639, "text": "Output:" }, { "code": null, "e": 26678, "s": 26647, "text": "Before clicking on the button:" }, { "code": null, "e": 26708, "s": 26678, "text": "After clicking on the button:" }, { "code": null, "e": 26787, "s": 26708, "text": "Example 2: In this example, the row is inserted at index provided by the user." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Insert new row at a certain index in a table using jQuery </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <strong> Click on the button to insert a new row in the table </strong> <br><br> <table> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = \"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_3</td> <td>GeeksForGeeks</td> <th>Geek_id_3</th> </tr> </table> <br> <button onclick = \"Geeks()\"> Click here </button> <!-- Script to insert new row in a table --> <script> function Geeks() { var i = 2; var html = \"<td>Geek_2</td><td>GeeksForGeeks</td><th>Geek_id_2</th>\"; $('table > tbody > tr').eq(i - 1).after(html); } </script> </center> </body> </html> ", "e": 28759, "s": 26787, "text": null }, { "code": null, "e": 28767, "s": 28759, "text": "Output:" }, { "code": null, "e": 28798, "s": 28767, "text": "Before clicking on the button:" }, { "code": null, "e": 28828, "s": 28798, "text": "After clicking on the button:" }, { "code": null, "e": 28840, "s": 28828, "text": "jQuery-Misc" }, { "code": null, "e": 28851, "s": 28840, "text": "JavaScript" }, { "code": null, "e": 28868, "s": 28851, "text": "Web Technologies" }, { "code": null, "e": 28895, "s": 28868, "text": "Web technologies Questions" }, { "code": null, "e": 28993, "s": 28895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29002, "s": 28993, "text": "Comments" }, { "code": null, "e": 29015, "s": 29002, "text": "Old Comments" }, { "code": null, "e": 29076, "s": 29015, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29121, "s": 29076, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29193, "s": 29121, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29242, "s": 29193, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 29283, "s": 29242, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29339, "s": 29283, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29372, "s": 29339, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29434, "s": 29372, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29477, "s": 29434, "text": "How to fetch data from an API in ReactJS ?" } ]
Sum of the mirror image nodes of a complete binary tree in an inorder way - GeeksforGeeks
05 Aug, 2021 Given a complete binary tree, the task is to find the sum of mirror image nodes in an inorder way i.e. find the inorder traversal of the left sub-tree and for every node traversed, add the value of its mirror node to the current node’s value. Examples: Input: Output: 20 51 19 10 Inorder traversal of the left sub-tree of the given tree is 4 23 11 5. Adding the mirror nodes, 4 + 16 = 20 23 + 28 = 51 11 + 8 = 19 5 + 5 = 10 Approach: We will use 2 pointers to maintain 2 nodes which are the mirror image of each other. So let’s take root1 and root2 are 2 mirror image nodes. Now left child of root1 and right child of root2 will be the mirror image of each other. We will pass these two nodes (root1->left and root2->right) for next recursive call. Since we have to traverse in an inorder manner so once left sub-tree is traversed then we print the current root data and then we traverse the right sub-tree. Similarly for the right sub-tree so right child of root1 and left child of root2 will be the mirror image of each other. We will pass these two nodes (root1->right and root2->left) for next recursive call. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std;typedef struct node { // struct to store data and links to // its left and right child int data; struct node* l; struct node* r; node(int d) { // Initialize data for the current node // with the passed value as d data = d; // Initialize left child to NULL l = NULL; // Initialize right child to NULL r = NULL; }} Node; // Function to print the required inorder traversalvoid printInorder(Node* rootL, Node* rootR){ // We are using 2 pointers for the nodes // which are mirror image of each other // If both child are NULL return if (rootL->l == NULL && rootR->r == NULL) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL->l, rootR->r); cout << rootL->l->data + rootR->r->data << endl; printInorder(rootL->r, rootR->l);} // Driver codeint main(){ Node* root = new Node(5); root->l = new Node(23); root->r = new Node(28); root->l->l = new Node(4); root->l->r = new Node(11); root->r->l = new Node(8); root->r->r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root) cout << root->data * 2 << endl; return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static class Node { // struct to store data and links to // its left and right child int data; Node l; Node r; Node(int d) { // Initialize data for the current Node // with the passed value as d data = d; // Initialize left child to null l = null; // Initialize right child to null r = null; } } // Function to print the required inorder traversal static void printInorder(Node rootL, Node rootR) { // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); System.out.println(rootL.l.data + rootR.r.data ); printInorder(rootL.r, rootR.l); } // Driver code public static void main(String args[]) { Node root = new Node(5); root.l = new Node(23); root.r = new Node(28); root.l.l = new Node(4); root.l.r = new Node(11); root.r.l = new Node(8); root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root != null) System.out.println(root.data * 2 ); }} // This code is contributed by Arnab Kundu # Python3 implementation of the approach class Node: def __init__(self, d): self.data = d self.l = None self.r = None # Function to print the required inorder traversaldef printInorder(rootL, rootR): # We are using 2 pointers for the nodes # which are mirror image of each other # If both child are None return if rootL.l == None and rootR.r == None: return # Since inorder traversal is required # First left, then root and then right printInorder(rootL.l, rootR.r) print(rootL.l.data + rootR.r.data) printInorder(rootL.r, rootR.l) # Driver codeif __name__ == "__main__": root = Node(5) root.l = Node(23) root.r = Node(28) root.l.l = Node(4) root.l.r = Node(11) root.r.l = Node(8) root.r.r = Node(16) printInorder(root, root) # Since root is mirror image of itself if root: print(root.data * 2) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System; class GFG{ public class Node { // struct to store data and links to // its left and right child public int data; public Node l; public Node r; public Node(int d) { // Initialize data for the current Node // with the passed value as d data = d; // Initialize left child to null l = null; // Initialize right child to null r = null; } } // Function to print the required inorder traversal static void printInorder(Node rootL, Node rootR) { // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); Console.WriteLine(rootL.l.data + rootR.r.data ); printInorder(rootL.r, rootR.l); } // Driver code public static void Main(String []args) { Node root = new Node(5); root.l = new Node(23); root.r = new Node(28); root.l.l = new Node(4); root.l.r = new Node(11); root.r.l = new Node(8); root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root != null) Console.WriteLine(root.data * 2 ); }} // This code is contributed by Arnab Kundu <script> // Javascript implementation of the approachclass Node{ constructor(d) { this.l = null; this.r = null; this.data = d; }} // Function to print the required inorder traversalfunction printInorder(rootL, rootR){ // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); document.write(rootL.l.data + rootR.r.data + "</br>"); printInorder(rootL.r, rootR.l);} // Driver codelet root = new Node(5);root.l = new Node(23);root.r = new Node(28);root.l.l = new Node(4);root.l.r = new Node(11);root.r.l = new Node(8);root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itselfif (root != null) document.write(root.data * 2 ); // This code is contributed by suresh07 </script> 20 51 19 10 Time Complexity: O(N)Auxiliary Space: O(N) rituraj_jain ManasChhabra2 andrew1234 suresh07 pankajsharmagfg Binary Tree Inorder Traversal Data Structures Recursion Tree Data Structures Recursion 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 Program to implement Singly Linked List in C++ using class TCS NQT Coding Sheet Hash Functions and list/types of Hash functions Building an undirected graph and finding shortest path using Dictionaries in Python Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24661, "s": 24633, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24904, "s": 24661, "text": "Given a complete binary tree, the task is to find the sum of mirror image nodes in an inorder way i.e. find the inorder traversal of the left sub-tree and for every node traversed, add the value of its mirror node to the current node’s value." }, { "code": null, "e": 24915, "s": 24904, "text": "Examples: " }, { "code": null, "e": 24924, "s": 24915, "text": "Input: " }, { "code": null, "e": 25090, "s": 24924, "text": "Output: 20 51 19 10 Inorder traversal of the left sub-tree of the given tree is 4 23 11 5. Adding the mirror nodes, 4 + 16 = 20 23 + 28 = 51 11 + 8 = 19 5 + 5 = 10 " }, { "code": null, "e": 25780, "s": 25090, "text": "Approach: We will use 2 pointers to maintain 2 nodes which are the mirror image of each other. So let’s take root1 and root2 are 2 mirror image nodes. Now left child of root1 and right child of root2 will be the mirror image of each other. We will pass these two nodes (root1->left and root2->right) for next recursive call. Since we have to traverse in an inorder manner so once left sub-tree is traversed then we print the current root data and then we traverse the right sub-tree. Similarly for the right sub-tree so right child of root1 and left child of root2 will be the mirror image of each other. We will pass these two nodes (root1->right and root2->left) for next recursive call." }, { "code": null, "e": 25831, "s": 25780, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 25835, "s": 25831, "text": "C++" }, { "code": null, "e": 25840, "s": 25835, "text": "Java" }, { "code": null, "e": 25848, "s": 25840, "text": "Python3" }, { "code": null, "e": 25851, "s": 25848, "text": "C#" }, { "code": null, "e": 25862, "s": 25851, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std;typedef struct node { // struct to store data and links to // its left and right child int data; struct node* l; struct node* r; node(int d) { // Initialize data for the current node // with the passed value as d data = d; // Initialize left child to NULL l = NULL; // Initialize right child to NULL r = NULL; }} Node; // Function to print the required inorder traversalvoid printInorder(Node* rootL, Node* rootR){ // We are using 2 pointers for the nodes // which are mirror image of each other // If both child are NULL return if (rootL->l == NULL && rootR->r == NULL) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL->l, rootR->r); cout << rootL->l->data + rootR->r->data << endl; printInorder(rootL->r, rootR->l);} // Driver codeint main(){ Node* root = new Node(5); root->l = new Node(23); root->r = new Node(28); root->l->l = new Node(4); root->l->r = new Node(11); root->r->l = new Node(8); root->r->r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root) cout << root->data * 2 << endl; return 0;}", "e": 27194, "s": 25862, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static class Node { // struct to store data and links to // its left and right child int data; Node l; Node r; Node(int d) { // Initialize data for the current Node // with the passed value as d data = d; // Initialize left child to null l = null; // Initialize right child to null r = null; } } // Function to print the required inorder traversal static void printInorder(Node rootL, Node rootR) { // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); System.out.println(rootL.l.data + rootR.r.data ); printInorder(rootL.r, rootR.l); } // Driver code public static void main(String args[]) { Node root = new Node(5); root.l = new Node(23); root.r = new Node(28); root.l.l = new Node(4); root.l.r = new Node(11); root.r.l = new Node(8); root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root != null) System.out.println(root.data * 2 ); }} // This code is contributed by Arnab Kundu", "e": 28769, "s": 27194, "text": null }, { "code": "# Python3 implementation of the approach class Node: def __init__(self, d): self.data = d self.l = None self.r = None # Function to print the required inorder traversaldef printInorder(rootL, rootR): # We are using 2 pointers for the nodes # which are mirror image of each other # If both child are None return if rootL.l == None and rootR.r == None: return # Since inorder traversal is required # First left, then root and then right printInorder(rootL.l, rootR.r) print(rootL.l.data + rootR.r.data) printInorder(rootL.r, rootR.l) # Driver codeif __name__ == \"__main__\": root = Node(5) root.l = Node(23) root.r = Node(28) root.l.l = Node(4) root.l.r = Node(11) root.r.l = Node(8) root.r.r = Node(16) printInorder(root, root) # Since root is mirror image of itself if root: print(root.data * 2) # This code is contributed by Rituraj Jain", "e": 29715, "s": 28769, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ public class Node { // struct to store data and links to // its left and right child public int data; public Node l; public Node r; public Node(int d) { // Initialize data for the current Node // with the passed value as d data = d; // Initialize left child to null l = null; // Initialize right child to null r = null; } } // Function to print the required inorder traversal static void printInorder(Node rootL, Node rootR) { // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); Console.WriteLine(rootL.l.data + rootR.r.data ); printInorder(rootL.r, rootR.l); } // Driver code public static void Main(String []args) { Node root = new Node(5); root.l = new Node(23); root.r = new Node(28); root.l.l = new Node(4); root.l.r = new Node(11); root.r.l = new Node(8); root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itself if (root != null) Console.WriteLine(root.data * 2 ); }} // This code is contributed by Arnab Kundu", "e": 31308, "s": 29715, "text": null }, { "code": "<script> // Javascript implementation of the approachclass Node{ constructor(d) { this.l = null; this.r = null; this.data = d; }} // Function to print the required inorder traversalfunction printInorder(rootL, rootR){ // We are using 2 pointers for the Nodes // which are mirror image of each other // If both child are null return if (rootL.l == null && rootR.r == null) return; // Since inorder traversal is required // First left, then root and then right printInorder(rootL.l, rootR.r); document.write(rootL.l.data + rootR.r.data + \"</br>\"); printInorder(rootL.r, rootR.l);} // Driver codelet root = new Node(5);root.l = new Node(23);root.r = new Node(28);root.l.l = new Node(4);root.l.r = new Node(11);root.r.l = new Node(8);root.r.r = new Node(16); printInorder(root, root); // Since root is mirror image of itselfif (root != null) document.write(root.data * 2 ); // This code is contributed by suresh07 </script>", "e": 32321, "s": 31308, "text": null }, { "code": null, "e": 32333, "s": 32321, "text": "20\n51\n19\n10" }, { "code": null, "e": 32379, "s": 32335, "text": "Time Complexity: O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 32392, "s": 32379, "text": "rituraj_jain" }, { "code": null, "e": 32406, "s": 32392, "text": "ManasChhabra2" }, { "code": null, "e": 32417, "s": 32406, "text": "andrew1234" }, { "code": null, "e": 32426, "s": 32417, "text": "suresh07" }, { "code": null, "e": 32442, "s": 32426, "text": "pankajsharmagfg" }, { "code": null, "e": 32454, "s": 32442, "text": "Binary Tree" }, { "code": null, "e": 32472, "s": 32454, "text": "Inorder Traversal" }, { "code": null, "e": 32488, "s": 32472, "text": "Data Structures" }, { "code": null, "e": 32498, "s": 32488, "text": "Recursion" }, { "code": null, "e": 32503, "s": 32498, "text": "Tree" }, { "code": null, "e": 32519, "s": 32503, "text": "Data Structures" }, { "code": null, "e": 32529, "s": 32519, "text": "Recursion" }, { "code": null, "e": 32534, "s": 32529, "text": "Tree" }, { "code": null, "e": 32632, "s": 32534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32641, "s": 32632, "text": "Comments" }, { "code": null, "e": 32654, "s": 32641, "text": "Old Comments" }, { "code": null, "e": 32690, "s": 32654, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 32749, "s": 32690, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 32770, "s": 32749, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 32818, "s": 32770, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 32902, "s": 32818, "text": "Building an undirected graph and finding shortest path using Dictionaries in Python" }, { "code": null, "e": 32962, "s": 32902, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33047, "s": 32962, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33057, "s": 33047, "text": "Recursion" }, { "code": null, "e": 33084, "s": 33057, "text": "Program for Tower of Hanoi" } ]
Maximum subarray size, such that all subarrays of that size have sum less than k - GeeksforGeeks
07 Sep, 2021 Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than or equals to k. Examples : Input : arr[] = {1, 2, 3, 4} and k = 8. Output : 2 Sum of subarrays of size 1: 1, 2, 3, 4. Sum of subarrays of size 2: 3, 5, 7. Sum of subarrays of size 3: 6, 9. Sum of subarrays of size 4: 10. So, maximum subarray size such that all subarrays of that size have the sum of elements less than 8 is 2. Input : arr[] = {1, 2, 10, 4} and k = 8. Output : -1 There is an array element with value greater than k, so subarray sum cannot be less than k. Input : arr[] = {1, 2, 10, 4} and K = 14 Output : 2 Naive Approach: Firstly, the required subarray size must lie between 1 to n. Now, since all the array elements are positive integers, we can say that the prefix sum of any subarray shall be strictly increasing. Thus, we can say that if arr[i] + arr[i + 1] + ..... + arr[j - 1] + arr[j] <= K then arr[i] + arr[i + 1] + ..... + arr[j - 1] <= K, as arr[j] is a positive integer. Perform Binary Search over the range 1 to n and find the highest subarray size such that all the subarrays of that size have the sum of elements less than or equals to k. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.#include<bits/stdc++.h>using namespace std; // Search for the maximum length of// required subarray.int bsearch(int prefixsum[], int n, int k){ // Initialize result int ans = -1; // Do Binary Search for largest // subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays after mid int i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans;} // Return the maximum subarray size,// such that all subarray of that size// have sum less than K.int maxSize(int arr[], int n, int k){ // Initialize prefix sum array as 0. int prefixsum[n + 1]; memset(prefixsum, 0, sizeof(prefixsum)); // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k);} // Driver codeint main(){ int arr[] = {1, 2, 10, 4}; int n = sizeof(arr) / sizeof(arr[0]); int k = 14; cout << maxSize(arr, n, k) << endl; return 0;} // Java program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.import java.util.Arrays; class GFG{ // Search for the maximum length // of required subarray. static int bsearch(int prefixsum[], int n, int k) { // Initialize result int ans = -1; // Do Binary Search for largest // subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays after mid int i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. static int maxSize(int arr[], int n, int k) { // Initialize prefix sum array as 0. int prefixsum[] = new int[n + 1]; Arrays.fill(prefixsum, 0); // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code public static void main(String arg[]) { int arr[] = { 1, 2, 10, 4 }; int n = arr.length; int k = 14; System.out.println(maxSize(arr, n, k)); }} // This code is contributed by Anant Agarwal. # Python3 program to find maximum# subarray size, such that all# subarrays of that size have# sum less than K. # Search for the maximum length of# required subarray.def bsearch(prefixsum, n, k): # Initialize result # Do Binary Search for largest # subarray size ans, left, right = -1, 1, n while (left <= right): # Check for all subarrays after mid mid = (left + right)//2 for i in range(mid, n + 1): # Checking if all the subarray of # a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k): i = i - 1 break i = i + 1 if (i == n + 1): left = mid + 1 ans = mid # We found a subarray of size mid with sum # greater than k else: right = mid - 1 return ans; # Return the maximum subarray size, such# that all subarray of that size have# sum less than K.def maxSize(arr, n, k): prefixsum = [0 for x in range(n + 1)] # Finding prefix sum of the array. for i in range(n): prefixsum[i + 1] = prefixsum[i] + arr[i] return bsearch(prefixsum, n, k); # Driver Codearr = [ 1, 2, 10, 4 ]n = len(arr)k = 14print (maxSize(arr, n, k)) # This code is contributed by Afzal // C# program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.using System; class GFG { // Search for the maximum length // of required subarray. static int bsearch(int []prefixsum, int n, int k) { // Initialize result int ans = -1; // Do Binary Search for // largest subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays // after mid int i; for (i = mid; i <= n; i++) { // Checking if all the // subarrays of a size is // less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. static int maxSize(int []arr, int n, int k) { // Initialize prefix sum array as 0. int []prefixsum = new int[n + 1]; for(int i=0;i<n+1;i++) prefixsum[i]=0; // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code public static void Main() { int []arr = { 1, 2, 10, 4 }; int n = arr.Length; int k = 14; Console.Write(maxSize(arr, n, k)); }} // This code is contributed by nitin mittal. <?php// PHP program to find maximum subarray// size, such that all subarrays of that// size have sum less than K. // Search for the maximum length of// required subarray.function bsearch(&$prefixsum, $n, $k){ // Initialize result $ans = -1; // Do Binary Search for largest // subarray size $left = 1; $right = $n; while ($left <= $right) { $mid = intval(($left + $right) / 2); // Check for all subarrays after mid for ($i = $mid; $i <= $n; $i++) { // Checking if all the subarrays // of a size less than k. if ($prefixsum[$i] - $prefixsum[$i - $mid] > $k) break; } // All subarrays of size mid have // sum less than or equal to k if ($i == $n + 1) { $left = $mid + 1; $ans = $mid; } // We found a subarray of size mid // with sum greater than k else $right = $mid - 1; } return $ans;} // Return the maximum subarray size,// such that all subarray of that size// have sum less than K.function maxSize(&$arr, $n, $k){ // Initialize prefix sum array as 0. $prefixsum = array_fill(0, $n + 1, NULL); // Finding prefix sum of the array. for ($i = 0; $i < $n; $i++) $prefixsum[$i + 1] = $prefixsum[$i] + $arr[$i]; return bsearch($prefixsum, $n, $k);} // Driver code$arr = array(1, 2, 10, 4);$n = sizeof($arr);$k = 14;echo maxSize($arr, $n, $k) . "\n"; // This code is contributed// by ChitraNayal?> <script> // javascript program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K. // Search for the maximum length // of required subarray. function bsearch(prefixsum , n , k) { // Initialize result var ans = -1; // Do Binary Search for largest // subarray size var left = 1, right = n; while (left <= right) { var mid = parseInt((left + right) / 2); // Check for all subarrays after mid var i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. function maxSize(arr , n , k) { // Initialize prefix sum array as 0. var prefixsum = Array(n + 1).fill(0); // Finding prefix sum of the array. for (i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code var arr = [ 1, 2, 10, 4 ]; var n = arr.length; var k = 14; document.write(maxSize(arr, n, k)); // This code contributed by Rajput-Ji </script> 2 Time Complexity: O(n log n) Efficient Approach: This method uses the Sliding Window Technique to solve the given problem. The approach is to find the minimum subarray size whose sum is greater than integer k. Increase the window size from the end up to which the sum of that window is greater than k. Now, store that subarray size if it is smaller than the already stored subarray size (in variable ans). Now, decrement the subarray size from the beginning. The variable ans will store the minimum subarray size whose sum is greater than k. At last, (ans-1) is the actual answer. Then, that subarray size – 1 is the maximum subarray size, such that all subarray of that size will have sum less than or equal to k. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// largest size subarrayvoid func(vector<int> arr, int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for (int end = 0; end < n; end++) { // Sliding window from left sum += arr[end]; while (sum > k) { // Sliding window from right sum -= arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer cout << ans;} // Driver codeint main(){ vector<int> arr{ 1, 2, 3, 4 }; int k = 8; int n = arr.size(); // Function call func(arr, k, n); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find the// largest size subarraypublic static void func(int arr[], int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for(int end = 0; end < n; end++) { // Sliding window from left sum += (int)arr[end]; while (sum > k) { // Sliding window from right sum -= (int)arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer System.out.println(ans);} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 3, 4 }; int k = 8; int n = arr.length; // Function call func(arr, k, n);}} // This code is contributed by rag2127 # Python3 program for the above approach # Function to find the# largest size subarraydef func(arr, k, n): # Variable declaration ans = n Sum = 0 start = 0 # Loop till N for end in range(n): # Sliding window from left Sum += arr[end] while (Sum > k): # Sliding window from right Sum -= arr[start] start += 1 # Storing sub-array size - 1 # for which sum was greater than k ans = min(ans, end - start + 1) # Sum will be 0 if start>end # because all elements are positive # start>end only when arr[end]>k i.e, # there is an array element with # value greater than k, so sub-array # sum cannot be less than k. if (Sum == 0): break if (Sum == 0): ans = -1 break # Print the answer print(ans) # Driver codearr = [ 1, 2, 3, 4 ]k = 8n = len(arr) # Function callfunc(arr, k, n) # This code is contributed by avanitrachhadiya2155 // C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find the// largest size subarraystatic void func(ArrayList arr, int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for(int end = 0; end < n; end++) { // Sliding window from left sum += (int)arr[end]; while (sum > k) { // Sliding window from right sum -= (int)arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.Min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer Console.Write(ans);} // Driver codepublic static void Main(string[] args){ ArrayList arr = new ArrayList(){ 1, 2, 3, 4 }; int k = 8; int n = arr.Count; // Function call func(arr, k, n);}} // This code is contributed by rutvik_56 <script>// Javascript program for the above approach // Function to find the// largest size subarrayfunction func(arr, k, n){ // Variable declaration let ans = n; let sum = 0; let start = 0; // Loop till N for (let end = 0; end < n; end++) { // Sliding window from left sum += arr[end]; while (sum > k) { // Sliding window from right sum -= arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer document.write(ans);} // Driver code let arr = [ 1, 2, 3, 4 ]; let k = 8; let n = arr.length; // Function call func(arr, k, n); </script> 2 Time Complexity: O(N) Guibao Wang nitin mittal ukasp avinashraghuthu ishanagarwal5 rutvik_56 avanitrachhadiya2155 rag2127 Rajput-Ji subhammahato348 kk773572498 Binary Search prefix-sum subarray subarray-sum Arrays prefix-sum Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create) Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number
[ { "code": null, "e": 26701, "s": 26673, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26899, "s": 26701, "text": "Given an array of n positive integers and a positive integer k, the task is to find the maximum subarray size such that all subarrays of that size have the sum of elements less than or equals to k." }, { "code": null, "e": 26911, "s": 26899, "text": "Examples : " }, { "code": null, "e": 27413, "s": 26911, "text": "Input : arr[] = {1, 2, 3, 4} and k = 8.\nOutput : 2\nSum of subarrays of size 1: 1, 2, 3, 4.\nSum of subarrays of size 2: 3, 5, 7.\nSum of subarrays of size 3: 6, 9.\nSum of subarrays of size 4: 10.\nSo, maximum subarray size such that all subarrays of that size have the sum of elements less than 8 is 2.\n\nInput : arr[] = {1, 2, 10, 4} and k = 8.\nOutput : -1\nThere is an array element with value greater than k, so subarray sum cannot be less than k.\n\nInput : arr[] = {1, 2, 10, 4} and K = 14\nOutput : 2" }, { "code": null, "e": 27647, "s": 27413, "text": "Naive Approach: Firstly, the required subarray size must lie between 1 to n. Now, since all the array elements are positive integers, we can say that the prefix sum of any subarray shall be strictly increasing. Thus, we can say that " }, { "code": null, "e": 27790, "s": 27647, "text": "if arr[i] + arr[i + 1] + ..... + arr[j - 1] + arr[j] <= K\nthen arr[i] + arr[i + 1] + ..... + arr[j - 1] <= K, as arr[j] is a positive integer." }, { "code": null, "e": 27961, "s": 27790, "text": "Perform Binary Search over the range 1 to n and find the highest subarray size such that all the subarrays of that size have the sum of elements less than or equals to k." }, { "code": null, "e": 28012, "s": 27961, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28016, "s": 28012, "text": "C++" }, { "code": null, "e": 28021, "s": 28016, "text": "Java" }, { "code": null, "e": 28029, "s": 28021, "text": "Python3" }, { "code": null, "e": 28032, "s": 28029, "text": "C#" }, { "code": null, "e": 28036, "s": 28032, "text": "PHP" }, { "code": null, "e": 28047, "s": 28036, "text": "Javascript" }, { "code": "// C++ program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.#include<bits/stdc++.h>using namespace std; // Search for the maximum length of// required subarray.int bsearch(int prefixsum[], int n, int k){ // Initialize result int ans = -1; // Do Binary Search for largest // subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays after mid int i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans;} // Return the maximum subarray size,// such that all subarray of that size// have sum less than K.int maxSize(int arr[], int n, int k){ // Initialize prefix sum array as 0. int prefixsum[n + 1]; memset(prefixsum, 0, sizeof(prefixsum)); // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k);} // Driver codeint main(){ int arr[] = {1, 2, 10, 4}; int n = sizeof(arr) / sizeof(arr[0]); int k = 14; cout << maxSize(arr, n, k) << endl; return 0;}", "e": 29692, "s": 28047, "text": null }, { "code": "// Java program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.import java.util.Arrays; class GFG{ // Search for the maximum length // of required subarray. static int bsearch(int prefixsum[], int n, int k) { // Initialize result int ans = -1; // Do Binary Search for largest // subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays after mid int i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. static int maxSize(int arr[], int n, int k) { // Initialize prefix sum array as 0. int prefixsum[] = new int[n + 1]; Arrays.fill(prefixsum, 0); // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code public static void main(String arg[]) { int arr[] = { 1, 2, 10, 4 }; int n = arr.length; int k = 14; System.out.println(maxSize(arr, n, k)); }} // This code is contributed by Anant Agarwal.", "e": 31629, "s": 29692, "text": null }, { "code": "# Python3 program to find maximum# subarray size, such that all# subarrays of that size have# sum less than K. # Search for the maximum length of# required subarray.def bsearch(prefixsum, n, k): # Initialize result # Do Binary Search for largest # subarray size ans, left, right = -1, 1, n while (left <= right): # Check for all subarrays after mid mid = (left + right)//2 for i in range(mid, n + 1): # Checking if all the subarray of # a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k): i = i - 1 break i = i + 1 if (i == n + 1): left = mid + 1 ans = mid # We found a subarray of size mid with sum # greater than k else: right = mid - 1 return ans; # Return the maximum subarray size, such# that all subarray of that size have# sum less than K.def maxSize(arr, n, k): prefixsum = [0 for x in range(n + 1)] # Finding prefix sum of the array. for i in range(n): prefixsum[i + 1] = prefixsum[i] + arr[i] return bsearch(prefixsum, n, k); # Driver Codearr = [ 1, 2, 10, 4 ]n = len(arr)k = 14print (maxSize(arr, n, k)) # This code is contributed by Afzal", "e": 32896, "s": 31629, "text": null }, { "code": "// C# program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K.using System; class GFG { // Search for the maximum length // of required subarray. static int bsearch(int []prefixsum, int n, int k) { // Initialize result int ans = -1; // Do Binary Search for // largest subarray size int left = 1, right = n; while (left <= right) { int mid = (left + right) / 2; // Check for all subarrays // after mid int i; for (i = mid; i <= n; i++) { // Checking if all the // subarrays of a size is // less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. static int maxSize(int []arr, int n, int k) { // Initialize prefix sum array as 0. int []prefixsum = new int[n + 1]; for(int i=0;i<n+1;i++) prefixsum[i]=0; // Finding prefix sum of the array. for (int i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code public static void Main() { int []arr = { 1, 2, 10, 4 }; int n = arr.Length; int k = 14; Console.Write(maxSize(arr, n, k)); }} // This code is contributed by nitin mittal.", "e": 34940, "s": 32896, "text": null }, { "code": "<?php// PHP program to find maximum subarray// size, such that all subarrays of that// size have sum less than K. // Search for the maximum length of// required subarray.function bsearch(&$prefixsum, $n, $k){ // Initialize result $ans = -1; // Do Binary Search for largest // subarray size $left = 1; $right = $n; while ($left <= $right) { $mid = intval(($left + $right) / 2); // Check for all subarrays after mid for ($i = $mid; $i <= $n; $i++) { // Checking if all the subarrays // of a size less than k. if ($prefixsum[$i] - $prefixsum[$i - $mid] > $k) break; } // All subarrays of size mid have // sum less than or equal to k if ($i == $n + 1) { $left = $mid + 1; $ans = $mid; } // We found a subarray of size mid // with sum greater than k else $right = $mid - 1; } return $ans;} // Return the maximum subarray size,// such that all subarray of that size// have sum less than K.function maxSize(&$arr, $n, $k){ // Initialize prefix sum array as 0. $prefixsum = array_fill(0, $n + 1, NULL); // Finding prefix sum of the array. for ($i = 0; $i < $n; $i++) $prefixsum[$i + 1] = $prefixsum[$i] + $arr[$i]; return bsearch($prefixsum, $n, $k);} // Driver code$arr = array(1, 2, 10, 4);$n = sizeof($arr);$k = 14;echo maxSize($arr, $n, $k) . \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 36522, "s": 34940, "text": null }, { "code": "<script> // javascript program to find maximum// subarray size, such that all// subarrays of that size have// sum less than K. // Search for the maximum length // of required subarray. function bsearch(prefixsum , n , k) { // Initialize result var ans = -1; // Do Binary Search for largest // subarray size var left = 1, right = n; while (left <= right) { var mid = parseInt((left + right) / 2); // Check for all subarrays after mid var i; for (i = mid; i <= n; i++) { // Checking if all the subarrays // of a size is less than k. if (prefixsum[i] - prefixsum[i - mid] > k) break; } // All subarrays of size mid have // sum less than or equal to k if (i == n + 1) { left = mid + 1; ans = mid; } // We found a subarray of size mid // with sum greater than k else right = mid - 1; } return ans; } // Return the maximum subarray size, such // that all subarray of that size have // sum less than K. function maxSize(arr , n , k) { // Initialize prefix sum array as 0. var prefixsum = Array(n + 1).fill(0); // Finding prefix sum of the array. for (i = 0; i < n; i++) prefixsum[i + 1] = prefixsum[i] + arr[i]; return bsearch(prefixsum, n, k); } // Driver code var arr = [ 1, 2, 10, 4 ]; var n = arr.length; var k = 14; document.write(maxSize(arr, n, k)); // This code contributed by Rajput-Ji </script>", "e": 38241, "s": 36522, "text": null }, { "code": null, "e": 38243, "s": 38241, "text": "2" }, { "code": null, "e": 38271, "s": 38243, "text": "Time Complexity: O(n log n)" }, { "code": null, "e": 38366, "s": 38271, "text": "Efficient Approach: This method uses the Sliding Window Technique to solve the given problem. " }, { "code": null, "e": 38453, "s": 38366, "text": "The approach is to find the minimum subarray size whose sum is greater than integer k." }, { "code": null, "e": 38545, "s": 38453, "text": "Increase the window size from the end up to which the sum of that window is greater than k." }, { "code": null, "e": 38649, "s": 38545, "text": "Now, store that subarray size if it is smaller than the already stored subarray size (in variable ans)." }, { "code": null, "e": 38785, "s": 38649, "text": "Now, decrement the subarray size from the beginning. The variable ans will store the minimum subarray size whose sum is greater than k." }, { "code": null, "e": 38958, "s": 38785, "text": "At last, (ans-1) is the actual answer. Then, that subarray size – 1 is the maximum subarray size, such that all subarray of that size will have sum less than or equal to k." }, { "code": null, "e": 39009, "s": 38958, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 39013, "s": 39009, "text": "C++" }, { "code": null, "e": 39018, "s": 39013, "text": "Java" }, { "code": null, "e": 39026, "s": 39018, "text": "Python3" }, { "code": null, "e": 39029, "s": 39026, "text": "C#" }, { "code": null, "e": 39040, "s": 39029, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// largest size subarrayvoid func(vector<int> arr, int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for (int end = 0; end < n; end++) { // Sliding window from left sum += arr[end]; while (sum > k) { // Sliding window from right sum -= arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer cout << ans;} // Driver codeint main(){ vector<int> arr{ 1, 2, 3, 4 }; int k = 8; int n = arr.size(); // Function call func(arr, k, n); return 0;}", "e": 40267, "s": 39040, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find the// largest size subarraypublic static void func(int arr[], int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for(int end = 0; end < n; end++) { // Sliding window from left sum += (int)arr[end]; while (sum > k) { // Sliding window from right sum -= (int)arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer System.out.println(ans);} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 3, 4 }; int k = 8; int n = arr.length; // Function call func(arr, k, n);}} // This code is contributed by rag2127", "e": 41653, "s": 40267, "text": null }, { "code": "# Python3 program for the above approach # Function to find the# largest size subarraydef func(arr, k, n): # Variable declaration ans = n Sum = 0 start = 0 # Loop till N for end in range(n): # Sliding window from left Sum += arr[end] while (Sum > k): # Sliding window from right Sum -= arr[start] start += 1 # Storing sub-array size - 1 # for which sum was greater than k ans = min(ans, end - start + 1) # Sum will be 0 if start>end # because all elements are positive # start>end only when arr[end]>k i.e, # there is an array element with # value greater than k, so sub-array # sum cannot be less than k. if (Sum == 0): break if (Sum == 0): ans = -1 break # Print the answer print(ans) # Driver codearr = [ 1, 2, 3, 4 ]k = 8n = len(arr) # Function callfunc(arr, k, n) # This code is contributed by avanitrachhadiya2155", "e": 42758, "s": 41653, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to find the// largest size subarraystatic void func(ArrayList arr, int k, int n){ // Variable declaration int ans = n; int sum = 0; int start = 0; // Loop till N for(int end = 0; end < n; end++) { // Sliding window from left sum += (int)arr[end]; while (sum > k) { // Sliding window from right sum -= (int)arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.Min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer Console.Write(ans);} // Driver codepublic static void Main(string[] args){ ArrayList arr = new ArrayList(){ 1, 2, 3, 4 }; int k = 8; int n = arr.Count; // Function call func(arr, k, n);}} // This code is contributed by rutvik_56", "e": 44149, "s": 42758, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the// largest size subarrayfunction func(arr, k, n){ // Variable declaration let ans = n; let sum = 0; let start = 0; // Loop till N for (let end = 0; end < n; end++) { // Sliding window from left sum += arr[end]; while (sum > k) { // Sliding window from right sum -= arr[start]; start++; // Storing sub-array size - 1 // for which sum was greater than k ans = Math.min(ans, end - start + 1); // Sum will be 0 if start>end // because all elements are positive // start>end only when arr[end]>k i.e, // there is an array element with // value greater than k, so sub-array // sum cannot be less than k. if (sum == 0) break; } if (sum == 0) { ans = -1; break; } } // Print the answer document.write(ans);} // Driver code let arr = [ 1, 2, 3, 4 ]; let k = 8; let n = arr.length; // Function call func(arr, k, n); </script>", "e": 45318, "s": 44149, "text": null }, { "code": null, "e": 45320, "s": 45318, "text": "2" }, { "code": null, "e": 45342, "s": 45320, "text": "Time Complexity: O(N)" }, { "code": null, "e": 45354, "s": 45342, "text": "Guibao Wang" }, { "code": null, "e": 45367, "s": 45354, "text": "nitin mittal" }, { "code": null, "e": 45373, "s": 45367, "text": "ukasp" }, { "code": null, "e": 45389, "s": 45373, "text": "avinashraghuthu" }, { "code": null, "e": 45403, "s": 45389, "text": "ishanagarwal5" }, { "code": null, "e": 45413, "s": 45403, "text": "rutvik_56" }, { "code": null, "e": 45434, "s": 45413, "text": "avanitrachhadiya2155" }, { "code": null, "e": 45442, "s": 45434, "text": "rag2127" }, { "code": null, "e": 45452, "s": 45442, "text": "Rajput-Ji" }, { "code": null, "e": 45468, "s": 45452, "text": "subhammahato348" }, { "code": null, "e": 45480, "s": 45468, "text": "kk773572498" }, { "code": null, "e": 45494, "s": 45480, "text": "Binary Search" }, { "code": null, "e": 45505, "s": 45494, "text": "prefix-sum" }, { "code": null, "e": 45514, "s": 45505, "text": "subarray" }, { "code": null, "e": 45527, "s": 45514, "text": "subarray-sum" }, { "code": null, "e": 45534, "s": 45527, "text": "Arrays" }, { "code": null, "e": 45545, "s": 45534, "text": "prefix-sum" }, { "code": null, "e": 45552, "s": 45545, "text": "Arrays" }, { "code": null, "e": 45566, "s": 45552, "text": "Binary Search" }, { "code": null, "e": 45664, "s": 45566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45687, "s": 45664, "text": "Introduction to Arrays" }, { "code": null, "e": 45719, "s": 45687, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 45733, "s": 45719, "text": "Linear Search" }, { "code": null, "e": 45754, "s": 45733, "text": "Linked List vs Array" }, { "code": null, "e": 45839, "s": 45754, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 45884, "s": 45839, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 45932, "s": 45884, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 45985, "s": 45932, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 46039, "s": 45985, "text": "Queue | Set 1 (Introduction and Array Implementation)" } ]
Executing functions with multiple arguments at a terminal in Python - GeeksforGeeks
02 Sep, 2020 Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line arguments with the help of sys module. The python sys module provides functions and variables that can be used to access different parts of the Python Runtime Environment. It allows access to system-specific parameters and functions. To use the sys module we need to import the sys module in our program before running any functions.There are mainly two functions in the sys module:sys.argv: gives the list of command-line arguments. For example, sys.argv[0] is the program name.len(sys.argv): gives the number of command-line arguments. Example 1 : This program demonstrates the use of sys.argv to fetch the command line arguments and len(sys.argv) gives the total number of command line arguments passed including the name of the python script. # importing the moduleimport sys # storing the argumentsprogram = sys.argv[0]arg1 = sys.argv[1]arg2 = sys.argv[2]arg3 = sys.argv[3] # displaying the program nameprint("Program name : " + program) # displaying the argumentsprint("arg1 : " + arg1)print("arg2 : " + arg2)print("arg3 : " + arg3)print("Number of arguments : ", len(sys.argv))print(sys.argv) Output : Example 2 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1, 2 and 3 are stored into the variables arg1, arg2 and arg3. The variables arg1, arg2 and arg3 are passed to the function defined. However, the command line arguments can be passed directly without storing its value in local variables. # importing the moduleimport sys # function definitiondef concat(s1, s2, s3): print(s1 + " " + s2 + " " + s3) # fetching the argumentsarg1 = sys.argv[1]arg2 = sys.argv[2]arg3 = sys.argv[3] # calling the functionconcat(arg1, arg2, arg3) Output : Example 3 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1 and 2 are stored into the variables arg1 and arg2. The variables a and b are passed to the function defined. Command line arguments are accepted as strings, hence in order to perform numerical operations it should be converted into the desired numeric type first. For example, in this program the command line argument is converted into integer first and then stored into the variables. However, the command line arguments can be passed directly without storing its value in local variables. # importing the moduleimport sys # function definitiondef add(a, b): print("Result", a + b) # fetching the argumentsarg1 = int(sys.argv[1])arg2 = int(sys.argv[2]) # displaying the argumentsprint(arg1, arg2) # calling the functionadd(arg1, arg2) Output : Using argparse moduleThere is a certain problem with sys.argv method as it does not throw any specific error if the argument is not passed or argument of invalid type is passed. The argparse module gracefully handles the absence and presence of parameters. The following examples show the utility of argparse module: # importing the moduleimport argparse # creating an ArgumentParsert objectparser = argparse.ArgumentParser() # fetching the argumentsparser.add_argument('number', help = "Enter number to triple it.")args = parser.parse_args() # performing some operationprint(args.number * 2) Output : Python by default accepts all command line arguments as string type hence the result is 55 ie. the string gets repeated twice. However, we can specify the data type we are expecting in the program itself so that whenever a command line argument is passed it is automatically converted into expected data type provided it is type compatible. # importing the moduleimport argparse # creating an ArgumentParsert objectparser = argparse.ArgumentParser() # fetching the argumentsparser.add_argument('number', help = "Enter number to double.", type = int)args = parser.parse_args()print(args.number * 2) Output : We can look at the errors generated : This argparse throws specific error unlike the sys module. Any of the modules can be used as per convenience and requirement. Python provides a getopt module that enables parsing command-line arguments. Example : import sys import getopt def full_name(): first_name = None last_name = None argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, "f:l:") except: print("Error") for opt, arg in opts: if opt in ['-f']: first_name = arg elif opt in ['-l']: last_name = arg print( first_name +" " + last_name) full_name() Output : python-utility 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": "\n02 Sep, 2020" }, { "code": null, "e": 25763, "s": 25537, "text": "Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are:" }, { "code": null, "e": 25778, "s": 25763, "text": "Using sys.argv" }, { "code": null, "e": 25802, "s": 25778, "text": "Using getopt module/li>" }, { "code": null, "e": 25824, "s": 25802, "text": "Using argparse module" }, { "code": null, "e": 26414, "s": 25824, "text": "The Python sys module allows access to command-line arguments with the help of sys module. The python sys module provides functions and variables that can be used to access different parts of the Python Runtime Environment. It allows access to system-specific parameters and functions. To use the sys module we need to import the sys module in our program before running any functions.There are mainly two functions in the sys module:sys.argv: gives the list of command-line arguments. For example, sys.argv[0] is the program name.len(sys.argv): gives the number of command-line arguments." }, { "code": null, "e": 26623, "s": 26414, "text": "Example 1 : This program demonstrates the use of sys.argv to fetch the command line arguments and len(sys.argv) gives the total number of command line arguments passed including the name of the python script." }, { "code": "# importing the moduleimport sys # storing the argumentsprogram = sys.argv[0]arg1 = sys.argv[1]arg2 = sys.argv[2]arg3 = sys.argv[3] # displaying the program nameprint(\"Program name : \" + program) # displaying the argumentsprint(\"arg1 : \" + arg1)print(\"arg2 : \" + arg2)print(\"arg3 : \" + arg3)print(\"Number of arguments : \", len(sys.argv))print(sys.argv)", "e": 26979, "s": 26623, "text": null }, { "code": null, "e": 26988, "s": 26979, "text": "Output :" }, { "code": null, "e": 27376, "s": 26988, "text": "Example 2 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1, 2 and 3 are stored into the variables arg1, arg2 and arg3. The variables arg1, arg2 and arg3 are passed to the function defined. However, the command line arguments can be passed directly without storing its value in local variables." }, { "code": "# importing the moduleimport sys # function definitiondef concat(s1, s2, s3): print(s1 + \" \" + s2 + \" \" + s3) # fetching the argumentsarg1 = sys.argv[1]arg2 = sys.argv[2]arg3 = sys.argv[3] # calling the functionconcat(arg1, arg2, arg3)", "e": 27618, "s": 27376, "text": null }, { "code": null, "e": 27627, "s": 27618, "text": "Output :" }, { "code": null, "e": 28272, "s": 27627, "text": "Example 3 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1 and 2 are stored into the variables arg1 and arg2. The variables a and b are passed to the function defined. Command line arguments are accepted as strings, hence in order to perform numerical operations it should be converted into the desired numeric type first. For example, in this program the command line argument is converted into integer first and then stored into the variables. However, the command line arguments can be passed directly without storing its value in local variables." }, { "code": "# importing the moduleimport sys # function definitiondef add(a, b): print(\"Result\", a + b) # fetching the argumentsarg1 = int(sys.argv[1])arg2 = int(sys.argv[2]) # displaying the argumentsprint(arg1, arg2) # calling the functionadd(arg1, arg2)", "e": 28524, "s": 28272, "text": null }, { "code": null, "e": 28533, "s": 28524, "text": "Output :" }, { "code": null, "e": 28850, "s": 28533, "text": "Using argparse moduleThere is a certain problem with sys.argv method as it does not throw any specific error if the argument is not passed or argument of invalid type is passed. The argparse module gracefully handles the absence and presence of parameters. The following examples show the utility of argparse module:" }, { "code": "# importing the moduleimport argparse # creating an ArgumentParsert objectparser = argparse.ArgumentParser() # fetching the argumentsparser.add_argument('number', help = \"Enter number to triple it.\")args = parser.parse_args() # performing some operationprint(args.number * 2)", "e": 29148, "s": 28850, "text": null }, { "code": null, "e": 29157, "s": 29148, "text": "Output :" }, { "code": null, "e": 29498, "s": 29157, "text": "Python by default accepts all command line arguments as string type hence the result is 55 ie. the string gets repeated twice. However, we can specify the data type we are expecting in the program itself so that whenever a command line argument is passed it is automatically converted into expected data type provided it is type compatible." }, { "code": "# importing the moduleimport argparse # creating an ArgumentParsert objectparser = argparse.ArgumentParser() # fetching the argumentsparser.add_argument('number', help = \"Enter number to double.\", type = int)args = parser.parse_args()print(args.number * 2)", "e": 29795, "s": 29498, "text": null }, { "code": null, "e": 29804, "s": 29795, "text": "Output :" }, { "code": null, "e": 29842, "s": 29804, "text": "We can look at the errors generated :" }, { "code": null, "e": 29968, "s": 29842, "text": "This argparse throws specific error unlike the sys module. Any of the modules can be used as per convenience and requirement." }, { "code": null, "e": 30045, "s": 29968, "text": "Python provides a getopt module that enables parsing command-line arguments." }, { "code": null, "e": 30055, "s": 30045, "text": "Example :" }, { "code": "import sys import getopt def full_name(): first_name = None last_name = None argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, \"f:l:\") except: print(\"Error\") for opt, arg in opts: if opt in ['-f']: first_name = arg elif opt in ['-l']: last_name = arg print( first_name +\" \" + last_name) full_name()", "e": 30488, "s": 30055, "text": null }, { "code": null, "e": 30497, "s": 30488, "text": "Output :" }, { "code": null, "e": 30512, "s": 30497, "text": "python-utility" }, { "code": null, "e": 30519, "s": 30512, "text": "Python" }, { "code": null, "e": 30617, "s": 30519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30649, "s": 30617, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30691, "s": 30649, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30733, "s": 30691, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30760, "s": 30733, "text": "Python Classes and Objects" }, { "code": null, "e": 30816, "s": 30760, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30838, "s": 30816, "text": "Defaultdict in Python" }, { "code": null, "e": 30877, "s": 30838, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30908, "s": 30877, "text": "Python | os.path.join() method" }, { "code": null, "e": 30937, "s": 30908, "text": "Create a directory in Python" } ]
C-LOOK Disk Scheduling Algorithm - GeeksforGeeks
22 Jun, 2021 Prerequisite: Disk Scheduling Algorithms Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if C-LOOK disk scheduling algorithm is used. Also, write a program to find the seek sequence using C-LOOK disk scheduling algorithm. C-LOOK (Circular LOOK) Disk Scheduling Algorithm: C-LOOK is an enhanced version of both SCAN as well as LOOK disk scheduling algorithms. This algorithm also uses the idea of wrapping the tracks as a circular cylinder as C-SCAN algorithm but the seek time is better than C-SCAN algorithm. We know that C-SCAN is used to avoid starvation and services all the requests more uniformly, the same goes for C-LOOK. In this algorithm, the head services requests only in one direction(either left or right) until all the requests in this direction are not serviced and then jumps back to the farthest request on the other direction and service the remaining requests which gives a better uniform servicing as well as avoids wasting seek time for going till the end of the disk. Algorithm- Let Request array represents an array storing indexes of the tracks that have been requested in ascending order of their time of arrival and head is the position of the disk head.The initial direction in which the head is moving is given and it services in the same direction.The head services all the requests one by one in the direction it is moving.The head continues to move in the same direction until all the requests in this direction have been serviced.While moving in this direction, calculate the absolute distance of the tracks from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 5 until we reach the last request in this direction.If we reach the last request in the current direction then reverse the direction and move the head in this direction until we reach the last request that is needed to be serviced in this direction without servicing the intermediate requests.Reverse the direction and go to step 3 until all the requests have not been serviced. Let Request array represents an array storing indexes of the tracks that have been requested in ascending order of their time of arrival and head is the position of the disk head. The initial direction in which the head is moving is given and it services in the same direction. The head services all the requests one by one in the direction it is moving. The head continues to move in the same direction until all the requests in this direction have been serviced. While moving in this direction, calculate the absolute distance of the tracks from the head. Increment the total seek count with this distance. Currently serviced track position now becomes the new head position. Go to step 5 until we reach the last request in this direction. If we reach the last request in the current direction then reverse the direction and move the head in this direction until we reach the last request that is needed to be serviced in this direction without servicing the intermediate requests. Reverse the direction and go to step 3 until all the requests have not been serviced. Examples: Input: Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} Initial head position = 50 Direction = right (Moving from left to right) Output: Initial position of head: 50 Total number of seek operations = 156 Seek Sequence is 60 79 92 114 176 11 34 41 The following chart shows the sequence in which requested tracks are serviced using C-LOOK. Therefore, the total seek count = (60 – 50) + (79 – 60) + (92 – 79) + (114 – 92) + (176 – 114) + (176 – 11) + (34 – 11) + (41 – 34) = 321 Implementation: The implementation of the C-LOOK algorithm is given below. Note that the distance variable is used to store the absolute distance between the head and the current track position, disk_size is the size of the disk. Vectors left and right store all the request tracks on the left-hand side and the right-hand side of the initial head position respectively. C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;int size = 8;int disk_size = 200; // Function to perform C-LOOK on the request// array starting from the given headvoid CLOOK(int arr[], int head){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // Sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // First service the requests // on the right side of the // head for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // Appending current track to seek sequence seek_sequence.push_back(cur_track); // Calculate absolute distance distance = abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for (int i = 0; i < left.size(); i++) { cur_track = left[i]; // Appending current track to seek sequence seek_sequence.push_back(cur_track); // Calculate absolute distance distance = abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } cout << "Total number of seek operations = " << seek_count << endl; cout << "Seek Sequence is" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // Request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; cout << "Initial position of head: " << head << endl; CLOOK(arr, head); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static int size = 8;static int disk_size = 200; // Function to perform C-LOOK on the request// array starting from the given headpublic static void CLOOK(int arr[], int head){ int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(); Vector<Integer> right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // Sorting left and right vectors Collections.sort(left); Collections.sort(right); // First service the requests // on the right side of the // head for(int i = 0; i < right.size(); i++) { cur_track = right.get(i); // Appending current track // to seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.abs(head - left.get(0)); head = left.get(0); // Now service the requests again // which are left for(int i = 0; i < left.size(); i++) { cur_track = left.get(i); // Appending current track to // seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } System.out.println("Total number of seek " + "operations = " + seek_count); System.out.println("Seek Sequence is"); for(int i = 0; i < seek_sequence.size(); i++) { System.out.println(seek_sequence.get(i)); }} // Driver codepublic static void main(String []args){ // Request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; System.out.println("Initial position of head: " + head); CLOOK(arr, head);}} // This code is contributed by divyesh072019 # Python3 implementation of the approachsize = 8disk_size = 200 # Function to perform C-LOOK on the request# array starting from the given headdef CLOOK(arr, head): seek_count = 0 distance = 0 cur_track = 0 left = [] right = [] seek_sequence = [] # Tracks on the left of the # head will be serviced when # once the head comes back # to the beginning (left end) for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # First service the requests # on the right side of the # head for i in range(len(right)): cur_track = right[i] # Appending current track # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track # Once reached the right end # jump to the last track that # is needed to be serviced in # left direction seek_count += abs(head - left[0]) head = left[0] # Now service the requests again # which are left for i in range(len(left)): cur_track = left[i] # Appending current track to # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track print("Total number of seek operations =", seek_count) print("Seek Sequence is") for i in range(len(seek_sequence)): print(seek_sequence[i]) # Driver code # Request arrayarr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]head = 50 print("Initial position of head:", head) CLOOK(arr, head) # This code is contributed by rag2127 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int size = 8; // Function to perform C-LOOK on the request// array starting from the given headstatic void CLOOK(int[] arr, int head){ int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(); List<int> right = new List<int>(); List<int> seek_sequence = new List<int>(); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // Sorting left and right vectors left.Sort(); right.Sort(); // First service the requests // on the right side of the // head for(int i = 0; i < right.Count; i++) { cur_track = right[i]; // Appending current track // to seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.Abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for(int i = 0; i < left.Count; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } Console.WriteLine("Total number of seek " + "operations = " + seek_count); Console.WriteLine("Seek Sequence is"); for(int i = 0; i < seek_sequence.Count; i++) { Console.WriteLine(seek_sequence[i]); }} // Driver codestatic void Main(){ // Request array int[] arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; Console.WriteLine("Initial position of head: " + head); CLOOK(arr, head);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript implementation of the approach let size = 8; // Function to perform C-LOOK on the request // array starting from the given head function CLOOK(arr, head) { let seek_count = 0; let distance, cur_track; let left = []; let right = []; let seek_sequence = []; // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // Sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // First service the requests // on the right side of the // head for(let i = 0; i < right.length; i++) { cur_track = right[i]; // Appending current track // to seek sequence seek_sequence.push(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for(let i = 0; i < left.length; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.push(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } document.write("Total number of seek " + "operations = " + seek_count + "</br>"); document.write("Seek Sequence is" + "</br>"); for(let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + "</br>"); } } // Request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; document.write("Initial position of head: " + head + "</br>"); CLOOK(arr, head); </script> Initial position of head: 50 Total number of seek operations = 321 Seek Sequence is 60 79 92 114 176 11 34 41 divyesh072019 divyeshrabadiya07 rag2127 mukesh07 clintra C++ Programs GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL Layers of OSI Model ACID Properties in DBMS TCP/IP Model Normal Forms in DBMS Differences between TCP and UDP
[ { "code": null, "e": 29429, "s": 29401, "text": "\n22 Jun, 2021" }, { "code": null, "e": 29470, "s": 29429, "text": "Prerequisite: Disk Scheduling Algorithms" }, { "code": null, "e": 29763, "s": 29470, "text": "Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if C-LOOK disk scheduling algorithm is used. Also, write a program to find the seek sequence using C-LOOK disk scheduling algorithm." }, { "code": null, "e": 30532, "s": 29763, "text": "C-LOOK (Circular LOOK) Disk Scheduling Algorithm: C-LOOK is an enhanced version of both SCAN as well as LOOK disk scheduling algorithms. This algorithm also uses the idea of wrapping the tracks as a circular cylinder as C-SCAN algorithm but the seek time is better than C-SCAN algorithm. We know that C-SCAN is used to avoid starvation and services all the requests more uniformly, the same goes for C-LOOK. In this algorithm, the head services requests only in one direction(either left or right) until all the requests in this direction are not serviced and then jumps back to the farthest request on the other direction and service the remaining requests which gives a better uniform servicing as well as avoids wasting seek time for going till the end of the disk." }, { "code": null, "e": 30544, "s": 30532, "text": "Algorithm- " }, { "code": null, "e": 31605, "s": 30544, "text": "Let Request array represents an array storing indexes of the tracks that have been requested in ascending order of their time of arrival and head is the position of the disk head.The initial direction in which the head is moving is given and it services in the same direction.The head services all the requests one by one in the direction it is moving.The head continues to move in the same direction until all the requests in this direction have been serviced.While moving in this direction, calculate the absolute distance of the tracks from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 5 until we reach the last request in this direction.If we reach the last request in the current direction then reverse the direction and move the head in this direction until we reach the last request that is needed to be serviced in this direction without servicing the intermediate requests.Reverse the direction and go to step 3 until all the requests have not been serviced." }, { "code": null, "e": 31785, "s": 31605, "text": "Let Request array represents an array storing indexes of the tracks that have been requested in ascending order of their time of arrival and head is the position of the disk head." }, { "code": null, "e": 31883, "s": 31785, "text": "The initial direction in which the head is moving is given and it services in the same direction." }, { "code": null, "e": 31960, "s": 31883, "text": "The head services all the requests one by one in the direction it is moving." }, { "code": null, "e": 32070, "s": 31960, "text": "The head continues to move in the same direction until all the requests in this direction have been serviced." }, { "code": null, "e": 32163, "s": 32070, "text": "While moving in this direction, calculate the absolute distance of the tracks from the head." }, { "code": null, "e": 32214, "s": 32163, "text": "Increment the total seek count with this distance." }, { "code": null, "e": 32283, "s": 32214, "text": "Currently serviced track position now becomes the new head position." }, { "code": null, "e": 32347, "s": 32283, "text": "Go to step 5 until we reach the last request in this direction." }, { "code": null, "e": 32589, "s": 32347, "text": "If we reach the last request in the current direction then reverse the direction and move the head in this direction until we reach the last request that is needed to be serviced in this direction without servicing the intermediate requests." }, { "code": null, "e": 32675, "s": 32589, "text": "Reverse the direction and go to step 3 until all the requests have not been serviced." }, { "code": null, "e": 32686, "s": 32675, "text": "Examples: " }, { "code": null, "e": 32940, "s": 32686, "text": "Input: Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} Initial head position = 50 Direction = right (Moving from left to right) Output: Initial position of head: 50 Total number of seek operations = 156 Seek Sequence is 60 79 92 114 176 11 34 41 " }, { "code": null, "e": 33033, "s": 32940, "text": "The following chart shows the sequence in which requested tracks are serviced using C-LOOK. " }, { "code": null, "e": 33171, "s": 33033, "text": "Therefore, the total seek count = (60 – 50) + (79 – 60) + (92 – 79) + (114 – 92) + (176 – 114) + (176 – 11) + (34 – 11) + (41 – 34) = 321" }, { "code": null, "e": 33542, "s": 33171, "text": "Implementation: The implementation of the C-LOOK algorithm is given below. Note that the distance variable is used to store the absolute distance between the head and the current track position, disk_size is the size of the disk. Vectors left and right store all the request tracks on the left-hand side and the right-hand side of the initial head position respectively." }, { "code": null, "e": 33546, "s": 33542, "text": "C++" }, { "code": null, "e": 33551, "s": 33546, "text": "Java" }, { "code": null, "e": 33559, "s": 33551, "text": "Python3" }, { "code": null, "e": 33562, "s": 33559, "text": "C#" }, { "code": null, "e": 33573, "s": 33562, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;int size = 8;int disk_size = 200; // Function to perform C-LOOK on the request// array starting from the given headvoid CLOOK(int arr[], int head){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // Sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // First service the requests // on the right side of the // head for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // Appending current track to seek sequence seek_sequence.push_back(cur_track); // Calculate absolute distance distance = abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for (int i = 0; i < left.size(); i++) { cur_track = left[i]; // Appending current track to seek sequence seek_sequence.push_back(cur_track); // Calculate absolute distance distance = abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } cout << \"Total number of seek operations = \" << seek_count << endl; cout << \"Seek Sequence is\" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // Request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; cout << \"Initial position of head: \" << head << endl; CLOOK(arr, head); return 0;}", "e": 35874, "s": 33573, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static int size = 8;static int disk_size = 200; // Function to perform C-LOOK on the request// array starting from the given headpublic static void CLOOK(int arr[], int head){ int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(); Vector<Integer> right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // Sorting left and right vectors Collections.sort(left); Collections.sort(right); // First service the requests // on the right side of the // head for(int i = 0; i < right.size(); i++) { cur_track = right.get(i); // Appending current track // to seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.abs(head - left.get(0)); head = left.get(0); // Now service the requests again // which are left for(int i = 0; i < left.size(); i++) { cur_track = left.get(i); // Appending current track to // seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } System.out.println(\"Total number of seek \" + \"operations = \" + seek_count); System.out.println(\"Seek Sequence is\"); for(int i = 0; i < seek_sequence.size(); i++) { System.out.println(seek_sequence.get(i)); }} // Driver codepublic static void main(String []args){ // Request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; System.out.println(\"Initial position of head: \" + head); CLOOK(arr, head);}} // This code is contributed by divyesh072019", "e": 38462, "s": 35874, "text": null }, { "code": "# Python3 implementation of the approachsize = 8disk_size = 200 # Function to perform C-LOOK on the request# array starting from the given headdef CLOOK(arr, head): seek_count = 0 distance = 0 cur_track = 0 left = [] right = [] seek_sequence = [] # Tracks on the left of the # head will be serviced when # once the head comes back # to the beginning (left end) for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # First service the requests # on the right side of the # head for i in range(len(right)): cur_track = right[i] # Appending current track # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track # Once reached the right end # jump to the last track that # is needed to be serviced in # left direction seek_count += abs(head - left[0]) head = left[0] # Now service the requests again # which are left for i in range(len(left)): cur_track = left[i] # Appending current track to # seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track print(\"Total number of seek operations =\", seek_count) print(\"Seek Sequence is\") for i in range(len(seek_sequence)): print(seek_sequence[i]) # Driver code # Request arrayarr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]head = 50 print(\"Initial position of head:\", head) CLOOK(arr, head) # This code is contributed by rag2127", "e": 40466, "s": 38462, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int size = 8; // Function to perform C-LOOK on the request// array starting from the given headstatic void CLOOK(int[] arr, int head){ int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(); List<int> right = new List<int>(); List<int> seek_sequence = new List<int>(); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // Sorting left and right vectors left.Sort(); right.Sort(); // First service the requests // on the right side of the // head for(int i = 0; i < right.Count; i++) { cur_track = right[i]; // Appending current track // to seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.Abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for(int i = 0; i < left.Count; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } Console.WriteLine(\"Total number of seek \" + \"operations = \" + seek_count); Console.WriteLine(\"Seek Sequence is\"); for(int i = 0; i < seek_sequence.Count; i++) { Console.WriteLine(seek_sequence[i]); }} // Driver codestatic void Main(){ // Request array int[] arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; Console.WriteLine(\"Initial position of head: \" + head); CLOOK(arr, head);}} // This code is contributed by divyeshrabadiya07", "e": 42965, "s": 40466, "text": null }, { "code": "<script> // Javascript implementation of the approach let size = 8; // Function to perform C-LOOK on the request // array starting from the given head function CLOOK(arr, head) { let seek_count = 0; let distance, cur_track; let left = []; let right = []; let seek_sequence = []; // Tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end) for(let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // Sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // First service the requests // on the right side of the // head for(let i = 0; i < right.length; i++) { cur_track = right[i]; // Appending current track // to seek sequence seek_sequence.push(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the last track that // is needed to be serviced in // left direction seek_count += Math.abs(head - left[0]); head = left[0]; // Now service the requests again // which are left for(let i = 0; i < left.length; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.push(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } document.write(\"Total number of seek \" + \"operations = \" + seek_count + \"</br>\"); document.write(\"Seek Sequence is\" + \"</br>\"); for(let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + \"</br>\"); } } // Request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; document.write(\"Initial position of head: \" + head + \"</br>\"); CLOOK(arr, head); </script>", "e": 45553, "s": 42965, "text": null }, { "code": null, "e": 45663, "s": 45553, "text": "Initial position of head: 50\nTotal number of seek operations = 321\nSeek Sequence is\n60\n79\n92\n114\n176\n11\n34\n41" }, { "code": null, "e": 45679, "s": 45665, "text": "divyesh072019" }, { "code": null, "e": 45697, "s": 45679, "text": "divyeshrabadiya07" }, { "code": null, "e": 45705, "s": 45697, "text": "rag2127" }, { "code": null, "e": 45714, "s": 45705, "text": "mukesh07" }, { "code": null, "e": 45722, "s": 45714, "text": "clintra" }, { "code": null, "e": 45735, "s": 45722, "text": "C++ Programs" }, { "code": null, "e": 45743, "s": 45735, "text": "GATE CS" }, { "code": null, "e": 45761, "s": 45743, "text": "Operating Systems" }, { "code": null, "e": 45779, "s": 45761, "text": "Operating Systems" }, { "code": null, "e": 45877, "s": 45779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45912, "s": 45877, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 45956, "s": 45912, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 46015, "s": 45956, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 46041, "s": 46015, "text": "C++ Program for QuickSort" }, { "code": null, "e": 46075, "s": 46041, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 46095, "s": 46075, "text": "Layers of OSI Model" }, { "code": null, "e": 46119, "s": 46095, "text": "ACID Properties in DBMS" }, { "code": null, "e": 46132, "s": 46119, "text": "TCP/IP Model" }, { "code": null, "e": 46153, "s": 46132, "text": "Normal Forms in DBMS" } ]
Find the second last node of a linked list in single traversal - GeeksforGeeks
09 Jun, 2021 Given a linked list. The task is to find the second last node of the linked list using a single traversal only.Examples: Input : List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output : 4Input : List = 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL Output : 33 The idea is to traverse the linked list following the below approach: If the list is empty or contains less than 2 elements, return false.Otherwise check if the current node is the second last node of the linked list or not. That is, if (current_node->next-next == NULL ) then the current node is the second last node.If the current node is the second last node, print the node otherwise move to the next node.Repeat the above two steps until the second last node is reached. If the list is empty or contains less than 2 elements, return false. Otherwise check if the current node is the second last node of the linked list or not. That is, if (current_node->next-next == NULL ) then the current node is the second last node. If the current node is the second last node, print the node otherwise move to the next node. Repeat the above two steps until the second last node is reached. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the second last node// of a linked list in single traversal #include <iostream>using namespace std; // Link list nodestruct Node { int data; struct Node* next;}; // Function to find the second last// node of the linked listint findSecondLastNode(struct Node* head){ struct Node* temp = head; // If the list is empty or contains less // than 2 nodes if (temp == NULL || temp->next == NULL) return -1; // Traverse the linked list while (temp != NULL) { // Check if the current node is the // second last node or not if (temp->next->next == NULL) return temp->data; // If not then move to the next node temp = temp->next; }} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); cout << findSecondLastNode(head); return 0;} // Java program to find the second last node// of a linked list in single traversal // Linked list nodeclass Node{ int data; Node next; Node(int d) { this.data = d; this.next = null; }}class LinkedList{ Node start; LinkedList() { start = null; } // Function to push node at head public void push(int data) { if(this.start == null) { Node temp = new Node(data); this.start = temp; } else { Node temp = new Node(data); temp.next = this.start; this.start = temp; } } // method to find the second last // node of the linked list public int findSecondLastNode(Node ptr) { Node temp = ptr; // If the list is empty or contains less // than 2 nodes if(temp == null || temp.next == null) return -1; // This loop stops at second last node while(temp.next.next != null) { temp = temp.next; } return temp.data; } // Driver code public static void main(String[] args) { LinkedList ll = new LinkedList(); /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ ll.push(12); ll.push(29); ll.push(11); ll.push(23); ll.push(8); System.out.println(ll.findSecondLastNode(ll.start)); }} // This code is Contributed by Adarsh_Verma # Python3 program to find the second last node# of a linked list in single traversalimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to find the second last# node of the linked listdef findSecondLastNode(head): temp = head # If the list is empty or # contains less than 2 nodes if (temp == None or temp.next == None): return -1 # Traverse the linked list while (temp != None): # Check if the current node is the # second last node or not if (temp.next.next == None): return temp.data # If not then move to the next node temp = temp.next # Function to push node at headdef push(head, new_data): new_node = Node(new_data) #new_node.data = new_data new_node.next = head head = new_node return head # Driver codeif __name__ == '__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 . 23 . 11 . 29 . 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) print(findSecondLastNode(head)) # This code is contributed by Srathore // C# program to find the second last node// of a linked list in single traversalusing System; // Linked list nodepublic class Node{ public int data; public Node next; public Node(int d) { this.data = d; this.next = null; }}public class LinkedList{ Node start; LinkedList() { start = null; } // Function to push node at head public void push(int data) { if(this.start == null) { Node temp = new Node(data); this.start = temp; } else { Node temp = new Node(data); temp.next = this.start; this.start = temp; } } // method to find the second last // node of the linked list public int findSecondLastNode(Node ptr) { Node temp = ptr; // If the list is empty or contains less // than 2 nodes if(temp == null || temp.next == null) return -1; // This loop stops at second last node while(temp.next.next != null) { temp = temp.next; } return temp.data; } // Driver code public static void Main() { LinkedList ll = new LinkedList(); /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ ll.push(12); ll.push(29); ll.push(11); ll.push(23); ll.push(8); Console.WriteLine(ll.findSecondLastNode(ll.start)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find the second last node// of a linked list in single traversal // Link list node class Node {constructor(data) {this.data = data;this.next = null;}} // method to find the second last// node of the linked listfunction findSecondLastNode( ptr){var temp = head ; // If the list is empty or// contains less than 2 nodesif (temp == null || temp.next == null)return -1 ; // Traverse the linked listwhile (temp != null){ // Check if the current node is the// second last node or notif (temp.next.next == null)return temp.data; // If not then move to the next nodetemp = temp.next;}} // Function to push node at headfunction push( data){var new_node = new Node(data) ;new_node.next = head ;head = new_node ;return head ;} // Driver Code var head = null ; /* Use push() function to constructthe below list 8 -> 23 -> 11 -> 29 -> 12 */ head = push(12);head = push(29);head = push(11);head = push(23);head = push(8);document.write(findSecondLastNode(head)); // This code is contributed by jana_sayantan.</script> 29 Time complexity : O(n) VishalBachchas Adarsh_Verma princiraj1992 sapnasingh4991 jana_sayantan Order-Statistics Technical Scripter 2018 Linked List Technical Scripter Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Real-time application of Data Structures Delete a node in a Doubly Linked List Linked List Implementation in C# Insert a node at a specific position in a linked list Insertion Sort for Singly Linked List
[ { "code": null, "e": 26179, "s": 26151, "text": "\n09 Jun, 2021" }, { "code": null, "e": 26302, "s": 26179, "text": "Given a linked list. The task is to find the second last node of the linked list using a single traversal only.Examples: " }, { "code": null, "e": 26423, "s": 26302, "text": "Input : List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output : 4Input : List = 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL Output : 33 " }, { "code": null, "e": 26497, "s": 26425, "text": "The idea is to traverse the linked list following the below approach: " }, { "code": null, "e": 26903, "s": 26497, "text": "If the list is empty or contains less than 2 elements, return false.Otherwise check if the current node is the second last node of the linked list or not. That is, if (current_node->next-next == NULL ) then the current node is the second last node.If the current node is the second last node, print the node otherwise move to the next node.Repeat the above two steps until the second last node is reached." }, { "code": null, "e": 26972, "s": 26903, "text": "If the list is empty or contains less than 2 elements, return false." }, { "code": null, "e": 27153, "s": 26972, "text": "Otherwise check if the current node is the second last node of the linked list or not. That is, if (current_node->next-next == NULL ) then the current node is the second last node." }, { "code": null, "e": 27246, "s": 27153, "text": "If the current node is the second last node, print the node otherwise move to the next node." }, { "code": null, "e": 27312, "s": 27246, "text": "Repeat the above two steps until the second last node is reached." }, { "code": null, "e": 27365, "s": 27312, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27369, "s": 27365, "text": "C++" }, { "code": null, "e": 27374, "s": 27369, "text": "Java" }, { "code": null, "e": 27382, "s": 27374, "text": "Python3" }, { "code": null, "e": 27385, "s": 27382, "text": "C#" }, { "code": null, "e": 27396, "s": 27385, "text": "Javascript" }, { "code": "// C++ program to find the second last node// of a linked list in single traversal #include <iostream>using namespace std; // Link list nodestruct Node { int data; struct Node* next;}; // Function to find the second last// node of the linked listint findSecondLastNode(struct Node* head){ struct Node* temp = head; // If the list is empty or contains less // than 2 nodes if (temp == NULL || temp->next == NULL) return -1; // Traverse the linked list while (temp != NULL) { // Check if the current node is the // second last node or not if (temp->next->next == NULL) return temp->data; // If not then move to the next node temp = temp->next; }} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); cout << findSecondLastNode(head); return 0;}", "e": 28657, "s": 27396, "text": null }, { "code": "// Java program to find the second last node// of a linked list in single traversal // Linked list nodeclass Node{ int data; Node next; Node(int d) { this.data = d; this.next = null; }}class LinkedList{ Node start; LinkedList() { start = null; } // Function to push node at head public void push(int data) { if(this.start == null) { Node temp = new Node(data); this.start = temp; } else { Node temp = new Node(data); temp.next = this.start; this.start = temp; } } // method to find the second last // node of the linked list public int findSecondLastNode(Node ptr) { Node temp = ptr; // If the list is empty or contains less // than 2 nodes if(temp == null || temp.next == null) return -1; // This loop stops at second last node while(temp.next.next != null) { temp = temp.next; } return temp.data; } // Driver code public static void main(String[] args) { LinkedList ll = new LinkedList(); /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ ll.push(12); ll.push(29); ll.push(11); ll.push(23); ll.push(8); System.out.println(ll.findSecondLastNode(ll.start)); }} // This code is Contributed by Adarsh_Verma", "e": 30158, "s": 28657, "text": null }, { "code": "# Python3 program to find the second last node# of a linked list in single traversalimport math # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to find the second last# node of the linked listdef findSecondLastNode(head): temp = head # If the list is empty or # contains less than 2 nodes if (temp == None or temp.next == None): return -1 # Traverse the linked list while (temp != None): # Check if the current node is the # second last node or not if (temp.next.next == None): return temp.data # If not then move to the next node temp = temp.next # Function to push node at headdef push(head, new_data): new_node = Node(new_data) #new_node.data = new_data new_node.next = head head = new_node return head # Driver codeif __name__ == '__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 . 23 . 11 . 29 . 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) print(findSecondLastNode(head)) # This code is contributed by Srathore", "e": 31405, "s": 30158, "text": null }, { "code": "// C# program to find the second last node// of a linked list in single traversalusing System; // Linked list nodepublic class Node{ public int data; public Node next; public Node(int d) { this.data = d; this.next = null; }}public class LinkedList{ Node start; LinkedList() { start = null; } // Function to push node at head public void push(int data) { if(this.start == null) { Node temp = new Node(data); this.start = temp; } else { Node temp = new Node(data); temp.next = this.start; this.start = temp; } } // method to find the second last // node of the linked list public int findSecondLastNode(Node ptr) { Node temp = ptr; // If the list is empty or contains less // than 2 nodes if(temp == null || temp.next == null) return -1; // This loop stops at second last node while(temp.next.next != null) { temp = temp.next; } return temp.data; } // Driver code public static void Main() { LinkedList ll = new LinkedList(); /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ ll.push(12); ll.push(29); ll.push(11); ll.push(23); ll.push(8); Console.WriteLine(ll.findSecondLastNode(ll.start)); }} // This code is contributed by PrinciRaj1992", "e": 32939, "s": 31405, "text": null }, { "code": "<script> // Javascript program to find the second last node// of a linked list in single traversal // Link list node class Node {constructor(data) {this.data = data;this.next = null;}} // method to find the second last// node of the linked listfunction findSecondLastNode( ptr){var temp = head ; // If the list is empty or// contains less than 2 nodesif (temp == null || temp.next == null)return -1 ; // Traverse the linked listwhile (temp != null){ // Check if the current node is the// second last node or notif (temp.next.next == null)return temp.data; // If not then move to the next nodetemp = temp.next;}} // Function to push node at headfunction push( data){var new_node = new Node(data) ;new_node.next = head ;head = new_node ;return head ;} // Driver Code var head = null ; /* Use push() function to constructthe below list 8 -> 23 -> 11 -> 29 -> 12 */ head = push(12);head = push(29);head = push(11);head = push(23);head = push(8);document.write(findSecondLastNode(head)); // This code is contributed by jana_sayantan.</script>", "e": 33977, "s": 32939, "text": null }, { "code": null, "e": 33980, "s": 33977, "text": "29" }, { "code": null, "e": 34006, "s": 33982, "text": "Time complexity : O(n) " }, { "code": null, "e": 34021, "s": 34006, "text": "VishalBachchas" }, { "code": null, "e": 34034, "s": 34021, "text": "Adarsh_Verma" }, { "code": null, "e": 34048, "s": 34034, "text": "princiraj1992" }, { "code": null, "e": 34063, "s": 34048, "text": "sapnasingh4991" }, { "code": null, "e": 34077, "s": 34063, "text": "jana_sayantan" }, { "code": null, "e": 34094, "s": 34077, "text": "Order-Statistics" }, { "code": null, "e": 34118, "s": 34094, "text": "Technical Scripter 2018" }, { "code": null, "e": 34130, "s": 34118, "text": "Linked List" }, { "code": null, "e": 34149, "s": 34130, "text": "Technical Scripter" }, { "code": null, "e": 34161, "s": 34149, "text": "Linked List" }, { "code": null, "e": 34259, "s": 34161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34300, "s": 34259, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 34350, "s": 34300, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 34409, "s": 34350, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34449, "s": 34409, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 34520, "s": 34449, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 34561, "s": 34520, "text": "Real-time application of Data Structures" }, { "code": null, "e": 34599, "s": 34561, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 34632, "s": 34599, "text": "Linked List Implementation in C#" }, { "code": null, "e": 34686, "s": 34632, "text": "Insert a node at a specific position in a linked list" } ]
response.is_redirect - Python requests - GeeksforGeeks
01 Mar, 2020 Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.is_redirect out of a response object. response.is_redirect returns True if the response was redirected, otherwise False. To illustrate use of response.is_redirect, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac # import requests moduleimport requests # Making a get requestresponse = requests.get('https://geeksforgeeks.org') # print responseprint(response) # print is_redirect Flagprint(response.is_redirect) Save above file as request.py and run using Python request.py Check that False at the start of the output, it shows that is_redirect is False. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests 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": "\n01 Mar, 2020" }, { "code": null, "e": 25991, "s": 25537, "text": "Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.is_redirect out of a response object. response.is_redirect returns True if the response was redirected, otherwise False." }, { "code": null, "e": 26143, "s": 25991, "text": "To illustrate use of response.is_redirect, let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC." }, { "code": null, "e": 26188, "s": 26143, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 26248, "s": 26188, "text": "How to install requests in Python – For windows, linux, mac" }, { "code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://geeksforgeeks.org') # print responseprint(response) # print is_redirect Flagprint(response.is_redirect)", "e": 26450, "s": 26248, "text": null }, { "code": null, "e": 26494, "s": 26450, "text": "Save above file as request.py and run using" }, { "code": null, "e": 26513, "s": 26494, "text": "Python request.py\n" }, { "code": null, "e": 26594, "s": 26513, "text": "Check that False at the start of the output, it shows that is_redirect is False." }, { "code": null, "e": 26845, "s": 26594, "text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute." }, { "code": null, "e": 26866, "s": 26845, "text": "requests.status_code" }, { "code": null, "e": 27023, "s": 26866, "text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources." }, { "code": null, "e": 27039, "s": 27023, "text": "Python-requests" }, { "code": null, "e": 27046, "s": 27039, "text": "Python" }, { "code": null, "e": 27144, "s": 27046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27176, "s": 27144, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27218, "s": 27176, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27260, "s": 27218, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27287, "s": 27260, "text": "Python Classes and Objects" }, { "code": null, "e": 27343, "s": 27287, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27365, "s": 27343, "text": "Defaultdict in Python" }, { "code": null, "e": 27404, "s": 27365, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27435, "s": 27404, "text": "Python | os.path.join() method" }, { "code": null, "e": 27464, "s": 27435, "text": "Create a directory in Python" } ]
base64.b32decode() in Python - GeeksforGeeks
26 Mar, 2020 With the help of base64.b32decode() method, we can decode the binary string using base32 alphabets into normal form. Syntax : base64.b32decode(b_string) Return : Return the decoded string. Example #1 :In this example we can see that by using base64.b32decode() method, we are able to get the decoded string which can be in binary form by using this method. # import base64from base64 import b32decodefrom base64 import b32encode s = b'GeeksForGeeks's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s) print(gfg) Output : b’GeeksForGeeks’ Example #2 : # import base64from base64 import b32decodefrom base64 import b32encode s = b'Hello World's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s) print(gfg) Output : b’Hello World’ Python base64-module 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25654, "s": 25537, "text": "With the help of base64.b32decode() method, we can decode the binary string using base32 alphabets into normal form." }, { "code": null, "e": 25690, "s": 25654, "text": "Syntax : base64.b32decode(b_string)" }, { "code": null, "e": 25726, "s": 25690, "text": "Return : Return the decoded string." }, { "code": null, "e": 25894, "s": 25726, "text": "Example #1 :In this example we can see that by using base64.b32decode() method, we are able to get the decoded string which can be in binary form by using this method." }, { "code": "# import base64from base64 import b32decodefrom base64 import b32encode s = b'GeeksForGeeks's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s) print(gfg)", "e": 26067, "s": 25894, "text": null }, { "code": null, "e": 26076, "s": 26067, "text": "Output :" }, { "code": null, "e": 26093, "s": 26076, "text": "b’GeeksForGeeks’" }, { "code": null, "e": 26106, "s": 26093, "text": "Example #2 :" }, { "code": "# import base64from base64 import b32decodefrom base64 import b32encode s = b'Hello World's = b32encode(s)# Using base64.b32decode() methodgfg = b32decode(s) print(gfg)", "e": 26277, "s": 26106, "text": null }, { "code": null, "e": 26286, "s": 26277, "text": "Output :" }, { "code": null, "e": 26301, "s": 26286, "text": "b’Hello World’" }, { "code": null, "e": 26322, "s": 26301, "text": "Python base64-module" }, { "code": null, "e": 26329, "s": 26322, "text": "Python" }, { "code": null, "e": 26427, "s": 26329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26459, "s": 26427, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26501, "s": 26459, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26543, "s": 26501, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26570, "s": 26543, "text": "Python Classes and Objects" }, { "code": null, "e": 26626, "s": 26570, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26665, "s": 26626, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26687, "s": 26665, "text": "Defaultdict in Python" }, { "code": null, "e": 26718, "s": 26687, "text": "Python | os.path.join() method" }, { "code": null, "e": 26747, "s": 26718, "text": "Create a directory in Python" } ]
MongoDB - Embedded Documents - GeeksforGeeks
14 Sep, 2021 MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents. Notes – In MongoDB, you can only nest document up to 100 levels. The overall document size must not exceed 16 MB. In MongoDB, you can easily embed a document inside another document. As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document. Syntax: { .... field: {field1: value1, field2: value2} .... } Let us discuss this concept with the help of the given examples – Example 1: Suppose we have a database named ‘GeeksforGeeks’. Now this database has a collection named ‘Courses’ and this collection contains a document. Inside this document, we have a field named ‘name’ which contains another document and this document contain three fields(i.e, first, middle, last) with their values. Example 2: Again, we are taking GeeksforGeeks database. Inside this database, we already have a collection named ‘Courses’, now we add another document in this collection, which contains the details of the student who select paid courses. Inside this document, we have a field named ‘courseDetails’. This field contains a document and this document contains some field-value pairs and a sub-document which contains the paymentDetials. So, overall the Courses collection contains two documents and these documents contain nested documents. gulshankumarar231 MongoDB Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Election algorithm and distributed processing Introduction to Internet of Things (IoT) | Set 1 Introduction to Electronic Mail Communication Models in IoT (Internet of Things )
[ { "code": null, "e": 25893, "s": 25865, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26317, "s": 25893, "text": "MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents. " }, { "code": null, "e": 26327, "s": 26317, "text": "Notes – " }, { "code": null, "e": 26384, "s": 26327, "text": "In MongoDB, you can only nest document up to 100 levels." }, { "code": null, "e": 26433, "s": 26384, "text": "The overall document size must not exceed 16 MB." }, { "code": null, "e": 26802, "s": 26437, "text": "In MongoDB, you can easily embed a document inside another document. As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document. " }, { "code": null, "e": 26812, "s": 26802, "text": "Syntax: " }, { "code": null, "e": 26866, "s": 26812, "text": "{\n....\nfield: {field1: value1, field2: value2}\n....\n}" }, { "code": null, "e": 26933, "s": 26866, "text": "Let us discuss this concept with the help of the given examples – " }, { "code": null, "e": 26945, "s": 26933, "text": "Example 1: " }, { "code": null, "e": 27256, "s": 26945, "text": "Suppose we have a database named ‘GeeksforGeeks’. Now this database has a collection named ‘Courses’ and this collection contains a document. Inside this document, we have a field named ‘name’ which contains another document and this document contain three fields(i.e, first, middle, last) with their values. " }, { "code": null, "e": 27270, "s": 27258, "text": "Example 2: " }, { "code": null, "e": 27696, "s": 27270, "text": "Again, we are taking GeeksforGeeks database. Inside this database, we already have a collection named ‘Courses’, now we add another document in this collection, which contains the details of the student who select paid courses. Inside this document, we have a field named ‘courseDetails’. This field contains a document and this document contains some field-value pairs and a sub-document which contains the paymentDetials. " }, { "code": null, "e": 27802, "s": 27696, "text": "So, overall the Courses collection contains two documents and these documents contain nested documents. " }, { "code": null, "e": 27822, "s": 27804, "text": "gulshankumarar231" }, { "code": null, "e": 27830, "s": 27822, "text": "MongoDB" }, { "code": null, "e": 27835, "s": 27830, "text": "Misc" }, { "code": null, "e": 27840, "s": 27835, "text": "Misc" }, { "code": null, "e": 27845, "s": 27840, "text": "Misc" }, { "code": null, "e": 27943, "s": 27845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27964, "s": 27943, "text": "Activation Functions" }, { "code": null, "e": 28002, "s": 27964, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 28038, "s": 28002, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 28073, "s": 28038, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 28112, "s": 28073, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 28158, "s": 28112, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 28207, "s": 28158, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 28239, "s": 28207, "text": "Introduction to Electronic Mail" } ]
Difference between __sizeof__() and getsizeof() method - Python - GeeksforGeeks
06 May, 2021 Memory management is of utmost priority when we write large chunks of code. So in addition to good coding knowledge, it is important to be able to write programs, so as to handle memory efficiently. So let us look at the two ways of getting the size of a particular object in Python. These are getsizeof() method and __sizeof() method. The getsizeof() is a system-specific method and hence we have to import the sys module to use it. A sample code is as shown below for calculating the size of a list. Python3 import sysa =[1, 2]b =[1, 2, 3, 4]c =[1, 2, 3, 4]d =[2, 3, 1, 4, 66, 54, 45, 89]print(sys.getsizeof(a))print(sys.getsizeof(b))print(sys.getsizeof(c))print(sys.getsizeof(d)) Output: 80 96 96 128 getsizeof() method calls the __sizeof__() method o the object with an additional garbage collector overhead. Hence the size returned by the getsize() method will be more than that returned by the __sizeof()__ method. For example, the getsizeof() method returns 64 bytes for an empty list and then 8 bytes for every additional element.Now let’s look at the __sizeof__() method. It returns the size of the object without any overhead. Python3 w =[1, 2]x =[4, 5, 7, 9]y =[2, 8, 6, 56, 45, 89, 88]z =[54, 45, 12, 23, 24, 90, 20, 40]print(w.__sizeof__())print(x.__sizeof__())print(y.__sizeof__())print(z.__sizeof__()) Output: 56 72 96 104 For example, the __sizeof__() method returns 40 bytes for an empty list and then 8 bytes for every additional element. anshuman24 Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n06 May, 2021" }, { "code": null, "e": 25763, "s": 25563, "text": "Memory management is of utmost priority when we write large chunks of code. So in addition to good coding knowledge, it is important to be able to write programs, so as to handle memory efficiently. " }, { "code": null, "e": 26067, "s": 25763, "text": "So let us look at the two ways of getting the size of a particular object in Python. These are getsizeof() method and __sizeof() method. The getsizeof() is a system-specific method and hence we have to import the sys module to use it. A sample code is as shown below for calculating the size of a list. " }, { "code": null, "e": 26075, "s": 26067, "text": "Python3" }, { "code": "import sysa =[1, 2]b =[1, 2, 3, 4]c =[1, 2, 3, 4]d =[2, 3, 1, 4, 66, 54, 45, 89]print(sys.getsizeof(a))print(sys.getsizeof(b))print(sys.getsizeof(c))print(sys.getsizeof(d))", "e": 26248, "s": 26075, "text": null }, { "code": null, "e": 26258, "s": 26248, "text": "Output: " }, { "code": null, "e": 26271, "s": 26258, "text": "80\n96\n96\n128" }, { "code": null, "e": 26705, "s": 26271, "text": "getsizeof() method calls the __sizeof__() method o the object with an additional garbage collector overhead. Hence the size returned by the getsize() method will be more than that returned by the __sizeof()__ method. For example, the getsizeof() method returns 64 bytes for an empty list and then 8 bytes for every additional element.Now let’s look at the __sizeof__() method. It returns the size of the object without any overhead. " }, { "code": null, "e": 26713, "s": 26705, "text": "Python3" }, { "code": "w =[1, 2]x =[4, 5, 7, 9]y =[2, 8, 6, 56, 45, 89, 88]z =[54, 45, 12, 23, 24, 90, 20, 40]print(w.__sizeof__())print(x.__sizeof__())print(y.__sizeof__())print(z.__sizeof__())", "e": 26885, "s": 26713, "text": null }, { "code": null, "e": 26895, "s": 26885, "text": "Output: " }, { "code": null, "e": 26908, "s": 26895, "text": "56\n72\n96\n104" }, { "code": null, "e": 27028, "s": 26908, "text": "For example, the __sizeof__() method returns 40 bytes for an empty list and then 8 bytes for every additional element. " }, { "code": null, "e": 27039, "s": 27028, "text": "anshuman24" }, { "code": null, "e": 27056, "s": 27039, "text": "Python-Functions" }, { "code": null, "e": 27063, "s": 27056, "text": "Python" }, { "code": null, "e": 27161, "s": 27063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27193, "s": 27161, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27235, "s": 27193, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27277, "s": 27235, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27304, "s": 27277, "text": "Python Classes and Objects" }, { "code": null, "e": 27360, "s": 27304, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27399, "s": 27360, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27421, "s": 27399, "text": "Defaultdict in Python" }, { "code": null, "e": 27452, "s": 27421, "text": "Python | os.path.join() method" }, { "code": null, "e": 27481, "s": 27452, "text": "Create a directory in Python" } ]
C++ Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers) - GeeksforGeeks
21 Dec, 2021 Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7 Output: Sum found between indexes 1 and 4 Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7 Input: arr[] = {1, 4}, sum = 0 Output: No subarray found There is no subarray with 0 sum There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray. Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm: Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray. Traverse the array from start to end. From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum. For every index in inner loop update sum = sum + array[j] If the sum is equal to the given sum then print the subarray. C++ /* C++ simple program to print subarray with sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // Try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { cout << "Sum found between indexes " << i << " and " << j - 1; return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } cout << "No subarray found"; return 0;} // Driver Codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}// This code is contributed by rathbhupendra Output : Sum found between indexes 1 and 4 Complexity Analysis: Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2) Space Complexity: O(1). As constant extra space is required. Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm: Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop. Create three variables, l=0, sum = 0 Traverse the array from start to end. Update the variable sum by adding current element, sum = sum + array[i] If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++. If the sum is equal to given sum, print the subarray and break the loop. C++ /* An efficient program to print subarray with sum as given sum */#include <iostream>using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { cout << "Sum found between indexes " << start << " and " << i - 1; return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray cout << "No subarray found"; return 0;} // Driver Codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}// This code is contributed by SHUBHAMSINGH10 Output : Sum found between indexes 1 and 4 Complexity Analysis: Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n). Space Complexity: O(1). As constant extra space is required. Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details! Amazon Facebook FactSet Google Morgan Stanley sliding-window subarray subarray-sum Visa Zoho Arrays C++ Programs Zoho Morgan Stanley Amazon FactSet Visa Google Facebook sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 26041, "s": 26013, "text": "\n21 Dec, 2021" }, { "code": null, "e": 26159, "s": 26041, "text": "Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : " }, { "code": null, "e": 26548, "s": 26159, "text": "Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33\nOutput: Sum found between indexes 2 and 4\nSum of elements between indices\n2 and 4 is 20 + 3 + 10 = 33\n\nInput: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7\nOutput: Sum found between indexes 1 and 4\nSum of elements between indices\n1 and 4 is 4 + 0 + 0 + 3 = 7\n\nInput: arr[] = {1, 4}, sum = 0\nOutput: No subarray found\nThere is no subarray with 0 sum" }, { "code": null, "e": 26664, "s": 26548, "text": "There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray. " }, { "code": null, "e": 26949, "s": 26664, "text": "Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm: " }, { "code": null, "e": 27246, "s": 26949, "text": "Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray." }, { "code": null, "e": 27284, "s": 27246, "text": "Traverse the array from start to end." }, { "code": null, "e": 27426, "s": 27284, "text": "From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum." }, { "code": null, "e": 27484, "s": 27426, "text": "For every index in inner loop update sum = sum + array[j]" }, { "code": null, "e": 27546, "s": 27484, "text": "If the sum is equal to the given sum then print the subarray." }, { "code": null, "e": 27550, "s": 27546, "text": "C++" }, { "code": "/* C++ simple program to print subarray with sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // Try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { cout << \"Sum found between indexes \" << i << \" and \" << j - 1; return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } cout << \"No subarray found\"; return 0;} // Driver Codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}// This code is contributed by rathbhupendra", "e": 28630, "s": 27550, "text": null }, { "code": null, "e": 28639, "s": 28630, "text": "Output :" }, { "code": null, "e": 28673, "s": 28639, "text": "Sum found between indexes 1 and 4" }, { "code": null, "e": 28696, "s": 28673, "text": "Complexity Analysis: " }, { "code": null, "e": 28810, "s": 28696, "text": "Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)" }, { "code": null, "e": 28871, "s": 28810, "text": "Space Complexity: O(1). As constant extra space is required." }, { "code": null, "e": 29351, "s": 28871, "text": "Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm: " }, { "code": null, "e": 29680, "s": 29351, "text": "Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop." }, { "code": null, "e": 29717, "s": 29680, "text": "Create three variables, l=0, sum = 0" }, { "code": null, "e": 29755, "s": 29717, "text": "Traverse the array from start to end." }, { "code": null, "e": 29827, "s": 29755, "text": "Update the variable sum by adding current element, sum = sum + array[i]" }, { "code": null, "e": 29940, "s": 29827, "text": "If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++." }, { "code": null, "e": 30013, "s": 29940, "text": "If the sum is equal to given sum, print the subarray and break the loop." }, { "code": null, "e": 30017, "s": 30013, "text": "C++" }, { "code": "/* An efficient program to print subarray with sum as given sum */#include <iostream>using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { cout << \"Sum found between indexes \" << start << \" and \" << i - 1; return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray cout << \"No subarray found\"; return 0;} // Driver Codeint main(){ int arr[] = {15, 2, 4, 8, 9, 5, 10, 23}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}// This code is contributed by SHUBHAMSINGH10", "e": 31467, "s": 30017, "text": null }, { "code": null, "e": 31476, "s": 31467, "text": "Output :" }, { "code": null, "e": 31510, "s": 31476, "text": "Sum found between indexes 1 and 4" }, { "code": null, "e": 31533, "s": 31510, "text": "Complexity Analysis: " }, { "code": null, "e": 31634, "s": 31533, "text": "Time Complexity : O(n). Only one traversal of the array is required. So the time complexity is O(n)." }, { "code": null, "e": 31695, "s": 31634, "text": "Space Complexity: O(1). As constant extra space is required." }, { "code": null, "e": 31805, "s": 31695, "text": "Please refer complete article on Find subarray with given sum | Set 1 (Nonnegative Numbers) for more details!" }, { "code": null, "e": 31812, "s": 31805, "text": "Amazon" }, { "code": null, "e": 31821, "s": 31812, "text": "Facebook" }, { "code": null, "e": 31829, "s": 31821, "text": "FactSet" }, { "code": null, "e": 31836, "s": 31829, "text": "Google" }, { "code": null, "e": 31851, "s": 31836, "text": "Morgan Stanley" }, { "code": null, "e": 31866, "s": 31851, "text": "sliding-window" }, { "code": null, "e": 31875, "s": 31866, "text": "subarray" }, { "code": null, "e": 31888, "s": 31875, "text": "subarray-sum" }, { "code": null, "e": 31893, "s": 31888, "text": "Visa" }, { "code": null, "e": 31898, "s": 31893, "text": "Zoho" }, { "code": null, "e": 31905, "s": 31898, "text": "Arrays" }, { "code": null, "e": 31918, "s": 31905, "text": "C++ Programs" }, { "code": null, "e": 31923, "s": 31918, "text": "Zoho" }, { "code": null, "e": 31938, "s": 31923, "text": "Morgan Stanley" }, { "code": null, "e": 31945, "s": 31938, "text": "Amazon" }, { "code": null, "e": 31953, "s": 31945, "text": "FactSet" }, { "code": null, "e": 31958, "s": 31953, "text": "Visa" }, { "code": null, "e": 31965, "s": 31958, "text": "Google" }, { "code": null, "e": 31974, "s": 31965, "text": "Facebook" }, { "code": null, "e": 31989, "s": 31974, "text": "sliding-window" }, { "code": null, "e": 31996, "s": 31989, "text": "Arrays" }, { "code": null, "e": 32094, "s": 31996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32125, "s": 32094, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 32152, "s": 32125, "text": "Count pairs with given sum" }, { "code": null, "e": 32177, "s": 32152, "text": "Window Sliding Technique" }, { "code": null, "e": 32215, "s": 32177, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32236, "s": 32215, "text": "Next Greater Element" }, { "code": null, "e": 32271, "s": 32236, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 32315, "s": 32271, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 32341, "s": 32315, "text": "C++ Program for QuickSort" }, { "code": null, "e": 32400, "s": 32341, "text": "How to return multiple values from a function in C or C++?" } ]
Python | Find Symmetric Pairs in dictionary - GeeksforGeeks
15 Oct, 2019 Sometimes, while working with Python dictionary, one can have a problem in which one desires to get key-value pairs that are symmetrical, i.e that has key-value pair of same value irrespective of the fact value is a key or value. Let’s discuss certain ways in which this task can be performed. Method #1 : Using generator + loop This task can be solved in brute force method using loops and generators by yielding at runtime the values of matching key-value pairs. # Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# using generator + loop # generator function to perform taskdef find_sym_pairs(test_dict): for key in test_dict.keys(): val = test_dict.get(key) if test_dict.get(val) == key: yield key, val return # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3, 1 : 'a', 2 : 'b'} # printing original dict print("The original dict is : " + str(test_dict)) # Find Symmetric Pairs in dictionary# using generator + loopres = []for key, val in find_sym_pairs(test_dict): temp = (key, val) res.append(temp) # printing resultprint("The pairs of Symmetric values : " + str(res)) The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'} The pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')] Method #2 : Using list comprehension This task can also be performed as a one-liner using list comprehension as a shortened way of performing loop-based solution. # Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# Using list comprehension # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3, 1 : 'a', 2 : 'b'} # printing original dict print("The original dict is : " + str(test_dict)) # Find Symmetric Pairs in dictionary# Using list comprehensiontemp = [(key, value) for key, value in test_dict.items()]res = [(x, y) for (x, y) in temp if (y, x) in temp] # printing resultprint("The pairs of Symmetric values : " + str(res)) The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'} The pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')] Python dictionary-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25681, "s": 25653, "text": "\n15 Oct, 2019" }, { "code": null, "e": 25975, "s": 25681, "text": "Sometimes, while working with Python dictionary, one can have a problem in which one desires to get key-value pairs that are symmetrical, i.e that has key-value pair of same value irrespective of the fact value is a key or value. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26010, "s": 25975, "text": "Method #1 : Using generator + loop" }, { "code": null, "e": 26146, "s": 26010, "text": "This task can be solved in brute force method using loops and generators by yielding at runtime the values of matching key-value pairs." }, { "code": "# Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# using generator + loop # generator function to perform taskdef find_sym_pairs(test_dict): for key in test_dict.keys(): val = test_dict.get(key) if test_dict.get(val) == key: yield key, val return # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3, 1 : 'a', 2 : 'b'} # printing original dict print(\"The original dict is : \" + str(test_dict)) # Find Symmetric Pairs in dictionary# using generator + loopres = []for key, val in find_sym_pairs(test_dict): temp = (key, val) res.append(temp) # printing resultprint(\"The pairs of Symmetric values : \" + str(res))", "e": 26834, "s": 26146, "text": null }, { "code": null, "e": 26972, "s": 26834, "text": "The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'}\nThe pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')]\n" }, { "code": null, "e": 27011, "s": 26974, "text": "Method #2 : Using list comprehension" }, { "code": null, "e": 27137, "s": 27011, "text": "This task can also be performed as a one-liner using list comprehension as a shortened way of performing loop-based solution." }, { "code": "# Python3 code to demonstrate working of# Find Symmetric Pairs in dictionary# Using list comprehension # Initializing dicttest_dict = {'a' : 1, 'b' : 2, 'c' : 3, 1 : 'a', 2 : 'b'} # printing original dict print(\"The original dict is : \" + str(test_dict)) # Find Symmetric Pairs in dictionary# Using list comprehensiontemp = [(key, value) for key, value in test_dict.items()]res = [(x, y) for (x, y) in temp if (y, x) in temp] # printing resultprint(\"The pairs of Symmetric values : \" + str(res))", "e": 27638, "s": 27137, "text": null }, { "code": null, "e": 27776, "s": 27638, "text": "The original dict is : {'a': 1, 1: 'a', 'c': 3, 'b': 2, 2: 'b'}\nThe pairs of Symmetric values : [('a', 1), (1, 'a'), ('b', 2), (2, 'b')]\n" }, { "code": null, "e": 27803, "s": 27776, "text": "Python dictionary-programs" }, { "code": null, "e": 27810, "s": 27803, "text": "Python" }, { "code": null, "e": 27826, "s": 27810, "text": "Python Programs" }, { "code": null, "e": 27924, "s": 27826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27942, "s": 27924, "text": "Python Dictionary" }, { "code": null, "e": 27977, "s": 27942, "text": "Read a file line by line in Python" }, { "code": null, "e": 28009, "s": 27977, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28031, "s": 28009, "text": "Enumerate() in Python" }, { "code": null, "e": 28073, "s": 28031, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28116, "s": 28073, "text": "Python program to convert a list to string" }, { "code": null, "e": 28138, "s": 28116, "text": "Defaultdict in Python" }, { "code": null, "e": 28177, "s": 28138, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28223, "s": 28177, "text": "Python | Split string into list of characters" } ]
How to use onKeyPress event in ReactJS? - GeeksforGeeks
25 Jan, 2021 The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers. To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app functiondemo Step 2: After creating your project folder i.e. functiondemo, move to it using the following command: cd functiondemo Project Structure: It will look like the following. Project Structure Example: In this example, we are going to build an application that displays the key pressed in the input box. Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React, { useState } from 'react'; const App = () => { const [state, setState] = useState(''); const handler = (event) => { // changing the state to the name of the key // which is pressed setState(event.key); }; return ( <div> <h1>Hi Geeks!</h1> <p>Key pressed is: {state}</p> {/* Passing the key pressed to the handler function */} <input type="text" onKeyPress={(e) => handler(e)} /> </div> );}; export default App; Note: You can define your own styling in the App.css file. Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Picked ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook How to set background images in ReactJS ? ReactJS defaultProps Re-rendering Components in ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25667, "s": 25639, "text": "\n25 Jan, 2021" }, { "code": null, "e": 25827, "s": 25667, "text": "The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers." }, { "code": null, "e": 25912, "s": 25827, "text": "To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method." }, { "code": null, "e": 25940, "s": 25912, "text": "Creating React Application:" }, { "code": null, "e": 26004, "s": 25940, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26038, "s": 26004, "text": "npx create-react-app functiondemo" }, { "code": null, "e": 26140, "s": 26038, "text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:" }, { "code": null, "e": 26156, "s": 26140, "text": "cd functiondemo" }, { "code": null, "e": 26208, "s": 26156, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26226, "s": 26208, "text": "Project Structure" }, { "code": null, "e": 26337, "s": 26226, "text": "Example: In this example, we are going to build an application that displays the key pressed in the input box." }, { "code": null, "e": 26476, "s": 26337, "text": "Filename- App.js: 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": 26487, "s": 26476, "text": "Javascript" }, { "code": "import React, { useState } from 'react'; const App = () => { const [state, setState] = useState(''); const handler = (event) => { // changing the state to the name of the key // which is pressed setState(event.key); }; return ( <div> <h1>Hi Geeks!</h1> <p>Key pressed is: {state}</p> {/* Passing the key pressed to the handler function */} <input type=\"text\" onKeyPress={(e) => handler(e)} /> </div> );}; export default App;", "e": 26984, "s": 26487, "text": null }, { "code": null, "e": 27043, "s": 26984, "text": "Note: You can define your own styling in the App.css file." }, { "code": null, "e": 27156, "s": 27043, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27166, "s": 27156, "text": "npm start" }, { "code": null, "e": 27175, "s": 27166, "text": "Output: " }, { "code": null, "e": 27182, "s": 27175, "text": "Picked" }, { "code": null, "e": 27190, "s": 27182, "text": "ReactJS" }, { "code": null, "e": 27207, "s": 27190, "text": "Web Technologies" }, { "code": null, "e": 27305, "s": 27207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27373, "s": 27305, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 27400, "s": 27373, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27442, "s": 27400, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27463, "s": 27442, "text": "ReactJS defaultProps" }, { "code": null, "e": 27498, "s": 27463, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 27538, "s": 27498, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27571, "s": 27538, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27616, "s": 27571, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27678, "s": 27616, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Kotlin Inline Functions - GeeksforGeeks
29 Jan, 2021 In Kotlin, the higher-order functions or lambda expressions, all stored as an object so memory allocation, for both function objects and classes, and virtual calls might introduce runtime overhead. Sometimes we can eliminate the memory overhead by inlining the lambda expression. In order to reduce the memory overhead of such higher-order functions or lambda expressions, we can use the inline keyword which ultimately requests the compiler to not allocate memory and simply copy the inlined code of that function at the calling place. Example: Kotlin fun higherfunc( str : String, mycall :(String)-> Unit) { // inovkes the print() by passing the string str mycall(str)} // main functionfun main(args: Array<String>) { print("GeeskforGeeks: ") higherfunc("A Computer Science portal for Geeks",::print)} Bytecode: Like Java, Kotlin is also platform independent language so it converts into the bytecode first. We can get the bytecode as Tools -> Kotlin -> Show Kotlin Bytecode. Then, decompile to get this bytecode. In the above bytecode, the main part to focus on is: mycall.invoke(str) mycall invokes the print function by passing the string as a parameter. While invoking the print(), it would create an additional call and increases memory overhead. It works like mycall(new Function() { @Override public void invoke() { //println statement is called here. } }); If we call a large number of functions as parameters each of them would add up to the method count then there is a vast impact on the memory and performance. What inline keyword will do in the above program? Kotlin inline fun higherfunc( str : String, mycall :(String)-> Unit){ // inovkes the print() by passing the string str mycall(str)}// main function fun main(args: Array<String>) { print("GeeskforGeeks: ") higherfunc("A Computer Science portal for Geeks",::print)} Bytecode: With the help of the inline keyword, the println lambda expression is copied in the main function in the form of System.out.println and no further calls required. In Kotlin, if we want to return from a lambda expression then the Kotlin compiler does not allow us to do so. With the help of the inline keyword, we can return from the lambda expression itself and exit the function in which inlined function is called. Kotlin Program of Using Return in Lambda Expression: Kotlin var lambda = { println("Lambda expression") return } // normally lambda expression does not allow return // statement, so gives compile time errorfun main(args: Array<String>) { lambda()} Output: Error:(4, 5) Kotlin: 'return' is not allowed here Normally it does not allow to return from lambda and it gives an error. Kotlin var lambda1 = { println("Lambda expression")} fun main(args: Array<String>) { lambda1()} Output: Lambda expression Normally without it works fine and print the statement. Kotlin Program of Using Return in Lambda While Passing as an Argument to Inlined Function: Kotlin fun main(args: Array<String>){ println("Main function starts") inlinedFunc({ println("Lambda expression 1") return }, // inlined function allow return // statement in lambda expression // so, does not give compile time error { println("Lambda expression 2")} ) println("Main function ends")} // inlined functioninline fun inlinedFunc( lmbd1: () -> Unit, lmbd2: () -> Unit ) { lmbd1() lmbd2()} Output: Main function starts Lambda expression 1 Explanation: Here, we passed two lambda expressions as arguments to the inlinedFunc() function. While calling the inlined function from the main, we pass both as to its arguments. In the inlined function, lmbd1() invoked the first expression and return keyword force the lambda expression itself and the main function from where it is called to exit. In the above program, return in lambda exits the inline function as well as its enclosing function. So to stop returning from the lambda expression we can mark it using the crossline. It will throw a compiler error if sees any return statement in the Lambda expression. Example: Kotlin fun main(args: Array<String>){ println("Main function starts") inlinedfunc({ println("Lambda expression 1") return }, // It gives compiler error { println("Lambda expression 2")} ) println("Main function ends")} inline fun inlinedfunc( crossinline lmbd1: () -> Unit, lmbd2: () -> Unit ) { lmbd1() lmbd2()} Output: Error:(6, 9) Kotlin: 'return' is not allowed here In Kotlin, if we want only some of the lambdas passed to an inline function to be inlined, we can mark some of the function parameters with the noinline modifier. Kotlin fun main(args: Array<String>){ println("Main function starts") inlinedFunc({ println("Lambda expression 1") return }, // It does not compiler time error { println("Lambda expression 2") return } ) // It gives compiler error println("Main function ends")} inline fun inlinedFunc( lmbd1: () -> Unit, noinline lmbd2: () -> Unit ) { lmbd1() lmbd2()} Output: Error:(11, 13) Kotlin: 'return' is not allowed here Sometimes we need to access the type of parameter passed during the call. We have to simply the pass of the parameter at the time function calling and we can retrieve the type of the parameter using a reified modifier. Kotlin fun main(args: Array<String>) { genericFunc<String>()} inline fun <reified T> genericFunc() { print(T::class)} Output: class kotlin.String Inlined function copy the code to the calling place, similarly inline keyword copy the inline properties accessor methods to calling place. The inline modifier can be used on accessors of properties that don’t have a backing field. Kotlin fun main(args: Array<String>) { print(flag)}fun foo(i: Int ): Int{ var a = i return a}inline var flag : Boolean get() = foo(10 ) == 10 set(flag) {flag} Output: true nidhi_biet kevilpy1 Kotlin Functions Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Android Tutorial Kotlin when expression Android Menus ImageView in Android with Example How to Build a Weather App in Android? MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25415, "s": 25387, "text": "\n29 Jan, 2021" }, { "code": null, "e": 25961, "s": 25415, "text": "In Kotlin, the higher-order functions or lambda expressions, all stored as an object so memory allocation, for both function objects and classes, and virtual calls might introduce runtime overhead. Sometimes we can eliminate the memory overhead by inlining the lambda expression. In order to reduce the memory overhead of such higher-order functions or lambda expressions, we can use the inline keyword which ultimately requests the compiler to not allocate memory and simply copy the inlined code of that function at the calling place. Example:" }, { "code": null, "e": 25968, "s": 25961, "text": "Kotlin" }, { "code": "fun higherfunc( str : String, mycall :(String)-> Unit) { // inovkes the print() by passing the string str mycall(str)} // main functionfun main(args: Array<String>) { print(\"GeeskforGeeks: \") higherfunc(\"A Computer Science portal for Geeks\",::print)}", "e": 26234, "s": 25968, "text": null }, { "code": null, "e": 26447, "s": 26234, "text": "Bytecode: Like Java, Kotlin is also platform independent language so it converts into the bytecode first. We can get the bytecode as Tools -> Kotlin -> Show Kotlin Bytecode. Then, decompile to get this bytecode. " }, { "code": null, "e": 26500, "s": 26447, "text": "In the above bytecode, the main part to focus on is:" }, { "code": null, "e": 26519, "s": 26500, "text": "mycall.invoke(str)" }, { "code": null, "e": 26685, "s": 26519, "text": "mycall invokes the print function by passing the string as a parameter. While invoking the print(), it would create an additional call and increases memory overhead." }, { "code": null, "e": 26699, "s": 26685, "text": "It works like" }, { "code": null, "e": 26835, "s": 26699, "text": "mycall(new Function() {\n @Override\n public void invoke() {\n //println statement is called here.\n }\n });" }, { "code": null, "e": 26994, "s": 26835, "text": "If we call a large number of functions as parameters each of them would add up to the method count then there is a vast impact on the memory and performance. " }, { "code": null, "e": 27044, "s": 26994, "text": "What inline keyword will do in the above program?" }, { "code": null, "e": 27051, "s": 27044, "text": "Kotlin" }, { "code": "inline fun higherfunc( str : String, mycall :(String)-> Unit){ // inovkes the print() by passing the string str mycall(str)}// main function fun main(args: Array<String>) { print(\"GeeskforGeeks: \") higherfunc(\"A Computer Science portal for Geeks\",::print)}", "e": 27320, "s": 27051, "text": null }, { "code": null, "e": 27332, "s": 27320, "text": "Bytecode: " }, { "code": null, "e": 27496, "s": 27332, "text": "With the help of the inline keyword, the println lambda expression is copied in the main function in the form of System.out.println and no further calls required. " }, { "code": null, "e": 27750, "s": 27496, "text": "In Kotlin, if we want to return from a lambda expression then the Kotlin compiler does not allow us to do so. With the help of the inline keyword, we can return from the lambda expression itself and exit the function in which inlined function is called." }, { "code": null, "e": 27804, "s": 27750, "text": "Kotlin Program of Using Return in Lambda Expression: " }, { "code": null, "e": 27811, "s": 27804, "text": "Kotlin" }, { "code": "var lambda = { println(\"Lambda expression\") return } // normally lambda expression does not allow return // statement, so gives compile time errorfun main(args: Array<String>) { lambda()}", "e": 28047, "s": 27811, "text": null }, { "code": null, "e": 28057, "s": 28047, "text": "Output: " }, { "code": null, "e": 28107, "s": 28057, "text": "Error:(4, 5) Kotlin: 'return' is not allowed here" }, { "code": null, "e": 28180, "s": 28107, "text": "Normally it does not allow to return from lambda and it gives an error. " }, { "code": null, "e": 28187, "s": 28180, "text": "Kotlin" }, { "code": "var lambda1 = { println(\"Lambda expression\")} fun main(args: Array<String>) { lambda1()}", "e": 28279, "s": 28187, "text": null }, { "code": null, "e": 28288, "s": 28279, "text": "Output: " }, { "code": null, "e": 28306, "s": 28288, "text": "Lambda expression" }, { "code": null, "e": 28362, "s": 28306, "text": "Normally without it works fine and print the statement." }, { "code": null, "e": 28454, "s": 28362, "text": "Kotlin Program of Using Return in Lambda While Passing as an Argument to Inlined Function: " }, { "code": null, "e": 28461, "s": 28454, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ println(\"Main function starts\") inlinedFunc({ println(\"Lambda expression 1\") return }, // inlined function allow return // statement in lambda expression // so, does not give compile time error { println(\"Lambda expression 2\")} ) println(\"Main function ends\")} // inlined functioninline fun inlinedFunc( lmbd1: () -> Unit, lmbd2: () -> Unit ) { lmbd1() lmbd2()}", "e": 28923, "s": 28461, "text": null }, { "code": null, "e": 28933, "s": 28923, "text": "Output: " }, { "code": null, "e": 28974, "s": 28933, "text": "Main function starts\nLambda expression 1" }, { "code": null, "e": 29325, "s": 28974, "text": "Explanation: Here, we passed two lambda expressions as arguments to the inlinedFunc() function. While calling the inlined function from the main, we pass both as to its arguments. In the inlined function, lmbd1() invoked the first expression and return keyword force the lambda expression itself and the main function from where it is called to exit." }, { "code": null, "e": 29595, "s": 29325, "text": "In the above program, return in lambda exits the inline function as well as its enclosing function. So to stop returning from the lambda expression we can mark it using the crossline. It will throw a compiler error if sees any return statement in the Lambda expression." }, { "code": null, "e": 29605, "s": 29595, "text": "Example: " }, { "code": null, "e": 29612, "s": 29605, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ println(\"Main function starts\") inlinedfunc({ println(\"Lambda expression 1\") return }, // It gives compiler error { println(\"Lambda expression 2\")} ) println(\"Main function ends\")} inline fun inlinedfunc( crossinline lmbd1: () -> Unit, lmbd2: () -> Unit ) { lmbd1() lmbd2()}", "e": 29955, "s": 29612, "text": null }, { "code": null, "e": 29965, "s": 29955, "text": "Output: " }, { "code": null, "e": 30015, "s": 29965, "text": "Error:(6, 9) Kotlin: 'return' is not allowed here" }, { "code": null, "e": 30179, "s": 30015, "text": "In Kotlin, if we want only some of the lambdas passed to an inline function to be inlined, we can mark some of the function parameters with the noinline modifier. " }, { "code": null, "e": 30186, "s": 30179, "text": "Kotlin" }, { "code": "fun main(args: Array<String>){ println(\"Main function starts\") inlinedFunc({ println(\"Lambda expression 1\") return }, // It does not compiler time error { println(\"Lambda expression 2\") return } ) // It gives compiler error println(\"Main function ends\")} inline fun inlinedFunc( lmbd1: () -> Unit, noinline lmbd2: () -> Unit ) { lmbd1() lmbd2()}", "e": 30581, "s": 30186, "text": null }, { "code": null, "e": 30591, "s": 30581, "text": "Output: " }, { "code": null, "e": 30643, "s": 30591, "text": "Error:(11, 13) Kotlin: 'return' is not allowed here" }, { "code": null, "e": 30863, "s": 30643, "text": "Sometimes we need to access the type of parameter passed during the call. We have to simply the pass of the parameter at the time function calling and we can retrieve the type of the parameter using a reified modifier. " }, { "code": null, "e": 30870, "s": 30863, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { genericFunc<String>()} inline fun <reified T> genericFunc() { print(T::class)}", "e": 30987, "s": 30870, "text": null }, { "code": null, "e": 30997, "s": 30987, "text": "Output: " }, { "code": null, "e": 31017, "s": 30997, "text": "class kotlin.String" }, { "code": null, "e": 31251, "s": 31017, "text": "Inlined function copy the code to the calling place, similarly inline keyword copy the inline properties accessor methods to calling place. The inline modifier can be used on accessors of properties that don’t have a backing field. " }, { "code": null, "e": 31258, "s": 31251, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { print(flag)}fun foo(i: Int ): Int{ var a = i return a}inline var flag : Boolean get() = foo(10 ) == 10 set(flag) {flag}", "e": 31426, "s": 31258, "text": null }, { "code": null, "e": 31436, "s": 31426, "text": "Output: " }, { "code": null, "e": 31441, "s": 31436, "text": "true" }, { "code": null, "e": 31452, "s": 31441, "text": "nidhi_biet" }, { "code": null, "e": 31461, "s": 31452, "text": "kevilpy1" }, { "code": null, "e": 31478, "s": 31461, "text": "Kotlin Functions" }, { "code": null, "e": 31485, "s": 31478, "text": "Kotlin" }, { "code": null, "e": 31583, "s": 31485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31614, "s": 31583, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 31656, "s": 31614, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31696, "s": 31656, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 31720, "s": 31696, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 31743, "s": 31720, "text": "Kotlin when expression" }, { "code": null, "e": 31757, "s": 31743, "text": "Android Menus" }, { "code": null, "e": 31791, "s": 31757, "text": "ImageView in Android with Example" }, { "code": null, "e": 31830, "s": 31791, "text": "How to Build a Weather App in Android?" } ]
How to Open URL in New Tab using JavaScript ? - GeeksforGeeks
20 Jul, 2021 In HTML, the anchor tag is used to open URLs in a new tab in an elementary and straightforward manner. More about this tag can be learnt from this article. However, sometimes there’s a need to do the same using Javascript. In this case window.open() method proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values. Approach: To open a new tab, we have to use _blank in second parameter of window.open(). The return value of window.open() is a reference to the newly created window or tab or null if it failed. Do not add a third parameter to it as it will result in the opening of a new window rather than a tab Syntax: window.open(URL, '_blank'); Example 1: <html> <body> <p>Click the button to open a new tab </p> <button onclick="NewTab()"> Open Geeksforgeeks </button> <script> function NewTab() { window.open( "https://www.geeksforgeeks.org", "_blank"); } </script> </body> </html> Output: Example 2: <html> <body> <p>Click the button to open google.</p> <button onclick="Open()">Geeksforgeeks</button> <script> function Open() { window.open("https://www.google.com", "_blank"); } </script> </body> </html> Output : JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. Picked JavaScript Web Technologies Web technologies Questions 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 Difference Between PUT and PATCH Request 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": 26191, "s": 26163, "text": "\n20 Jul, 2021" }, { "code": null, "e": 26604, "s": 26191, "text": "In HTML, the anchor tag is used to open URLs in a new tab in an elementary and straightforward manner. More about this tag can be learnt from this article. However, sometimes there’s a need to do the same using Javascript. In this case window.open() method proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values." }, { "code": null, "e": 26614, "s": 26604, "text": "Approach:" }, { "code": null, "e": 26693, "s": 26614, "text": "To open a new tab, we have to use _blank in second parameter of window.open()." }, { "code": null, "e": 26799, "s": 26693, "text": "The return value of window.open() is a reference to the newly created window or tab or null if it failed." }, { "code": null, "e": 26901, "s": 26799, "text": "Do not add a third parameter to it as it will result in the opening of a new window rather than a tab" }, { "code": null, "e": 26909, "s": 26901, "text": "Syntax:" }, { "code": null, "e": 26938, "s": 26909, "text": "window.open(URL, '_blank');\n" }, { "code": null, "e": 26949, "s": 26938, "text": "Example 1:" }, { "code": "<html> <body> <p>Click the button to open a new tab </p> <button onclick=\"NewTab()\"> Open Geeksforgeeks </button> <script> function NewTab() { window.open( \"https://www.geeksforgeeks.org\", \"_blank\"); } </script> </body> </html>", "e": 27242, "s": 26949, "text": null }, { "code": null, "e": 27250, "s": 27242, "text": "Output:" }, { "code": null, "e": 27261, "s": 27250, "text": "Example 2:" }, { "code": "<html> <body> <p>Click the button to open google.</p> <button onclick=\"Open()\">Geeksforgeeks</button> <script> function Open() { window.open(\"https://www.google.com\", \"_blank\"); } </script> </body> </html>", "e": 27513, "s": 27261, "text": null }, { "code": null, "e": 27522, "s": 27513, "text": "Output :" }, { "code": null, "e": 27741, "s": 27522, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 27748, "s": 27741, "text": "Picked" }, { "code": null, "e": 27759, "s": 27748, "text": "JavaScript" }, { "code": null, "e": 27776, "s": 27759, "text": "Web Technologies" }, { "code": null, "e": 27803, "s": 27776, "text": "Web technologies Questions" }, { "code": null, "e": 27901, "s": 27803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27941, "s": 27901, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27986, "s": 27941, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28047, "s": 27986, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28119, "s": 28047, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28160, "s": 28119, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28200, "s": 28160, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28233, "s": 28200, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28278, "s": 28233, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28321, "s": 28278, "text": "How to fetch data from an API in ReactJS ?" } ]
Reduce a number to 1 by performing given operations - GeeksforGeeks
17 May, 2021 Given a number N. The task is to reduce the given number N to 1 in the minimum number of steps. You can perform any one of the below operations in each step. Operation 1: If the number is even then you can divide the number by 2. Operation 2: If the number is odd then you are allowed to perform either (n+1) or (n-1). You need to print the minimum number of steps required to reduce the number N to 1 by performing the above operations. Examples: Input : n = 15 Output : 5 15 is odd 15+1=16 16 is even 16/2=8 8 is even 8/2=4 4 is even 4/2=2 2 is even 2/2=1 Input : n = 7 Output : 4 7->6 6->3 3->2 2->1 Method 1 – The idea is to recursively compute the minimum number of steps required. If the number is even, then we are allowed to only divide the number by 2. But, when the number is Odd, we can either increment or decrement it by 1. So, we will use recursion for both n-1 and n+1 and return the one with the minimum number of operations. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count minimum// steps to reduce a number#include <cmath>#include <iostream> using namespace std; int countways(int n){ if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + min(countways(n - 1), countways(n + 1));} // Driver codeint main(){ int n = 15; cout << countways(n) << "\n"; return 0;} // Java program to count minimum// steps to reduce a numberclass Geeks { static int countways(int n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.min(countways(n - 1), countways(n + 1)); } // Driver code public static void main(String args[]) { int n = 15; System.out.println(countways(n)); }} // This code is contributed by ankita_saini # Python3 program to count minimum# steps to reduce a number def countways(n): if (n == 1): return 0; elif (n % 2 == 0): return 1 + countways(n / 2); else: return 1 + min(countways(n - 1), countways(n + 1)); # Driver coden = 15;print(countways(n)); # This code is contributed by PrinciRaj1992 // C# program to count minimum// steps to reduce a numberusing System; class GFG { static int countways(int n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.Min(countways(n - 1), countways(n + 1)); } // Driver code static public void Main() { int n = 15; Console.Write(countways(n)); }} // This code is contributed by Raj <script> // Javascript program to count minimum// steps to reduce a number function countways(n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.min(countways(n - 1), countways(n + 1)); } // Driver code let n = 15; document.write(countways(n)); // This code is contributed by unknown2108 </script> 5 The above-mentioned approach has a time complexity of O(2^n). It is possible to reduce this complexity to O(log n). Method 2 – (Efficient Solution)It is clear with little observation that performing an increment of 1 or a decrement of 1 on an odd number can result in an even number, one of it divisible by 4. For an odd number, the only operation possible is either an increment of 1 or a decrement of 1, most certainly one operation will result in a number divisible by four, this is the optimal choice clearly. Algorithm : 1. Initialize count = 0 2. While number is greater than one perform following steps - Perform count++ for each iteration if num % 2 == 0, perform division else if num % 4 == 3, perform increment else perform decrement (as odd % 4 is either 1 or 3) 3. return count; C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>using namespace std; int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // driver code int main(){ int n = 15; // Function call cout << countSteps(n) << "\n"; return 0;} // Java program for the above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ public static int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // Driver codepublic static void main(String[] args){ int n = 15; // Function call System.out.print(countSteps(n));}} // This code is contributed by paragpallavsingh # Python3 program for the above approachdef countSteps(n): count = 0 while (n > 1): count += 1 # num even, divide by 2 if (n % 2 == 0): n //= 2 # num odd, n%4 == 1 # or n==3(special edge case), # decrement by 1 elif (n % 4 == 1 or n == 3): n -= 1 # num odd, n%4 == 3, increment by 1 else: n += 1 return count # Driver codeif __name__ == "__main__": n = 15 # Function call print(countSteps(n)) # This code is contributed by chitranayal // C# program for the above approachusing System; class GFG{ public static int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // Driver codestatic public void Main (){ int n = 15; // Function call Console.WriteLine(countSteps(n));}} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program for the above approach function countSteps(n) { let count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n = Math.floor(n/2); // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count; } // Driver code let n = 15; // Function call document.write(countSteps(n)); // This code is contributed by patel2127</script> 5 Time complexity : O(logN) ankita_saini R_Raj princiraj1992 ksucheta19 ukasp ParagPallavSingh1 rohit768 avanitrachhadiya2155 unknown2108 patel2127 Algorithms-Recursion Amazon Recursion Amazon Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Recursive Practice Problems with Solutions Write a program to reverse digits of a number Print all subsequences of a string Count all possible paths from top left to bottom right of a mXn matrix Recursive Functions Check if a number is Palindrome Reverse a stack using recursion Recursive Bubble Sort
[ { "code": null, "e": 26655, "s": 26627, "text": "\n17 May, 2021" }, { "code": null, "e": 26813, "s": 26655, "text": "Given a number N. The task is to reduce the given number N to 1 in the minimum number of steps. You can perform any one of the below operations in each step." }, { "code": null, "e": 26885, "s": 26813, "text": "Operation 1: If the number is even then you can divide the number by 2." }, { "code": null, "e": 26974, "s": 26885, "text": "Operation 2: If the number is odd then you are allowed to perform either (n+1) or (n-1)." }, { "code": null, "e": 27093, "s": 26974, "text": "You need to print the minimum number of steps required to reduce the number N to 1 by performing the above operations." }, { "code": null, "e": 27105, "s": 27093, "text": "Examples: " }, { "code": null, "e": 27314, "s": 27105, "text": "Input : n = 15\nOutput : 5\n 15 is odd 15+1=16 \n 16 is even 16/2=8 \n 8 is even 8/2=4 \n 4 is even 4/2=2 \n 2 is even 2/2=1 \n\nInput : n = 7\nOutput : 4\n 7->6 \n 6->3 \n 3->2 \n 2->1" }, { "code": null, "e": 27400, "s": 27314, "text": "Method 1 – The idea is to recursively compute the minimum number of steps required. " }, { "code": null, "e": 27475, "s": 27400, "text": "If the number is even, then we are allowed to only divide the number by 2." }, { "code": null, "e": 27655, "s": 27475, "text": "But, when the number is Odd, we can either increment or decrement it by 1. So, we will use recursion for both n-1 and n+1 and return the one with the minimum number of operations." }, { "code": null, "e": 27706, "s": 27655, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27710, "s": 27706, "text": "C++" }, { "code": null, "e": 27715, "s": 27710, "text": "Java" }, { "code": null, "e": 27723, "s": 27715, "text": "Python3" }, { "code": null, "e": 27726, "s": 27723, "text": "C#" }, { "code": null, "e": 27737, "s": 27726, "text": "Javascript" }, { "code": "// C++ program to count minimum// steps to reduce a number#include <cmath>#include <iostream> using namespace std; int countways(int n){ if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + min(countways(n - 1), countways(n + 1));} // Driver codeint main(){ int n = 15; cout << countways(n) << \"\\n\"; return 0;}", "e": 28146, "s": 27737, "text": null }, { "code": "// Java program to count minimum// steps to reduce a numberclass Geeks { static int countways(int n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.min(countways(n - 1), countways(n + 1)); } // Driver code public static void main(String args[]) { int n = 15; System.out.println(countways(n)); }} // This code is contributed by ankita_saini", "e": 28626, "s": 28146, "text": null }, { "code": "# Python3 program to count minimum# steps to reduce a number def countways(n): if (n == 1): return 0; elif (n % 2 == 0): return 1 + countways(n / 2); else: return 1 + min(countways(n - 1), countways(n + 1)); # Driver coden = 15;print(countways(n)); # This code is contributed by PrinciRaj1992", "e": 28969, "s": 28626, "text": null }, { "code": "// C# program to count minimum// steps to reduce a numberusing System; class GFG { static int countways(int n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.Min(countways(n - 1), countways(n + 1)); } // Driver code static public void Main() { int n = 15; Console.Write(countways(n)); }} // This code is contributed by Raj", "e": 29430, "s": 28969, "text": null }, { "code": "<script> // Javascript program to count minimum// steps to reduce a number function countways(n) { if (n == 1) return 0; else if (n % 2 == 0) return 1 + countways(n / 2); else return 1 + Math.min(countways(n - 1), countways(n + 1)); } // Driver code let n = 15; document.write(countways(n)); // This code is contributed by unknown2108 </script>", "e": 29877, "s": 29430, "text": null }, { "code": null, "e": 29879, "s": 29877, "text": "5" }, { "code": null, "e": 29998, "s": 29881, "text": "The above-mentioned approach has a time complexity of O(2^n). It is possible to reduce this complexity to O(log n). " }, { "code": null, "e": 30397, "s": 29998, "text": "Method 2 – (Efficient Solution)It is clear with little observation that performing an increment of 1 or a decrement of 1 on an odd number can result in an even number, one of it divisible by 4. For an odd number, the only operation possible is either an increment of 1 or a decrement of 1, most certainly one operation will result in a number divisible by four, this is the optimal choice clearly. " }, { "code": null, "e": 30712, "s": 30397, "text": "Algorithm : \n1. Initialize count = 0\n2. While number is greater than one perform following steps - \n Perform count++ for each iteration\n if num % 2 == 0, perform division\n else if num % 4 == 3, perform increment\n else perform decrement (as odd % 4 is either 1 or 3)\n3. return count;" }, { "code": null, "e": 30716, "s": 30712, "text": "C++" }, { "code": null, "e": 30721, "s": 30716, "text": "Java" }, { "code": null, "e": 30729, "s": 30721, "text": "Python3" }, { "code": null, "e": 30732, "s": 30729, "text": "C#" }, { "code": null, "e": 30743, "s": 30732, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // driver code int main(){ int n = 15; // Function call cout << countSteps(n) << \"\\n\"; return 0;}", "e": 31328, "s": 30743, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ public static int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // Driver codepublic static void main(String[] args){ int n = 15; // Function call System.out.print(countSteps(n));}} // This code is contributed by paragpallavsingh", "e": 32062, "s": 31328, "text": null }, { "code": "# Python3 program for the above approachdef countSteps(n): count = 0 while (n > 1): count += 1 # num even, divide by 2 if (n % 2 == 0): n //= 2 # num odd, n%4 == 1 # or n==3(special edge case), # decrement by 1 elif (n % 4 == 1 or n == 3): n -= 1 # num odd, n%4 == 3, increment by 1 else: n += 1 return count # Driver codeif __name__ == \"__main__\": n = 15 # Function call print(countSteps(n)) # This code is contributed by chitranayal", "e": 32626, "s": 32062, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ public static int countSteps(int n){ int count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n /= 2; // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count;} // Driver codestatic public void Main (){ int n = 15; // Function call Console.WriteLine(countSteps(n));}} // This code is contributed by avanitrachhadiya2155", "e": 33318, "s": 32626, "text": null }, { "code": "<script>// Javascript program for the above approach function countSteps(n) { let count = 0; while (n > 1) { count++; // num even, divide by 2 if (n % 2 == 0) n = Math.floor(n/2); // num odd, n%4 == 1 // or n==3(special edge case), // decrement by 1 else if (n % 4 == 1||n==3) n -= 1; // num odd, n%4 == 3, increment by 1 else n += 1; } return count; } // Driver code let n = 15; // Function call document.write(countSteps(n)); // This code is contributed by patel2127</script>", "e": 33993, "s": 33318, "text": null }, { "code": null, "e": 33995, "s": 33993, "text": "5" }, { "code": null, "e": 34022, "s": 33995, "text": "Time complexity : O(logN) " }, { "code": null, "e": 34035, "s": 34022, "text": "ankita_saini" }, { "code": null, "e": 34041, "s": 34035, "text": "R_Raj" }, { "code": null, "e": 34055, "s": 34041, "text": "princiraj1992" }, { "code": null, "e": 34066, "s": 34055, "text": "ksucheta19" }, { "code": null, "e": 34072, "s": 34066, "text": "ukasp" }, { "code": null, "e": 34090, "s": 34072, "text": "ParagPallavSingh1" }, { "code": null, "e": 34099, "s": 34090, "text": "rohit768" }, { "code": null, "e": 34120, "s": 34099, "text": "avanitrachhadiya2155" }, { "code": null, "e": 34132, "s": 34120, "text": "unknown2108" }, { "code": null, "e": 34142, "s": 34132, "text": "patel2127" }, { "code": null, "e": 34163, "s": 34142, "text": "Algorithms-Recursion" }, { "code": null, "e": 34170, "s": 34163, "text": "Amazon" }, { "code": null, "e": 34180, "s": 34170, "text": "Recursion" }, { "code": null, "e": 34187, "s": 34180, "text": "Amazon" }, { "code": null, "e": 34197, "s": 34187, "text": "Recursion" }, { "code": null, "e": 34295, "s": 34197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34323, "s": 34295, "text": "Backtracking | Introduction" }, { "code": null, "e": 34396, "s": 34323, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34439, "s": 34396, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 34485, "s": 34439, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 34520, "s": 34485, "text": "Print all subsequences of a string" }, { "code": null, "e": 34591, "s": 34520, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34611, "s": 34591, "text": "Recursive Functions" }, { "code": null, "e": 34643, "s": 34611, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34675, "s": 34643, "text": "Reverse a stack using recursion" } ]
bad_alloc in C++ - GeeksforGeeks
27 Feb, 2018 Prerequisite : Exceptions in C++ Standard C++ contains several built-in exception classes. The most commonly used is bad_alloc, which is thrown if an error occurs when attempting to allocate memory with new. This class is derived from exception. To make use of bad_alloc, one should set up the appropriate try and catch blocks. Here’s a short example, that shows how it’s used : C++ // CPP code for bad_alloc#include <iostream>#include <new> // Driver codeint main () { try { int* gfg_array = new int[100000000]; } catch (std::bad_alloc & ba) { std::cerr << "bad_alloc caught: " << ba.what(); } return 0;} bad_alloc caught: std::bad_alloc cpp-exception 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) Array of Strings in C++ (5 Different Ways to Create) Inline Functions in C++ Convert string to char array in C++
[ { "code": null, "e": 25369, "s": 25341, "text": "\n27 Feb, 2018" }, { "code": null, "e": 25402, "s": 25369, "text": "Prerequisite : Exceptions in C++" }, { "code": null, "e": 25577, "s": 25402, "text": "Standard C++ contains several built-in exception classes. The most commonly used is bad_alloc, which is thrown if an error occurs when attempting to allocate memory with new." }, { "code": null, "e": 25615, "s": 25577, "text": "This class is derived from exception." }, { "code": null, "e": 25748, "s": 25615, "text": "To make use of bad_alloc, one should set up the appropriate try and catch blocks. Here’s a short example, that shows how it’s used :" }, { "code": null, "e": 25752, "s": 25748, "text": "C++" }, { "code": "// CPP code for bad_alloc#include <iostream>#include <new> // Driver codeint main () { try { int* gfg_array = new int[100000000]; } catch (std::bad_alloc & ba) { std::cerr << \"bad_alloc caught: \" << ba.what(); } return 0;}", "e": 25991, "s": 25752, "text": null }, { "code": null, "e": 26025, "s": 25991, "text": "bad_alloc caught: std::bad_alloc\n" }, { "code": null, "e": 26039, "s": 26025, "text": "cpp-exception" }, { "code": null, "e": 26043, "s": 26039, "text": "C++" }, { "code": null, "e": 26047, "s": 26043, "text": "CPP" }, { "code": null, "e": 26145, "s": 26047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26173, "s": 26145, "text": "Operator Overloading in C++" }, { "code": null, "e": 26193, "s": 26173, "text": "Polymorphism in C++" }, { "code": null, "e": 26217, "s": 26193, "text": "Sorting a vector in C++" }, { "code": null, "e": 26250, "s": 26217, "text": "Friend class and function in C++" }, { "code": null, "e": 26294, "s": 26250, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 26319, "s": 26294, "text": "std::string class in C++" }, { "code": null, "e": 26364, "s": 26319, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 26417, "s": 26364, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 26441, "s": 26417, "text": "Inline Functions in C++" } ]
Extract title from a webpage using Python - GeeksforGeeks
04 Apr, 2022 Prerequisite Implementing Web Scraping in Python with BeautifulSoup, Python Urllib Module, Tools for Web Scraping In this article, we are going to write python scripts to extract the title form the webpage from the given webpage URL. Method 1: bs4 Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests module allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Approach: Import the modules Make requests instance and pass into URL Pass the requests into a Beautifulsoup() function Use the ‘title’ tag to find them all tag (‘title’) Code: Python3 # importing the modulesimport requestsfrom bs4 import BeautifulSoup # target urlurl = 'https://www.geeksforgeeks.org/' # making requests instancereqs = requests.get(url) # using the BeautifulSoup modulesoup = BeautifulSoup(reqs.text, 'html.parser') # displaying the titleprint("Title of the website is : ")for title in soup.find_all('title'): print(title.get_text()) Output: Title of the website is : GeeksforGeeks | A computer science portal for geeks Methods 2: In this method, we will use urllib and Beautifulsoup modules to extract the title of the website. urllib is a package that allows you to access the webpage with the program. Installation: pip install urllib Approach: Import module Read the URL with the request.urlopen(URL). Find the title with soup.title from the HTML document Implementation: Python3 # importing the modulesfrom urllib.request import urlopenfrom bs4 import BeautifulSoup # target urlurl = 'https://www.geeksforgeeks.org/' # using the BeautifulSoup modulesoup = BeautifulSoup(urlopen(url)) # displaying the titleprint("Title of the website is : ")print (soup.title.get_text()) Output: Title of the website is : GeeksforGeeks | A computer science portal for geeks Method 3: In this method, we will use the mechanize module. It is stateful programmatic web browsing in Python. Browse pages programmatically with easy HTML form filling and clicking of links. Installation: pip install mechanize Approach: Import module. Initialize the Browser() instance. Retrieves the webpage content Browser.open(). Display the title with Browser.title() Implementation: Python3 # importing the modulefrom mechanize import Browser # target urlurl = 'https://www.geeksforgeeks.org/' # creating a Browser instancebr = Browser()br.open(url) # displaying the titleprint("Title of the website is : ")print( br.title()) Output: Title of the website is : GeeksforGeeks | A computer science portal for geeks surinderdawra388 Python web-scraping-exercises Python-requests Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26135, "s": 26107, "text": "\n04 Apr, 2022" }, { "code": null, "e": 26249, "s": 26135, "text": "Prerequisite Implementing Web Scraping in Python with BeautifulSoup, Python Urllib Module, Tools for Web Scraping" }, { "code": null, "e": 26369, "s": 26249, "text": "In this article, we are going to write python scripts to extract the title form the webpage from the given webpage URL." }, { "code": null, "e": 26571, "s": 26369, "text": "Method 1: bs4 Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26587, "s": 26571, "text": "pip install bs4" }, { "code": null, "e": 26767, "s": 26587, "text": "requests module allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26788, "s": 26767, "text": "pip install requests" }, { "code": null, "e": 26798, "s": 26788, "text": "Approach:" }, { "code": null, "e": 26817, "s": 26798, "text": "Import the modules" }, { "code": null, "e": 26858, "s": 26817, "text": "Make requests instance and pass into URL" }, { "code": null, "e": 26908, "s": 26858, "text": "Pass the requests into a Beautifulsoup() function" }, { "code": null, "e": 26959, "s": 26908, "text": "Use the ‘title’ tag to find them all tag (‘title’)" }, { "code": null, "e": 26965, "s": 26959, "text": "Code:" }, { "code": null, "e": 26973, "s": 26965, "text": "Python3" }, { "code": "# importing the modulesimport requestsfrom bs4 import BeautifulSoup # target urlurl = 'https://www.geeksforgeeks.org/' # making requests instancereqs = requests.get(url) # using the BeautifulSoup modulesoup = BeautifulSoup(reqs.text, 'html.parser') # displaying the titleprint(\"Title of the website is : \")for title in soup.find_all('title'): print(title.get_text())", "e": 27343, "s": 26973, "text": null }, { "code": null, "e": 27351, "s": 27343, "text": "Output:" }, { "code": null, "e": 27430, "s": 27351, "text": "Title of the website is : \nGeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 27615, "s": 27430, "text": "Methods 2: In this method, we will use urllib and Beautifulsoup modules to extract the title of the website. urllib is a package that allows you to access the webpage with the program." }, { "code": null, "e": 27629, "s": 27615, "text": "Installation:" }, { "code": null, "e": 27648, "s": 27629, "text": "pip install urllib" }, { "code": null, "e": 27658, "s": 27648, "text": "Approach:" }, { "code": null, "e": 27672, "s": 27658, "text": "Import module" }, { "code": null, "e": 27716, "s": 27672, "text": "Read the URL with the request.urlopen(URL)." }, { "code": null, "e": 27770, "s": 27716, "text": "Find the title with soup.title from the HTML document" }, { "code": null, "e": 27786, "s": 27770, "text": "Implementation:" }, { "code": null, "e": 27794, "s": 27786, "text": "Python3" }, { "code": "# importing the modulesfrom urllib.request import urlopenfrom bs4 import BeautifulSoup # target urlurl = 'https://www.geeksforgeeks.org/' # using the BeautifulSoup modulesoup = BeautifulSoup(urlopen(url)) # displaying the titleprint(\"Title of the website is : \")print (soup.title.get_text())", "e": 28086, "s": 27794, "text": null }, { "code": null, "e": 28094, "s": 28086, "text": "Output:" }, { "code": null, "e": 28173, "s": 28094, "text": "Title of the website is : \nGeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 28366, "s": 28173, "text": "Method 3: In this method, we will use the mechanize module. It is stateful programmatic web browsing in Python. Browse pages programmatically with easy HTML form filling and clicking of links." }, { "code": null, "e": 28380, "s": 28366, "text": "Installation:" }, { "code": null, "e": 28402, "s": 28380, "text": "pip install mechanize" }, { "code": null, "e": 28412, "s": 28402, "text": "Approach:" }, { "code": null, "e": 28427, "s": 28412, "text": "Import module." }, { "code": null, "e": 28462, "s": 28427, "text": "Initialize the Browser() instance." }, { "code": null, "e": 28508, "s": 28462, "text": "Retrieves the webpage content Browser.open()." }, { "code": null, "e": 28547, "s": 28508, "text": "Display the title with Browser.title()" }, { "code": null, "e": 28563, "s": 28547, "text": "Implementation:" }, { "code": null, "e": 28571, "s": 28563, "text": "Python3" }, { "code": "# importing the modulefrom mechanize import Browser # target urlurl = 'https://www.geeksforgeeks.org/' # creating a Browser instancebr = Browser()br.open(url) # displaying the titleprint(\"Title of the website is : \")print( br.title())", "e": 28806, "s": 28571, "text": null }, { "code": null, "e": 28814, "s": 28806, "text": "Output:" }, { "code": null, "e": 28893, "s": 28814, "text": "Title of the website is : \nGeeksforGeeks | A computer science portal for geeks" }, { "code": null, "e": 28910, "s": 28893, "text": "surinderdawra388" }, { "code": null, "e": 28940, "s": 28910, "text": "Python web-scraping-exercises" }, { "code": null, "e": 28956, "s": 28940, "text": "Python-requests" }, { "code": null, "e": 28969, "s": 28956, "text": "Web-scraping" }, { "code": null, "e": 28976, "s": 28969, "text": "Python" }, { "code": null, "e": 29074, "s": 28976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29092, "s": 29074, "text": "Python Dictionary" }, { "code": null, "e": 29127, "s": 29092, "text": "Read a file line by line in Python" }, { "code": null, "e": 29159, "s": 29127, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29181, "s": 29159, "text": "Enumerate() in Python" }, { "code": null, "e": 29223, "s": 29181, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29253, "s": 29223, "text": "Iterate over a list in Python" }, { "code": null, "e": 29279, "s": 29253, "text": "Python String | replace()" }, { "code": null, "e": 29308, "s": 29279, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29352, "s": 29308, "text": "Reading and Writing to text files in Python" } ]
XOR Encryption by Shifting Plaintext - GeeksforGeeks
28 Nov, 2021 Here is a cipher algorithm, based on hexadecimal strings that is implemented by XORing the given plaintext, N number of times where N is its length. But, the catch is that every next XOR operation is done after shifting the consecutive plain text entry to the right. A sample operation is shown below : Suppose the password is ‘abcd’ then the hexadecimal text is calculated as a1d0a1d by XORing the password with itself N times i.e. 4 times in this case. Similarly if the password is ‘636f646572’, then 653cae8da8edb426052 is the hexadecimal text. So, the problem statement is to create a decryption algorithm (in any programming language) and deduce the plain text from the given hexadecimal string. Examples : Input : a1d0a1d Output : abcd abcd once coded will return a1d0a1d Input : 653cae8da8edb426052 Output : 636f646572 Approach : The key ingredient in encrypting and decrypting is in the properties of XOR. XOR is a bitwise operation where the result is 0 if the two possible inputs are same but 1 when the inputs are different. The XOR table is given below for reference : An important and useful property of XOR that is widely popular in cryptography is that in case of multiple XORing of numbers (say M numbers), if we know only the M – 1 numbers (one is unknown) along with the XOR result then, we can easily calculate the missing number by XORing the known numbers and the XOR result. This property is discussed with the following hexadecimal numbers : We shall be using the above listed property the most in course of this problem. Now, if we look at the encryption diagram of ‘abcd’ at the base it is just the repeated XORing of the digits. The rightmost digit is d and the rightmost digit of the ‘abcd’ is d as well so the last digit of both plaintext and hexstring is the same. The next digit is 1 which is calculated by XORing the second right digit of abcd and the previous digit i.e. 1 = d ^ c using the property we know the plain text digit can be deduced as d ^ 1 = c. Similarly, the next digit is a which is found by d ^ c ^ b = a. We only need to do this till the half of the hex string as the rest is symmetrical so they are not required. Below is the implementation of above approach : # Implementation in Python 3 # Hex String variablehex_s = '653cae8da8edb426052' # Plain text variableplain = '' # variable to store the XOR# of previous digitsx = 0 l = len(hex_s) # Loop for loop from the end to# the mid section of the stringfor i in range(l - 1, int(l / 2) - 1, -1): # calculation of the plaintext digit y = x^int(hex_s[i], 16) # calculation of XOR chain x = x^y plain = hex(y)[-1] + plain print(plain) 636f646572 Bitwise-XOR cryptography Bit Magic Mathematical Python Strings Strings Mathematical Bit Magic cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) Bits manipulation (Important tactics) Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26061, "s": 26033, "text": "\n28 Nov, 2021" }, { "code": null, "e": 26364, "s": 26061, "text": "Here is a cipher algorithm, based on hexadecimal strings that is implemented by XORing the given plaintext, N number of times where N is its length. But, the catch is that every next XOR operation is done after shifting the consecutive plain text entry to the right. A sample operation is shown below :" }, { "code": null, "e": 26516, "s": 26364, "text": "Suppose the password is ‘abcd’ then the hexadecimal text is calculated as a1d0a1d by XORing the password with itself N times i.e. 4 times in this case." }, { "code": null, "e": 26564, "s": 26516, "text": "Similarly if the password is ‘636f646572’, then" }, { "code": null, "e": 26609, "s": 26564, "text": "653cae8da8edb426052 is the hexadecimal text." }, { "code": null, "e": 26762, "s": 26609, "text": "So, the problem statement is to create a decryption algorithm (in any programming language) and deduce the plain text from the given hexadecimal string." }, { "code": null, "e": 26773, "s": 26762, "text": "Examples :" }, { "code": null, "e": 26889, "s": 26773, "text": "Input : a1d0a1d\nOutput : abcd\nabcd once coded will return a1d0a1d\n\nInput : 653cae8da8edb426052\nOutput : 636f646572\n" }, { "code": null, "e": 27144, "s": 26889, "text": "Approach : The key ingredient in encrypting and decrypting is in the properties of XOR. XOR is a bitwise operation where the result is 0 if the two possible inputs are same but 1 when the inputs are different. The XOR table is given below for reference :" }, { "code": null, "e": 27528, "s": 27144, "text": "An important and useful property of XOR that is widely popular in cryptography is that in case of multiple XORing of numbers (say M numbers), if we know only the M – 1 numbers (one is unknown) along with the XOR result then, we can easily calculate the missing number by XORing the known numbers and the XOR result. This property is discussed with the following hexadecimal numbers :" }, { "code": null, "e": 28226, "s": 27528, "text": "We shall be using the above listed property the most in course of this problem. Now, if we look at the encryption diagram of ‘abcd’ at the base it is just the repeated XORing of the digits. The rightmost digit is d and the rightmost digit of the ‘abcd’ is d as well so the last digit of both plaintext and hexstring is the same. The next digit is 1 which is calculated by XORing the second right digit of abcd and the previous digit i.e. 1 = d ^ c using the property we know the plain text digit can be deduced as d ^ 1 = c. Similarly, the next digit is a which is found by d ^ c ^ b = a. We only need to do this till the half of the hex string as the rest is symmetrical so they are not required." }, { "code": null, "e": 28274, "s": 28226, "text": "Below is the implementation of above approach :" }, { "code": "# Implementation in Python 3 # Hex String variablehex_s = '653cae8da8edb426052' # Plain text variableplain = '' # variable to store the XOR# of previous digitsx = 0 l = len(hex_s) # Loop for loop from the end to# the mid section of the stringfor i in range(l - 1, int(l / 2) - 1, -1): # calculation of the plaintext digit y = x^int(hex_s[i], 16) # calculation of XOR chain x = x^y plain = hex(y)[-1] + plain print(plain)", "e": 28732, "s": 28274, "text": null }, { "code": null, "e": 28744, "s": 28732, "text": "636f646572\n" }, { "code": null, "e": 28756, "s": 28744, "text": "Bitwise-XOR" }, { "code": null, "e": 28769, "s": 28756, "text": "cryptography" }, { "code": null, "e": 28779, "s": 28769, "text": "Bit Magic" }, { "code": null, "e": 28792, "s": 28779, "text": "Mathematical" }, { "code": null, "e": 28799, "s": 28792, "text": "Python" }, { "code": null, "e": 28807, "s": 28799, "text": "Strings" }, { "code": null, "e": 28815, "s": 28807, "text": "Strings" }, { "code": null, "e": 28828, "s": 28815, "text": "Mathematical" }, { "code": null, "e": 28838, "s": 28828, "text": "Bit Magic" }, { "code": null, "e": 28851, "s": 28838, "text": "cryptography" }, { "code": null, "e": 28949, "s": 28851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28979, "s": 28949, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 29025, "s": 28979, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 29076, "s": 29025, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 29119, "s": 29076, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 29157, "s": 29119, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 29187, "s": 29157, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29247, "s": 29187, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29262, "s": 29247, "text": "C++ Data Types" }, { "code": null, "e": 29305, "s": 29262, "text": "Set in C++ Standard Template Library (STL)" } ]
C program to create a pendulum clock using graphics - GeeksforGeeks
23 Apr, 2021 In this article, it is discussed how to design a Pendulum Clock in the C programming language using Graphics. Approach: Create two rectangles, one inside the other, using the rectangle() function to act as the outer outline of the clock & the other is the inner outline of the clock. Color the space between the two rectangles brown using setfillstyle() and floodfill() functions Implement a circle inside the inner rectangle using the circle() function Color all other parts leaving the circle with dark gray using setfillstyle() and floodfill() functions. In the circle, insert all the digits using settextstyle() and outtextxy() functions. Calculate the coordinates of the digits. Implement the pendulum with two lines by using the line() function & another circle by using the circle() function which will act as the bob. Color all of them black using the setfillstyle() and floodfill() functions again. Implement hour, minute & second hands by using the line() function. Color the objects individually by using the setcolor() function. Below is the implementation of the above approach: C // C program toc draw the pendulum clock#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver initgraph(&gd, &gm, "C:\\" "turboc3\\bgi"); // Clock Outer Outline rectangle(500, 50, 800, 650); // Clock Inner Outline rectangle(520, 70, 780, 630); // Coloring Middle Part Of // Rectangle With Brown setfillstyle(SOLID_FILL, BROWN); floodfill(505, 55, 15); // Clock Outline circle(650, 200, 130); circle(650, 200, 3); // Coloring all the parts Of the // clock except the circle with // Darkgray setfillstyle(SOLID_FILL, DARKGRAY); floodfill(525, 355, 15); floodfill(522, 72, 15); floodfill(768, 72, 15); // Inserting Digits settextstyle(6, 0, 3); outtextxy(697, 100, "01"); outtextxy(730, 140, "02"); outtextxy(742, 190, "03"); outtextxy(721, 240, "04"); outtextxy(690, 280, "05"); outtextxy(630, 300, "06"); outtextxy(578, 280, "07"); outtextxy(540, 240, "08"); outtextxy(530, 190, "09"); outtextxy(537, 140, "10"); outtextxy(569, 100, "11"); outtextxy(630, 80, "12"); // Left Line Of Pendulum line(645, 328, 645, 528); // Right Line Of Pendulum line(655, 328, 655, 528); // Pendulum Bob circle(650, 546, 20); // Coloring Line & Bob With Black setfillstyle(SOLID_FILL, BLACK); floodfill(652, 544, 15); floodfill(647, 330, 15); // Creating the Hour Hand // & Color Blue setcolor(BLUE); line(647, 197, 600, 170); // Creating Minute Hand // & Color Yellow setcolor(YELLOW); line(653, 200, 730, 170); // Creating Second Hand and the // Color Red setcolor(RED); line(650, 203, 630, 290); // Hold the screen for a while getch(); // Close the initialized gdriver closegraph();} Output: c-graphics computer-graphics C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25453, "s": 25425, "text": "\n23 Apr, 2021" }, { "code": null, "e": 25563, "s": 25453, "text": "In this article, it is discussed how to design a Pendulum Clock in the C programming language using Graphics." }, { "code": null, "e": 25573, "s": 25563, "text": "Approach:" }, { "code": null, "e": 25737, "s": 25573, "text": "Create two rectangles, one inside the other, using the rectangle() function to act as the outer outline of the clock & the other is the inner outline of the clock." }, { "code": null, "e": 25833, "s": 25737, "text": "Color the space between the two rectangles brown using setfillstyle() and floodfill() functions" }, { "code": null, "e": 25907, "s": 25833, "text": "Implement a circle inside the inner rectangle using the circle() function" }, { "code": null, "e": 26011, "s": 25907, "text": "Color all other parts leaving the circle with dark gray using setfillstyle() and floodfill() functions." }, { "code": null, "e": 26096, "s": 26011, "text": "In the circle, insert all the digits using settextstyle() and outtextxy() functions." }, { "code": null, "e": 26137, "s": 26096, "text": "Calculate the coordinates of the digits." }, { "code": null, "e": 26279, "s": 26137, "text": "Implement the pendulum with two lines by using the line() function & another circle by using the circle() function which will act as the bob." }, { "code": null, "e": 26361, "s": 26279, "text": "Color all of them black using the setfillstyle() and floodfill() functions again." }, { "code": null, "e": 26429, "s": 26361, "text": "Implement hour, minute & second hands by using the line() function." }, { "code": null, "e": 26494, "s": 26429, "text": "Color the objects individually by using the setcolor() function." }, { "code": null, "e": 26545, "s": 26494, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26547, "s": 26545, "text": "C" }, { "code": "// C program toc draw the pendulum clock#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver initgraph(&gd, &gm, \"C:\\\\\" \"turboc3\\\\bgi\"); // Clock Outer Outline rectangle(500, 50, 800, 650); // Clock Inner Outline rectangle(520, 70, 780, 630); // Coloring Middle Part Of // Rectangle With Brown setfillstyle(SOLID_FILL, BROWN); floodfill(505, 55, 15); // Clock Outline circle(650, 200, 130); circle(650, 200, 3); // Coloring all the parts Of the // clock except the circle with // Darkgray setfillstyle(SOLID_FILL, DARKGRAY); floodfill(525, 355, 15); floodfill(522, 72, 15); floodfill(768, 72, 15); // Inserting Digits settextstyle(6, 0, 3); outtextxy(697, 100, \"01\"); outtextxy(730, 140, \"02\"); outtextxy(742, 190, \"03\"); outtextxy(721, 240, \"04\"); outtextxy(690, 280, \"05\"); outtextxy(630, 300, \"06\"); outtextxy(578, 280, \"07\"); outtextxy(540, 240, \"08\"); outtextxy(530, 190, \"09\"); outtextxy(537, 140, \"10\"); outtextxy(569, 100, \"11\"); outtextxy(630, 80, \"12\"); // Left Line Of Pendulum line(645, 328, 645, 528); // Right Line Of Pendulum line(655, 328, 655, 528); // Pendulum Bob circle(650, 546, 20); // Coloring Line & Bob With Black setfillstyle(SOLID_FILL, BLACK); floodfill(652, 544, 15); floodfill(647, 330, 15); // Creating the Hour Hand // & Color Blue setcolor(BLUE); line(647, 197, 600, 170); // Creating Minute Hand // & Color Yellow setcolor(YELLOW); line(653, 200, 730, 170); // Creating Second Hand and the // Color Red setcolor(RED); line(650, 203, 630, 290); // Hold the screen for a while getch(); // Close the initialized gdriver closegraph();}", "e": 28430, "s": 26547, "text": null }, { "code": null, "e": 28438, "s": 28430, "text": "Output:" }, { "code": null, "e": 28449, "s": 28438, "text": "c-graphics" }, { "code": null, "e": 28467, "s": 28449, "text": "computer-graphics" }, { "code": null, "e": 28478, "s": 28467, "text": "C Language" }, { "code": null, "e": 28489, "s": 28478, "text": "C Programs" }, { "code": null, "e": 28587, "s": 28489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28625, "s": 28587, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28651, "s": 28625, "text": "Exception Handling in C++" }, { "code": null, "e": 28671, "s": 28651, "text": "Multithreading in C" }, { "code": null, "e": 28693, "s": 28671, "text": "'this' pointer in C++" }, { "code": null, "e": 28734, "s": 28693, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28747, "s": 28734, "text": "Strings in C" }, { "code": null, "e": 28788, "s": 28747, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28829, "s": 28788, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28864, "s": 28829, "text": "Header files in C/C++ and its uses" } ]
Python | Count occurrences of an element in a Tuple - GeeksforGeeks
17 Jul, 2020 In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using simple approach and how inbuilt functions can be used to solve this problem. Examples: Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2) Input : 4 Output : 0 times Input : 10 Output : 3 times Input : 8 Output : 4 times Method 1(Simple Approach):We keep a counter that keeps on increasing if the required element is found in the tuple. # Program to count the number of times an element# Present in the listdef countX(tup, x): count = 0 for ele in tup: if (ele == x): count = count + 1 return count # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(countX(tup, enq))print(countX(tup, enq1))print(countX(tup, enq2)) Output: 0 times 3 times 4 times Method 2(Using count()):The idea is to use method count() to count number of occurrences. # Program to count the number of times an element# Present in the list# Count function is useddef Count(tup, en): return tup.count(en) # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(Count(tup, enq), "times")print(Count(tup, enq1), "times")print(Count(tup, enq2), "times") Output: 0 times 3 times 4 times python-tuple 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": 26217, "s": 26189, "text": "\n17 Jul, 2020" }, { "code": null, "e": 26498, "s": 26217, "text": "In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using simple approach and how inbuilt functions can be used to solve this problem." }, { "code": null, "e": 26508, "s": 26498, "text": "Examples:" }, { "code": null, "e": 26642, "s": 26508, "text": "Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)\n\nInput : 4\nOutput : 0 times\n\nInput : 10\nOutput : 3 times\n\nInput : 8\nOutput : 4 times\n" }, { "code": null, "e": 26758, "s": 26642, "text": "Method 1(Simple Approach):We keep a counter that keeps on increasing if the required element is found in the tuple." }, { "code": "# Program to count the number of times an element# Present in the listdef countX(tup, x): count = 0 for ele in tup: if (ele == x): count = count + 1 return count # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(countX(tup, enq))print(countX(tup, enq1))print(countX(tup, enq2))", "e": 27104, "s": 26758, "text": null }, { "code": null, "e": 27112, "s": 27104, "text": "Output:" }, { "code": null, "e": 27137, "s": 27112, "text": "0 times\n3 times\n4 times\n" }, { "code": null, "e": 27227, "s": 27137, "text": "Method 2(Using count()):The idea is to use method count() to count number of occurrences." }, { "code": "# Program to count the number of times an element# Present in the list# Count function is useddef Count(tup, en): return tup.count(en) # Driver Codetup = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)enq = 4enq1 = 10enq2 = 8print(Count(tup, enq), \"times\")print(Count(tup, enq1), \"times\")print(Count(tup, enq2), \"times\")", "e": 27545, "s": 27227, "text": null }, { "code": null, "e": 27553, "s": 27545, "text": "Output:" }, { "code": null, "e": 27578, "s": 27553, "text": "0 times\n3 times\n4 times\n" }, { "code": null, "e": 27591, "s": 27578, "text": "python-tuple" }, { "code": null, "e": 27598, "s": 27591, "text": "Python" }, { "code": null, "e": 27696, "s": 27598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27714, "s": 27696, "text": "Python Dictionary" }, { "code": null, "e": 27749, "s": 27714, "text": "Read a file line by line in Python" }, { "code": null, "e": 27781, "s": 27749, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27803, "s": 27781, "text": "Enumerate() in Python" }, { "code": null, "e": 27845, "s": 27803, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27875, "s": 27845, "text": "Iterate over a list in Python" }, { "code": null, "e": 27901, "s": 27875, "text": "Python String | replace()" }, { "code": null, "e": 27930, "s": 27901, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27974, "s": 27930, "text": "Reading and Writing to text files in Python" } ]
HTML | <textarea> required Attribute - GeeksforGeeks
06 May, 2019 The HTML <textarea> required Attribute is a Boolean attribute which is used to specify that the <textarea> element must be filled out before submitting the Form. Syntax: <textarea required> Example: This Example illustrates the use of required attribute in Textarea Element. <!DOCTYPE html><html> <head> <title>required Attribute</title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>HTML Textarea required attribute </h2> <form action="#"> <textarea rows="7" cols="50" name="comment" required></textarea> <input type="submit"> </form></body> </html> output: Supported Browsers: The browser supported by HTML Textarea required Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes 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 ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form HTML Cheat Sheet - A Basic Guide to HTML Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25755, "s": 25727, "text": "\n06 May, 2019" }, { "code": null, "e": 25917, "s": 25755, "text": "The HTML <textarea> required Attribute is a Boolean attribute which is used to specify that the <textarea> element must be filled out before submitting the Form." }, { "code": null, "e": 25925, "s": 25917, "text": "Syntax:" }, { "code": null, "e": 25946, "s": 25925, "text": "<textarea required> " }, { "code": null, "e": 26031, "s": 25946, "text": "Example: This Example illustrates the use of required attribute in Textarea Element." }, { "code": "<!DOCTYPE html><html> <head> <title>required Attribute</title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>HTML Textarea required attribute </h2> <form action=\"#\"> <textarea rows=\"7\" cols=\"50\" name=\"comment\" required></textarea> <input type=\"submit\"> </form></body> </html>", "e": 26562, "s": 26031, "text": null }, { "code": null, "e": 26570, "s": 26562, "text": "output:" }, { "code": null, "e": 26666, "s": 26570, "text": "Supported Browsers: The browser supported by HTML Textarea required Attribute are listed below:" }, { "code": null, "e": 26680, "s": 26666, "text": "Google Chrome" }, { "code": null, "e": 26698, "s": 26680, "text": "Internet Explorer" }, { "code": null, "e": 26706, "s": 26698, "text": "Firefox" }, { "code": null, "e": 26712, "s": 26706, "text": "Opera" }, { "code": null, "e": 26849, "s": 26712, "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": 26865, "s": 26849, "text": "HTML-Attributes" }, { "code": null, "e": 26870, "s": 26865, "text": "HTML" }, { "code": null, "e": 26887, "s": 26870, "text": "Web Technologies" }, { "code": null, "e": 26892, "s": 26887, "text": "HTML" }, { "code": null, "e": 26990, "s": 26892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27038, "s": 26990, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27062, "s": 27038, "text": "REST API (Introduction)" }, { "code": null, "e": 27112, "s": 27062, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27162, "s": 27112, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27203, "s": 27162, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27243, "s": 27203, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27276, "s": 27243, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27321, "s": 27276, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27364, "s": 27321, "text": "How to fetch data from an API in ReactJS ?" } ]
Export and Import data in Cassandra - GeeksforGeeks
02 Jan, 2020 Prerequisite – CassandraIn this article, we are going to discuss how we can export and import data through cqlsh query.Let’s discuss one by one. First, we are going to create table namely as Data in which id, firstname, lastname are the fields for sample exercise.Let’s have a look. Table name: Data CREATE TABLE Data ( id UUID PRIMARY KEY, firstname text, lastname text ); Now, we are going to insert some data to export and import data for sample exercise. let’s have a look. INSERT INTO Data (id, firstname, lastname ) VALUES (3b6441dd-3f90-4c93-8f61-abcfa3a510e1, 'Ashish', 'Rana'); INSERT INTO Data (id, firstname, lastname) VALUES (3b6442dd-bc0d-4157-a80f-abcfa3a510e2, 'Amit', 'Gupta'); INSERT INTO Data (id, firstname, lastname) VALUES (3b6443dd-d358-4d99-b900-abcfa3a510e3, 'Ashish', 'Gupta'); INSERT INTO Data (id, firstname, lastname) VALUES (3b6444dd-4860-49d6-9a4b-abcfa3a510e4, 'Dhruv', 'Gupta'); INSERT INTO Data (id, firstname, lastname) VALUES (3b6445dd-e68e-48d9-a5f8-abcfa3a510e5, 'Harsh', 'Vardhan'); INSERT INTO Data (id, firstname, lastname) VALUES (3b6446dd-eb95-4bb4-8685-abcfa3a510e6, 'Shivang', 'Rana'); Now, we are going to Export Data used the following cqlsh query given below. let’s have a look. cqlsh>COPY Data(id, firstname, lastname) TO 'AshishRana\Desktop\Data.csv' WITH HEADER = TRUE; The CSV file is created: Using 7 child processes Starting copy of Data with columns [id, firstname, lastname]. Processed: 6 rows; Rate: 20 rows/s; Avg. rate: 30 rows/s 6 rows exported to 1 files in 0.213 seconds. Now, we are going to delete data from table ‘Data’ to import again from CSV file which is already has been created. truncate Data; Now, here we are going to import data again. To import Data used the following cqlsh query given below. COPY Data (id, firstname, lastname) FROM 'AshishRana\Desktop\Data.csv' WITH HEADER = TRUE; The rows are imported: Using 7 child processes Starting copy of Data with columns [id, firstname, lastname]. Processed: 6 rows; Rate: 10 rows/s; Avg. rate: 14 rows/s 6 rows imported from 1 files in 0.423 seconds (0 skipped). To verify the results whether it is successfully imported or not. let’s have a look. SELECT * FROM Data; Output: To copy a specific rows of a table used the following cqlsh query given below.First, export data from table and then truncate after these two steps follow these steps given below. COPY Data FROM STDIN; After executing above cqlsh query the line prompt changes to [copy] let’s have a look. Using 7 child processes Starting copy of cluster1.Data with columns [id, firstname, lastname]. [Use . on a line by itself to end input] [copy] Now, insert the row value of table which you want to import. [copy] 3b6441dd-3f90-4c93-8f61-abcfa3a510e1, 'Ashish', 'Rana' [copy] . // keep it in mind at the end insert the period After successfully executed above given cqlsh query will give you the following results given below. let’s have a look. Processed: 1 rows; Rate: 0 rows/s; Avg. rate: 0 rows/s 1 rows imported from 1 files in 36.991 seconds (0 skipped). Now, let verify the results. SELECT * FROM Data; Output: Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Introduction of B-Tree CTE in SQL SQL Trigger | Student Database Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 Difference between DDL and DML in DBMS SQL | Views
[ { "code": null, "e": 25325, "s": 25297, "text": "\n02 Jan, 2020" }, { "code": null, "e": 25470, "s": 25325, "text": "Prerequisite – CassandraIn this article, we are going to discuss how we can export and import data through cqlsh query.Let’s discuss one by one." }, { "code": null, "e": 25608, "s": 25470, "text": "First, we are going to create table namely as Data in which id, firstname, lastname are the fields for sample exercise.Let’s have a look." }, { "code": null, "e": 25625, "s": 25608, "text": "Table name: Data" }, { "code": null, "e": 25709, "s": 25625, "text": "CREATE TABLE Data ( \n id UUID PRIMARY KEY, \n firstname text,\n lastname text \n); " }, { "code": null, "e": 25813, "s": 25709, "text": "Now, we are going to insert some data to export and import data for sample exercise. let’s have a look." }, { "code": null, "e": 26479, "s": 25813, "text": "INSERT INTO Data (id, firstname, lastname ) \nVALUES (3b6441dd-3f90-4c93-8f61-abcfa3a510e1, 'Ashish', 'Rana');\n\nINSERT INTO Data (id, firstname, lastname) \nVALUES (3b6442dd-bc0d-4157-a80f-abcfa3a510e2, 'Amit', 'Gupta');\n\nINSERT INTO Data (id, firstname, lastname) \nVALUES (3b6443dd-d358-4d99-b900-abcfa3a510e3, 'Ashish', 'Gupta');\n\nINSERT INTO Data (id, firstname, lastname) \nVALUES (3b6444dd-4860-49d6-9a4b-abcfa3a510e4, 'Dhruv', 'Gupta');\n\nINSERT INTO Data (id, firstname, lastname) \nVALUES (3b6445dd-e68e-48d9-a5f8-abcfa3a510e5, 'Harsh', 'Vardhan');\n\nINSERT INTO Data (id, firstname, lastname) \nVALUES (3b6446dd-eb95-4bb4-8685-abcfa3a510e6, 'Shivang', 'Rana'); " }, { "code": null, "e": 26575, "s": 26479, "text": "Now, we are going to Export Data used the following cqlsh query given below. let’s have a look." }, { "code": null, "e": 26671, "s": 26575, "text": "cqlsh>COPY Data(id, firstname, lastname) \nTO 'AshishRana\\Desktop\\Data.csv' WITH HEADER = TRUE; " }, { "code": null, "e": 26696, "s": 26671, "text": "The CSV file is created:" }, { "code": null, "e": 26721, "s": 26696, "text": "Using 7 child processes " }, { "code": null, "e": 26783, "s": 26721, "text": "Starting copy of Data with columns [id, firstname, lastname]." }, { "code": null, "e": 26886, "s": 26783, "text": "Processed: 6 rows; Rate: 20 rows/s; Avg. rate: 30 rows/s\n6 rows exported to 1 files in 0.213 seconds. " }, { "code": null, "e": 27002, "s": 26886, "text": "Now, we are going to delete data from table ‘Data’ to import again from CSV file which is already has been created." }, { "code": null, "e": 27018, "s": 27002, "text": "truncate Data; " }, { "code": null, "e": 27122, "s": 27018, "text": "Now, here we are going to import data again. To import Data used the following cqlsh query given below." }, { "code": null, "e": 27215, "s": 27122, "text": "COPY Data (id, firstname, lastname)\nFROM 'AshishRana\\Desktop\\Data.csv' \nWITH HEADER = TRUE; " }, { "code": null, "e": 27238, "s": 27215, "text": "The rows are imported:" }, { "code": null, "e": 27263, "s": 27238, "text": "Using 7 child processes " }, { "code": null, "e": 27325, "s": 27263, "text": "Starting copy of Data with columns [id, firstname, lastname]." }, { "code": null, "e": 27442, "s": 27325, "text": "Processed: 6 rows; Rate: 10 rows/s; Avg. rate: 14 rows/s\n6 rows imported from 1 files in 0.423 seconds (0 skipped). " }, { "code": null, "e": 27527, "s": 27442, "text": "To verify the results whether it is successfully imported or not. let’s have a look." }, { "code": null, "e": 27549, "s": 27527, "text": "SELECT * \nFROM Data; " }, { "code": null, "e": 27557, "s": 27549, "text": "Output:" }, { "code": null, "e": 27737, "s": 27557, "text": "To copy a specific rows of a table used the following cqlsh query given below.First, export data from table and then truncate after these two steps follow these steps given below." }, { "code": null, "e": 27760, "s": 27737, "text": "COPY Data FROM STDIN; " }, { "code": null, "e": 27847, "s": 27760, "text": "After executing above cqlsh query the line prompt changes to [copy] let’s have a look." }, { "code": null, "e": 27872, "s": 27847, "text": "Using 7 child processes " }, { "code": null, "e": 27943, "s": 27872, "text": "Starting copy of cluster1.Data with columns [id, firstname, lastname]." }, { "code": null, "e": 27992, "s": 27943, "text": "[Use . on a line by itself to end input]\n[copy] " }, { "code": null, "e": 28053, "s": 27992, "text": "Now, insert the row value of table which you want to import." }, { "code": null, "e": 28176, "s": 28053, "text": "[copy] 3b6441dd-3f90-4c93-8f61-abcfa3a510e1, 'Ashish', 'Rana'\n[copy] . // keep it in mind at the end insert the period " }, { "code": null, "e": 28296, "s": 28176, "text": "After successfully executed above given cqlsh query will give you the following results given below. let’s have a look." }, { "code": null, "e": 28412, "s": 28296, "text": "Processed: 1 rows; Rate: 0 rows/s; Avg. rate: 0 rows/s\n1 rows imported from 1 files in 36.991 seconds (0 skipped). " }, { "code": null, "e": 28441, "s": 28412, "text": "Now, let verify the results." }, { "code": null, "e": 28463, "s": 28441, "text": "SELECT * \nFROM Data; " }, { "code": null, "e": 28471, "s": 28463, "text": "Output:" }, { "code": null, "e": 28478, "s": 28471, "text": "Apache" }, { "code": null, "e": 28483, "s": 28478, "text": "DBMS" }, { "code": null, "e": 28488, "s": 28483, "text": "DBMS" }, { "code": null, "e": 28586, "s": 28488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28610, "s": 28586, "text": "SQL Interview Questions" }, { "code": null, "e": 28633, "s": 28610, "text": "Introduction of B-Tree" }, { "code": null, "e": 28644, "s": 28633, "text": "CTE in SQL" }, { "code": null, "e": 28675, "s": 28644, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 28728, "s": 28675, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 28762, "s": 28728, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 28787, "s": 28762, "text": "Introduction of ER Model" }, { "code": null, "e": 28845, "s": 28787, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 28884, "s": 28845, "text": "Difference between DDL and DML in DBMS" } ]
scipy stats.gamma() | Python - GeeksforGeeks
27 Mar, 2019 scipy.stats.gamma() is an gamma continuous random variable that is defined with a standard format and some shape parameters to complete its specification. Parameters :-> q : lower and upper tail probability-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> a : shape parameters-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : gamma continuous random variable Code #1 : Creating gamma continuous random variable from scipy.stats import gamma numargs = gamma .numargs[a] = [0.7, ] * numargsrv = gamma (a) print ("RV : \n", rv) Output : RV : <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D57997F60> Code #2 : generalized gamma random variates. import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = gamma.rvs(a, scale = 2, size = 10)print ("Random Variates : \n", R) # PDFR = gamma.pdf(a, quantile, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0.01601209 0.05164555 1.22072489 0.53476245 0.11529018 0.16966403 0.59198231 0.71995529 0.86063603 3.81492177] Probability Distribution : [0.00710916 0.07919869 0.15097014 0.21974949 0.28337498 0.34020629 0.38910556 0.42939763 0.46081639 0.48344302] Code #3 : Graphical Representation. import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102 2.93877551 3. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = gamma.pdf(x, a, 1, 3)y2 = gamma.pdf(x, a, 1, 4)plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25489, "s": 25461, "text": "\n27 Mar, 2019" }, { "code": null, "e": 25644, "s": 25489, "text": "scipy.stats.gamma() is an gamma continuous random variable that is defined with a standard format and some shape parameters to complete its specification." }, { "code": null, "e": 26043, "s": 25644, "text": "Parameters :-> q : lower and upper tail probability-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> a : shape parameters-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26086, "s": 26043, "text": "Results : gamma continuous random variable" }, { "code": null, "e": 26138, "s": 26086, "text": "Code #1 : Creating gamma continuous random variable" }, { "code": "from scipy.stats import gamma numargs = gamma .numargs[a] = [0.7, ] * numargsrv = gamma (a) print (\"RV : \\n\", rv) ", "e": 26256, "s": 26138, "text": null }, { "code": null, "e": 26265, "s": 26256, "text": "Output :" }, { "code": null, "e": 26348, "s": 26265, "text": "RV : \n <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D57997F60>\n" }, { "code": null, "e": 26393, "s": 26348, "text": "Code #2 : generalized gamma random variates." }, { "code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = gamma.rvs(a, scale = 2, size = 10)print (\"Random Variates : \\n\", R) # PDFR = gamma.pdf(a, quantile, loc = 0, scale = 1)print (\"\\nProbability Distribution : \\n\", R)", "e": 26636, "s": 26393, "text": null }, { "code": null, "e": 26645, "s": 26636, "text": "Output :" }, { "code": null, "e": 26921, "s": 26645, "text": "Random Variates : \n [0.01601209 0.05164555 1.22072489 0.53476245 0.11529018 0.16966403\n 0.59198231 0.71995529 0.86063603 3.81492177]\n\nProbability Distribution : \n [0.00710916 0.07919869 0.15097014 0.21974949 0.28337498 0.34020629\n 0.38910556 0.42939763 0.46081639 0.48344302]" }, { "code": null, "e": 26957, "s": 26921, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))", "e": 27157, "s": 26957, "text": null }, { "code": null, "e": 27166, "s": 27157, "text": "Output :" }, { "code": null, "e": 27742, "s": 27166, "text": "Distribution : \n [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245\n 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939\n 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633\n 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327\n 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102\n 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714\n 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408\n 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102\n 2.93877551 3. ]" }, { "code": null, "e": 27781, "s": 27742, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = gamma.pdf(x, a, 1, 3)y2 = gamma.pdf(x, a, 1, 4)plt.plot(x, y1, \"*\", x, y2, \"r--\")", "e": 27977, "s": 27781, "text": null }, { "code": null, "e": 27986, "s": 27977, "text": "Output :" }, { "code": null, "e": 28015, "s": 27986, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28028, "s": 28015, "text": "Python-scipy" }, { "code": null, "e": 28035, "s": 28028, "text": "Python" }, { "code": null, "e": 28133, "s": 28035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28151, "s": 28133, "text": "Python Dictionary" }, { "code": null, "e": 28186, "s": 28151, "text": "Read a file line by line in Python" }, { "code": null, "e": 28218, "s": 28186, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28240, "s": 28218, "text": "Enumerate() in Python" }, { "code": null, "e": 28282, "s": 28240, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28312, "s": 28282, "text": "Iterate over a list in Python" }, { "code": null, "e": 28338, "s": 28312, "text": "Python String | replace()" }, { "code": null, "e": 28367, "s": 28338, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28411, "s": 28367, "text": "Reading and Writing to text files in Python" } ]
Python - Concatenate Dictionary string values - GeeksforGeeks
23 Jan, 2020 Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss string concatenation of like key values and ways to solve it in this article. Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line. # Python3 code to demonstrate working of# Concatenate Dictionary string values# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using dictionary comprehension + keys()# Concatenate Dictionary string valuesres = {key: test_dict1[key] + test_dict2.get(key, '') for key in test_dict1.keys()} # printing result print("The string concatenation of dictionary is : " + str(res)) The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'} The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'} The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'} Method #2 : Using Counter() + “+” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the plus operator can perform the task of concatenation. # Python3 code to demonstrate working of# Concatenate Dictionary string values# Using Counter() + "+" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using Counter() + "+" operator# Concatenate Dictionary string valuestemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] + temp2[key] for key in temp1}) # printing result print("The string concatenation of dictionary is : " + str(dict(res))) The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'} The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'} The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'} Python dictionary-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26165, "s": 26137, "text": "\n23 Jan, 2020" }, { "code": null, "e": 26474, "s": 26165, "text": "Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss string concatenation of like key values and ways to solve it in this article." }, { "code": null, "e": 26704, "s": 26474, "text": "Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line." }, { "code": "# Python3 code to demonstrate working of# Concatenate Dictionary string values# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using dictionary comprehension + keys()# Concatenate Dictionary string valuesres = {key: test_dict1[key] + test_dict2.get(key, '') for key in test_dict1.keys()} # printing result print(\"The string concatenation of dictionary is : \" + str(res))", "e": 27348, "s": 26704, "text": null }, { "code": null, "e": 27563, "s": 27348, "text": "The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}\nThe original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}\nThe string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}\n" }, { "code": null, "e": 27816, "s": 27565, "text": "Method #2 : Using Counter() + “+” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the plus operator can perform the task of concatenation." }, { "code": "# Python3 code to demonstrate working of# Concatenate Dictionary string values# Using Counter() + \"+\" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using Counter() + \"+\" operator# Concatenate Dictionary string valuestemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] + temp2[key] for key in temp1}) # printing result print(\"The string concatenation of dictionary is : \" + str(dict(res)))", "e": 28514, "s": 27816, "text": null }, { "code": null, "e": 28729, "s": 28514, "text": "The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}\nThe original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}\nThe string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}\n" }, { "code": null, "e": 28756, "s": 28729, "text": "Python dictionary-programs" }, { "code": null, "e": 28763, "s": 28756, "text": "Python" }, { "code": null, "e": 28779, "s": 28763, "text": "Python Programs" }, { "code": null, "e": 28877, "s": 28779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28895, "s": 28877, "text": "Python Dictionary" }, { "code": null, "e": 28930, "s": 28895, "text": "Read a file line by line in Python" }, { "code": null, "e": 28962, "s": 28930, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28984, "s": 28962, "text": "Enumerate() in Python" }, { "code": null, "e": 29026, "s": 28984, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29069, "s": 29026, "text": "Python program to convert a list to string" }, { "code": null, "e": 29091, "s": 29069, "text": "Defaultdict in Python" }, { "code": null, "e": 29130, "s": 29091, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29176, "s": 29130, "text": "Python | Split string into list of characters" } ]
Java Program for Linear Search - GeeksforGeeks
04 Dec, 2018 Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. Java // Java code for linearly search x in arr[]. If x// is present then return its location, otherwise// return -1class LinearSearch { // This function returns index of element x in arr[] static int search(int arr[], int n, int x) { for (int i = 0; i < n; i++) { // Return the index of the element if the element // is found if (arr[i] == x) return i; } // return -1 if the element is not found return -1; } public static void main(String[] args) { int[] arr = { 3, 4, 1, 7, 5 }; int n = arr.length; int x = 4; int index = search(arr, n, x); if (index == -1) System.out.println("Element is not present in the array"); else System.out.println("Element found at position " + index); }} Element found at position 1 The time complexity of the above algorithm is O(n). Please refer complete article on Linear Search for more details! Java Programs Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String How to Write Data into Excel Sheet using Java? Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26211, "s": 26183, "text": "\n04 Dec, 2018" }, { "code": null, "e": 26311, "s": 26211, "text": "Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]." }, { "code": null, "e": 26316, "s": 26311, "text": "Java" }, { "code": "// Java code for linearly search x in arr[]. If x// is present then return its location, otherwise// return -1class LinearSearch { // This function returns index of element x in arr[] static int search(int arr[], int n, int x) { for (int i = 0; i < n; i++) { // Return the index of the element if the element // is found if (arr[i] == x) return i; } // return -1 if the element is not found return -1; } public static void main(String[] args) { int[] arr = { 3, 4, 1, 7, 5 }; int n = arr.length; int x = 4; int index = search(arr, n, x); if (index == -1) System.out.println(\"Element is not present in the array\"); else System.out.println(\"Element found at position \" + index); }}", "e": 27173, "s": 26316, "text": null }, { "code": null, "e": 27202, "s": 27173, "text": "Element found at position 1\n" }, { "code": null, "e": 27254, "s": 27202, "text": "The time complexity of the above algorithm is O(n)." }, { "code": null, "e": 27319, "s": 27254, "text": "Please refer complete article on Linear Search for more details!" }, { "code": null, "e": 27333, "s": 27319, "text": "Java Programs" }, { "code": null, "e": 27343, "s": 27333, "text": "Searching" }, { "code": null, "e": 27353, "s": 27343, "text": "Searching" }, { "code": null, "e": 27451, "s": 27353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27499, "s": 27451, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 27550, "s": 27499, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 27584, "s": 27550, "text": "Java Program to Write into a File" }, { "code": null, "e": 27622, "s": 27584, "text": "Java Program to Read a File to String" }, { "code": null, "e": 27669, "s": 27622, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 27683, "s": 27669, "text": "Binary Search" }, { "code": null, "e": 27751, "s": 27683, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 27765, "s": 27751, "text": "Linear Search" }, { "code": null, "e": 27813, "s": 27765, "text": "Search an element in a sorted and rotated array" } ]
PyQt5 Label – Accessing opacity level of the Opacity effect - GeeksforGeeks
10 May, 2020 In this article we will see how we can access the opacity level of the opacity effect of the label, the more the value of opacity the label will be clearly the visible and if opacity value is lesser more transparent it will become. By default opacity level is 0.7 and in order to set the opacity we use setOpacity method. In order to do this we use opacity method. Syntax : opacity_effect.opacity(n) Argument : It takes no argument Return : It returns float value Note : Opacity level value ranges from 0 to 1 Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel("Label", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet("QLabel" "{" "border : 2px solid green;" "background : lightgreen;" "}") # creating a opacity effect self.opacity_effect = QGraphicsOpacityEffect() # setting opacity level self.opacity_effect.setOpacity(0.3) # adding opacity effect to the label label.setGraphicsEffect(self.opacity_effect) # result label result = QLabel(self) # setting geometry of the result label result.setGeometry(200, 200, 300, 30) # getting opacity level level = self.opacity_effect.opacity() # setting text to the result label result.setText("Opacity level : " + str(level)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-Label Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26277, "s": 26249, "text": "\n10 May, 2020" }, { "code": null, "e": 26599, "s": 26277, "text": "In this article we will see how we can access the opacity level of the opacity effect of the label, the more the value of opacity the label will be clearly the visible and if opacity value is lesser more transparent it will become. By default opacity level is 0.7 and in order to set the opacity we use setOpacity method." }, { "code": null, "e": 26642, "s": 26599, "text": "In order to do this we use opacity method." }, { "code": null, "e": 26677, "s": 26642, "text": "Syntax : opacity_effect.opacity(n)" }, { "code": null, "e": 26709, "s": 26677, "text": "Argument : It takes no argument" }, { "code": null, "e": 26741, "s": 26709, "text": "Return : It returns float value" }, { "code": null, "e": 26787, "s": 26741, "text": "Note : Opacity level value ranges from 0 to 1" }, { "code": null, "e": 26815, "s": 26787, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating label label = QLabel(\"Label\", self) # setting geometry to the label label.setGeometry(200, 100, 150, 60) # setting alignment to the label label.setAlignment(Qt.AlignCenter) # setting font label.setFont(QFont('Arial', 15)) # setting style sheet of the label label.setStyleSheet(\"QLabel\" \"{\" \"border : 2px solid green;\" \"background : lightgreen;\" \"}\") # creating a opacity effect self.opacity_effect = QGraphicsOpacityEffect() # setting opacity level self.opacity_effect.setOpacity(0.3) # adding opacity effect to the label label.setGraphicsEffect(self.opacity_effect) # result label result = QLabel(self) # setting geometry of the result label result.setGeometry(200, 200, 300, 30) # getting opacity level level = self.opacity_effect.opacity() # setting text to the result label result.setText(\"Opacity level : \" + str(level)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 28615, "s": 26815, "text": null }, { "code": null, "e": 28624, "s": 28615, "text": "Output :" }, { "code": null, "e": 28643, "s": 28624, "text": "Python PyQt5-Label" }, { "code": null, "e": 28654, "s": 28643, "text": "Python-gui" }, { "code": null, "e": 28666, "s": 28654, "text": "Python-PyQt" }, { "code": null, "e": 28673, "s": 28666, "text": "Python" }, { "code": null, "e": 28771, "s": 28673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28789, "s": 28771, "text": "Python Dictionary" }, { "code": null, "e": 28821, "s": 28789, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28856, "s": 28821, "text": "Read a file line by line in Python" }, { "code": null, "e": 28878, "s": 28856, "text": "Enumerate() in Python" }, { "code": null, "e": 28920, "s": 28878, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28950, "s": 28920, "text": "Iterate over a list in Python" }, { "code": null, "e": 28976, "s": 28950, "text": "Python String | replace()" }, { "code": null, "e": 29020, "s": 28976, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29049, "s": 29020, "text": "*args and **kwargs in Python" } ]
Generate all possible combinations of at most X characters from a given array - GeeksforGeeks
22 Apr, 2021 Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ≤ X ≤ N). Examples: Input: N = 3, X = 2, arr[] = {‘a’, ‘b’, ‘a’}Output: a b c bc ca ab cb ac baExplanation: All possible combinations using 1 character is 3 {‘a’, ‘b’, ‘c’}. All possible combinations using 2 characters are {“bc” “ca” “ab” “cb” “ac” “ba”}. Input: N = 3, X = 3, arr[] = {‘d’, ‘a’, ‘b’}Output: d a b da ab bd ad ba db dab dba abd adb bda bad Approach: The given problem can be solved using the Dynamic Programming approach. Follow the below steps to solve the problem: Generate all possible permutations that can be created with 1 character, which is the given array arr[].Store all permutations.Once stored, generate all possible permutations of 2 characters and store them.Once the last step is completed, discard all permutations of a single character.Iteratively, in the same way, calculate the permutations until X is reached. Generate all possible permutations that can be created with 1 character, which is the given array arr[]. Store all permutations. Once stored, generate all possible permutations of 2 characters and store them. Once the last step is completed, discard all permutations of a single character. Iteratively, in the same way, calculate the permutations until X is reached. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate permutations of// at most X elements from array arr[]void differentFlagPermutations(int X, vector<string> arr){ vector<string> ml; ml = arr; for(int i = 0; i < ml.size(); i++) { cout << ml[i] << " "; } int count = ml.size(); // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z vector<string> tmp; // Traverse the array for(int i = 0; i < arr.size(); i++) { for(int k = 0; k < ml.size(); k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.push_back(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.size(); i++) { cout << tmp[i] << " "; } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; }} // Driver Codeint main(){ // Given array vector<string> arr{ "c", "a", "b" }; // Given X int X = 2; differentFlagPermutations(X, arr); return 0;} // This code is contributed by divyeshrabadiya07 // Java program for the above approachimport java.util.*;class GFG{ // Function to generate permutations of// at most X elements from array arr[]static void differentFlagPermutations(int X, String[] arr){ String[] ml = arr; for(int i = 0; i < ml.length; i++) { System.out.print(ml[i] + " "); } int count = ml.length; // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z Vector<String> tmp = new Vector<String>(); // Traverse the array for(int i = 0; i < arr.length; i++) { for(int k = 0; k < ml.length; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.add(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.size(); i++) { System.out.print(tmp.get(i) + " "); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp.toArray(new String[tmp.size()]);; }} // Driver Codepublic static void main(String[] args){ // Given array String []arr = { "c", "a", "b" }; // Given X int X = 2; differentFlagPermutations(X, arr); }} // This code is contributed by shikhasingrajput # Python3 program for the above approach # Function to generate permutations of# at most X elements from array arr[]def differentFlagPermutations(X, arr): ml = arr.copy() print(" ".join(ml), end =" ") count = len(ml) # Traverse all possible lengths for z in range(X-1): # Stores all combinations # of length z tmp = [] # Traverse the array for i in arr: for k in ml: if i not in k: # Generate all # combinations of length z tmp.append(k + i) count += 1 # Print all combinations of length z print(" ".join(tmp), end =" ") # Replace all combinations of length z - 1 # with all combinations of length z ml = tmp # Given arrayarr = ['c', 'a', 'b'] # Given XX = 2 differentFlagPermutations(X, arr) // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate permutations of // at most X elements from array arr[] static void differentFlagPermutations(int X, List<string> arr) { List<string> ml = new List<string>(); ml = arr; for(int i = 0; i < ml.Count; i++) { Console.Write(ml[i] + " "); } int count = ml.Count; // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z List<string> tmp = new List<string>(); // Traverse the array for(int i = 0; i < arr.Count; i++) { for(int k = 0; k < ml.Count; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.Add(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.Count; i++) { Console.Write(tmp[i] + " "); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; } } // Driver code static void Main() { // Given array List<string> arr = new List<string>(new string[] { "c", "a", "b" }); // Given X int X = 2; differentFlagPermutations(X, arr); }} // This code is contributed by divyesh072019 <script> // Javascript program for the above approach // Function to generate permutations of // at most X elements from array arr[] function differentFlagPermutations(X, arr) { let ml = []; ml = arr; for(let i = 0; i < ml.length; i++) { document.write(ml[i] + " "); } let count = ml.length; // Traverse all possible lengths for(let z = 0; z < X - 1; z++) { // Stores all combinations // of length z let tmp = []; // Traverse the array for(let i = 0; i < arr.length; i++) { for(let k = 0; k < ml.length; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.push(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(let i = 0; i < tmp.length; i++) { document.write(tmp[i] + " "); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; } } // Given array let arr = [ "c", "a", "b" ]; // Given X let X = 2; differentFlagPermutations(X, arr); </script> c a b ac bc ca ba cb ab Time Complexity: O(X*N2)Auxiliary Space: O(N2) divyeshrabadiya07 divyesh072019 shikhasingrajput suresh07 permutation Arrays Combinatorial Dynamic Programming Strings Arrays Strings Dynamic Programming permutation Combinatorial 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Combinational Sum Factorial of a large number Count ways to reach the nth stair using step 1, 2 or 3
[ { "code": null, "e": 26413, "s": 26385, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26548, "s": 26413, "text": "Given an array arr[] consisting of N characters, the task is to generate all possible combinations of at most X elements ( 1 ≤ X ≤ N)." }, { "code": null, "e": 26558, "s": 26548, "text": "Examples:" }, { "code": null, "e": 26794, "s": 26558, "text": "Input: N = 3, X = 2, arr[] = {‘a’, ‘b’, ‘a’}Output: a b c bc ca ab cb ac baExplanation: All possible combinations using 1 character is 3 {‘a’, ‘b’, ‘c’}. All possible combinations using 2 characters are {“bc” “ca” “ab” “cb” “ac” “ba”}." }, { "code": null, "e": 26894, "s": 26794, "text": "Input: N = 3, X = 3, arr[] = {‘d’, ‘a’, ‘b’}Output: d a b da ab bd ad ba db dab dba abd adb bda bad" }, { "code": null, "e": 27021, "s": 26894, "text": "Approach: The given problem can be solved using the Dynamic Programming approach. Follow the below steps to solve the problem:" }, { "code": null, "e": 27384, "s": 27021, "text": "Generate all possible permutations that can be created with 1 character, which is the given array arr[].Store all permutations.Once stored, generate all possible permutations of 2 characters and store them.Once the last step is completed, discard all permutations of a single character.Iteratively, in the same way, calculate the permutations until X is reached." }, { "code": null, "e": 27489, "s": 27384, "text": "Generate all possible permutations that can be created with 1 character, which is the given array arr[]." }, { "code": null, "e": 27513, "s": 27489, "text": "Store all permutations." }, { "code": null, "e": 27593, "s": 27513, "text": "Once stored, generate all possible permutations of 2 characters and store them." }, { "code": null, "e": 27674, "s": 27593, "text": "Once the last step is completed, discard all permutations of a single character." }, { "code": null, "e": 27751, "s": 27674, "text": "Iteratively, in the same way, calculate the permutations until X is reached." }, { "code": null, "e": 27802, "s": 27751, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27806, "s": 27802, "text": "C++" }, { "code": null, "e": 27811, "s": 27806, "text": "Java" }, { "code": null, "e": 27819, "s": 27811, "text": "Python3" }, { "code": null, "e": 27822, "s": 27819, "text": "C#" }, { "code": null, "e": 27833, "s": 27822, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate permutations of// at most X elements from array arr[]void differentFlagPermutations(int X, vector<string> arr){ vector<string> ml; ml = arr; for(int i = 0; i < ml.size(); i++) { cout << ml[i] << \" \"; } int count = ml.size(); // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z vector<string> tmp; // Traverse the array for(int i = 0; i < arr.size(); i++) { for(int k = 0; k < ml.size(); k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.push_back(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.size(); i++) { cout << tmp[i] << \" \"; } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; }} // Driver Codeint main(){ // Given array vector<string> arr{ \"c\", \"a\", \"b\" }; // Given X int X = 2; differentFlagPermutations(X, arr); return 0;} // This code is contributed by divyeshrabadiya07", "e": 29339, "s": 27833, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to generate permutations of// at most X elements from array arr[]static void differentFlagPermutations(int X, String[] arr){ String[] ml = arr; for(int i = 0; i < ml.length; i++) { System.out.print(ml[i] + \" \"); } int count = ml.length; // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z Vector<String> tmp = new Vector<String>(); // Traverse the array for(int i = 0; i < arr.length; i++) { for(int k = 0; k < ml.length; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.add(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.size(); i++) { System.out.print(tmp.get(i) + \" \"); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp.toArray(new String[tmp.size()]);; }} // Driver Codepublic static void main(String[] args){ // Given array String []arr = { \"c\", \"a\", \"b\" }; // Given X int X = 2; differentFlagPermutations(X, arr); }} // This code is contributed by shikhasingrajput", "e": 30898, "s": 29339, "text": null }, { "code": "# Python3 program for the above approach # Function to generate permutations of# at most X elements from array arr[]def differentFlagPermutations(X, arr): ml = arr.copy() print(\" \".join(ml), end =\" \") count = len(ml) # Traverse all possible lengths for z in range(X-1): # Stores all combinations # of length z tmp = [] # Traverse the array for i in arr: for k in ml: if i not in k: # Generate all # combinations of length z tmp.append(k + i) count += 1 # Print all combinations of length z print(\" \".join(tmp), end =\" \") # Replace all combinations of length z - 1 # with all combinations of length z ml = tmp # Given arrayarr = ['c', 'a', 'b'] # Given XX = 2 differentFlagPermutations(X, arr)", "e": 31851, "s": 30898, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to generate permutations of // at most X elements from array arr[] static void differentFlagPermutations(int X, List<string> arr) { List<string> ml = new List<string>(); ml = arr; for(int i = 0; i < ml.Count; i++) { Console.Write(ml[i] + \" \"); } int count = ml.Count; // Traverse all possible lengths for(int z = 0; z < X - 1; z++) { // Stores all combinations // of length z List<string> tmp = new List<string>(); // Traverse the array for(int i = 0; i < arr.Count; i++) { for(int k = 0; k < ml.Count; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.Add(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(int i = 0; i < tmp.Count; i++) { Console.Write(tmp[i] + \" \"); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; } } // Driver code static void Main() { // Given array List<string> arr = new List<string>(new string[] { \"c\", \"a\", \"b\" }); // Given X int X = 2; differentFlagPermutations(X, arr); }} // This code is contributed by divyesh072019", "e": 33250, "s": 31851, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to generate permutations of // at most X elements from array arr[] function differentFlagPermutations(X, arr) { let ml = []; ml = arr; for(let i = 0; i < ml.length; i++) { document.write(ml[i] + \" \"); } let count = ml.length; // Traverse all possible lengths for(let z = 0; z < X - 1; z++) { // Stores all combinations // of length z let tmp = []; // Traverse the array for(let i = 0; i < arr.length; i++) { for(let k = 0; k < ml.length; k++) { if (arr[i] != ml[k]) { // Generate all // combinations of length z tmp.push(ml[k] + arr[i]); count += 1; } } } // Print all combinations of length z for(let i = 0; i < tmp.length; i++) { document.write(tmp[i] + \" \"); } // Replace all combinations of length z - 1 // with all combinations of length z ml = tmp; } } // Given array let arr = [ \"c\", \"a\", \"b\" ]; // Given X let X = 2; differentFlagPermutations(X, arr); </script>", "e": 34520, "s": 33250, "text": null }, { "code": null, "e": 34544, "s": 34520, "text": "c a b ac bc ca ba cb ab" }, { "code": null, "e": 34593, "s": 34546, "text": "Time Complexity: O(X*N2)Auxiliary Space: O(N2)" }, { "code": null, "e": 34611, "s": 34593, "text": "divyeshrabadiya07" }, { "code": null, "e": 34625, "s": 34611, "text": "divyesh072019" }, { "code": null, "e": 34642, "s": 34625, "text": "shikhasingrajput" }, { "code": null, "e": 34651, "s": 34642, "text": "suresh07" }, { "code": null, "e": 34663, "s": 34651, "text": "permutation" }, { "code": null, "e": 34670, "s": 34663, "text": "Arrays" }, { "code": null, "e": 34684, "s": 34670, "text": "Combinatorial" }, { "code": null, "e": 34704, "s": 34684, "text": "Dynamic Programming" }, { "code": null, "e": 34712, "s": 34704, "text": "Strings" }, { "code": null, "e": 34719, "s": 34712, "text": "Arrays" }, { "code": null, "e": 34727, "s": 34719, "text": "Strings" }, { "code": null, "e": 34747, "s": 34727, "text": "Dynamic Programming" }, { "code": null, "e": 34759, "s": 34747, "text": "permutation" }, { "code": null, "e": 34773, "s": 34759, "text": "Combinatorial" }, { "code": null, "e": 34871, "s": 34773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34939, "s": 34871, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34983, "s": 34939, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35006, "s": 34983, "text": "Introduction to Arrays" }, { "code": null, "e": 35038, "s": 35006, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35052, "s": 35038, "text": "Linear Search" }, { "code": null, "e": 35090, "s": 35052, "text": "Permutation and Combination in Python" }, { "code": null, "e": 35167, "s": 35090, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 35185, "s": 35167, "text": "Combinational Sum" }, { "code": null, "e": 35213, "s": 35185, "text": "Factorial of a large number" } ]
Detecting objects of similar color in Python using OpenCV - GeeksforGeeks
23 Jun, 2021 OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar. OpenCV Numpy First of all, we need to read the image which is in our local folder using cv2.imread( ). For filtering a specific color we need to convert image into HSV format which is hue, saturation, and value and mask the image using cv2.inRange( ) by providing lower and upper bounds of RGB values we wanted to filter which gives us a black and white image where the images with the color of our interests are in white and remaining are in black. we can get back the images with the specified color which we gave it by trackbar by doing cv2 bitwise_and operation. Code: Python3 # import required libraryimport cv2import numpy as npimport matplotlib.pyplot as plt # create a video object# for capture the frames.# for Webcamera we pass 0 # as an argument cap = cv2.VideoCapture(0) # define a empty function def nothing(x): pass # set windown namecv2.namedWindow('Tracking') # Creates a trackbar and attaches # it to the specified window # with nothing functioncv2.createTrackbar("LH", "Tracking", 0, 255, nothing)cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)cv2.createTrackbar("HH", "Tracking", 0, 255, nothing)cv2.createTrackbar("HS", "Tracking", 0, 255, nothing)cv2.createTrackbar("HV", "Tracking", 0, 255, nothing) # This drives the program # into an infinite loop. while True: # Captures the live stream frame-by-frame _, frame = cap.read() # Converts images from BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # find LH trackbar position l_h = cv2.getTrackbarPos("LH", "Tracking") # find LS trackbar position l_s = cv2.getTrackbarPos("LS", "Tracking") # find LV trackbar position l_v = cv2.getTrackbarPos("LV", "Tracking") # find HH trackbar position h_h = cv2.getTrackbarPos("HH", "Tracking") # find HS trackbar position h_s = cv2.getTrackbarPos("HS", "Tracking") # find HV trackbar position h_v = cv2.getTrackbarPos("HV", "Tracking") # create a given numpy array l_b = np.array([l_h, l_s, l_v]) # create a given numpy array u_b = np.array([h_h, h_s, h_v]) # create a mask mask = cv2.inRange(hsv, l_b, u_b) # applying bitwise_and operation res = cv2.bitwise_and(frame, frame, mask = mask) # display frame, mask # and res window cv2.imshow('frame', frame) cv2.imshow('mask', mask) cv2.imshow('res', res) # wait for 1 sec k = cv2.waitKey(1) # break out of while loop # if k value is 27 if k == 27: break # release the captured frames cap.release() # Destroys all windows. cv2.destroyAllWindows() Output: sweetyty Python-OpenCV 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": 25563, "s": 25535, "text": "\n23 Jun, 2021" }, { "code": null, "e": 25651, "s": 25563, "text": "OpenCV is a library of programming functions mainly aimed at real-time computer vision." }, { "code": null, "e": 25825, "s": 25651, "text": "In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar." }, { "code": null, "e": 25838, "s": 25825, "text": "OpenCV\nNumpy" }, { "code": null, "e": 26392, "s": 25838, "text": "First of all, we need to read the image which is in our local folder using cv2.imread( ). For filtering a specific color we need to convert image into HSV format which is hue, saturation, and value and mask the image using cv2.inRange( ) by providing lower and upper bounds of RGB values we wanted to filter which gives us a black and white image where the images with the color of our interests are in white and remaining are in black. we can get back the images with the specified color which we gave it by trackbar by doing cv2 bitwise_and operation." }, { "code": null, "e": 26398, "s": 26392, "text": "Code:" }, { "code": null, "e": 26406, "s": 26398, "text": "Python3" }, { "code": "# import required libraryimport cv2import numpy as npimport matplotlib.pyplot as plt # create a video object# for capture the frames.# for Webcamera we pass 0 # as an argument cap = cv2.VideoCapture(0) # define a empty function def nothing(x): pass # set windown namecv2.namedWindow('Tracking') # Creates a trackbar and attaches # it to the specified window # with nothing functioncv2.createTrackbar(\"LH\", \"Tracking\", 0, 255, nothing)cv2.createTrackbar(\"LS\", \"Tracking\", 0, 255, nothing)cv2.createTrackbar(\"LV\", \"Tracking\", 0, 255, nothing)cv2.createTrackbar(\"HH\", \"Tracking\", 0, 255, nothing)cv2.createTrackbar(\"HS\", \"Tracking\", 0, 255, nothing)cv2.createTrackbar(\"HV\", \"Tracking\", 0, 255, nothing) # This drives the program # into an infinite loop. while True: # Captures the live stream frame-by-frame _, frame = cap.read() # Converts images from BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # find LH trackbar position l_h = cv2.getTrackbarPos(\"LH\", \"Tracking\") # find LS trackbar position l_s = cv2.getTrackbarPos(\"LS\", \"Tracking\") # find LV trackbar position l_v = cv2.getTrackbarPos(\"LV\", \"Tracking\") # find HH trackbar position h_h = cv2.getTrackbarPos(\"HH\", \"Tracking\") # find HS trackbar position h_s = cv2.getTrackbarPos(\"HS\", \"Tracking\") # find HV trackbar position h_v = cv2.getTrackbarPos(\"HV\", \"Tracking\") # create a given numpy array l_b = np.array([l_h, l_s, l_v]) # create a given numpy array u_b = np.array([h_h, h_s, h_v]) # create a mask mask = cv2.inRange(hsv, l_b, u_b) # applying bitwise_and operation res = cv2.bitwise_and(frame, frame, mask = mask) # display frame, mask # and res window cv2.imshow('frame', frame) cv2.imshow('mask', mask) cv2.imshow('res', res) # wait for 1 sec k = cv2.waitKey(1) # break out of while loop # if k value is 27 if k == 27: break # release the captured frames cap.release() # Destroys all windows. cv2.destroyAllWindows()", "e": 28851, "s": 26406, "text": null }, { "code": null, "e": 28859, "s": 28851, "text": "Output:" }, { "code": null, "e": 28868, "s": 28859, "text": "sweetyty" }, { "code": null, "e": 28882, "s": 28868, "text": "Python-OpenCV" }, { "code": null, "e": 28889, "s": 28882, "text": "Python" }, { "code": null, "e": 28987, "s": 28889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29019, "s": 28987, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29061, "s": 29019, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29103, "s": 29061, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29159, "s": 29103, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29186, "s": 29159, "text": "Python Classes and Objects" }, { "code": null, "e": 29225, "s": 29186, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29256, "s": 29225, "text": "Python | os.path.join() method" }, { "code": null, "e": 29285, "s": 29256, "text": "Create a directory in Python" }, { "code": null, "e": 29307, "s": 29285, "text": "Defaultdict in Python" } ]
Generate N integers satisfying the given conditions - GeeksforGeeks
27 Mar, 2022 Given an integer N, the task is to generate an array of size N with the following properties: No two elements divide each other.Every odd subset has an odd sum and every even subset has an even sum. No two elements divide each other. Every odd subset has an odd sum and every even subset has an even sum. Examples: Input: N = 3 Output: 3 5 7 No two element divide each other and the sum of all the odd subsets {3}, {5}, {7} and {3, 5, 7} is odd. Sum of all the even subsets is even i.e. {3, 5}, {3, 7} and {5, 7}Input: N = 6 Output: 3 5 7 11 13 17 Approach: In order to satisfy the condition when every odd subset has an odd sum and even a subset has an even sum, every element has to be odd and in order for any two elements to not divide each other they must be prime. So, the task now is to find the first N odd prime numbers.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 1000000 // Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersvoid solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count cout << i << " "; count++; } }} // Driver codeint main(){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{static int MAX = 1000000; // Create a boolean array "prime[0..n]" and// initialize all entries it as true.// A value in prime[i] will finally be false// if i is Not a prime, else true.static boolean []prime = new boolean[MAX + 1];static void SieveOfEratosthenes(){ for (int i = 0; i <= MAX; i ++) prime[i] = true; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersstatic void solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count System.out.print(i + " "); count++; } }} // Driver codepublic static void main(String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n);}} // This code is contributed by Rajput-Ji # Python3 implementation of the approachfrom math import sqrt MAX = 1000000 # Create a boolean array "prime[0..n]" and# initialize all entries it as true.# A value in prime[i] will finally be false# if i is Not a prime, else true.prime = [True] * (MAX + 1); def SieveOfEratosthenes() : prime[1] = False; for p in range(2, int(sqrt(MAX)) + 1) : # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Set all multiples of p to non-prime for i in range(p * 2, MAX + 1, p) : prime[i] = False; # Function to find the first# n odd prime numbersdef solve(n) : # To store the current count # of prime numbers count = 0; i = 3; # Starting with 3 as 2 is # an even prime number while count < n : # If i is prime if (prime[i]) : # Print i and increment count print(i, end = " "); count += 1; i += 1 # Driver codeif __name__ == "__main__" : # Create the sieve SieveOfEratosthenes(); n = 6; solve(n); # This code is contributed by AnkitRai01 // C# implementation of the above approachusing System; class GFG{static int MAX = 1000000; // Create a boolean array "prime[0..n]" and// initialize all entries it as true.// A value in prime[i] will finally be false// if i is Not a prime, else true.static bool []prime = new bool[MAX + 1];static void SieveOfEratosthenes(){ for (int i = 0; i <= MAX; i ++) prime[i] = true; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersstatic void solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count Console.Write(i + " "); count++; } }} // Driver codepublic static void Main(String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n);}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach const MAX = 1000000; // Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.let prime = new Array(MAX + 1).fill(true);function SieveOfEratosthenes(){ prime[1] = false; for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (let i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersfunction solve(n){ // To store the current count // of prime numbers let count = 0; // Starting with 3 as 2 is // an even prime number for (let i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count document.write(i + " "); count++; } }} // Driver code // Create the sieve SieveOfEratosthenes(); let n = 6; solve(n); </script> 3 5 7 11 13 17 Time Complexity: O(n + MAX3/2) Auxiliary Space: O(MAX) ankthon Rajput-Ji 29AjayKumar subhammahato348 Numbers Prime Number Mathematical Mathematical Prime Number Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Fizz Buzz Implementation Count all possible paths from top left to bottom right of a mXn matrix Check if a number is Palindrome Program to multiply two matrices Generate all permutation of a set in Python Merge two sorted arrays with O(1) extra space Count ways to reach the n'th stair
[ { "code": null, "e": 25963, "s": 25935, "text": "\n27 Mar, 2022" }, { "code": null, "e": 26059, "s": 25963, "text": "Given an integer N, the task is to generate an array of size N with the following properties: " }, { "code": null, "e": 26164, "s": 26059, "text": "No two elements divide each other.Every odd subset has an odd sum and every even subset has an even sum." }, { "code": null, "e": 26199, "s": 26164, "text": "No two elements divide each other." }, { "code": null, "e": 26270, "s": 26199, "text": "Every odd subset has an odd sum and every even subset has an even sum." }, { "code": null, "e": 26282, "s": 26270, "text": "Examples: " }, { "code": null, "e": 26517, "s": 26282, "text": "Input: N = 3 Output: 3 5 7 No two element divide each other and the sum of all the odd subsets {3}, {5}, {7} and {3, 5, 7} is odd. Sum of all the even subsets is even i.e. {3, 5}, {3, 7} and {5, 7}Input: N = 6 Output: 3 5 7 11 13 17 " }, { "code": null, "e": 26853, "s": 26519, "text": "Approach: In order to satisfy the condition when every odd subset has an odd sum and even a subset has an even sum, every element has to be odd and in order for any two elements to not divide each other they must be prime. So, the task now is to find the first N odd prime numbers.Below is the implementation of the above approach: " }, { "code": null, "e": 26857, "s": 26853, "text": "C++" }, { "code": null, "e": 26862, "s": 26857, "text": "Java" }, { "code": null, "e": 26870, "s": 26862, "text": "Python3" }, { "code": null, "e": 26873, "s": 26870, "text": "C#" }, { "code": null, "e": 26884, "s": 26873, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 1000000 // Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersvoid solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count cout << i << \" \"; count++; } }} // Driver codeint main(){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n); return 0;}", "e": 28041, "s": 26884, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 1000000; // Create a boolean array \"prime[0..n]\" and// initialize all entries it as true.// A value in prime[i] will finally be false// if i is Not a prime, else true.static boolean []prime = new boolean[MAX + 1];static void SieveOfEratosthenes(){ for (int i = 0; i <= MAX; i ++) prime[i] = true; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersstatic void solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count System.out.print(i + \" \"); count++; } }} // Driver codepublic static void main(String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n);}} // This code is contributed by Rajput-Ji", "e": 29347, "s": 28041, "text": null }, { "code": "# Python3 implementation of the approachfrom math import sqrt MAX = 1000000 # Create a boolean array \"prime[0..n]\" and# initialize all entries it as true.# A value in prime[i] will finally be false# if i is Not a prime, else true.prime = [True] * (MAX + 1); def SieveOfEratosthenes() : prime[1] = False; for p in range(2, int(sqrt(MAX)) + 1) : # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Set all multiples of p to non-prime for i in range(p * 2, MAX + 1, p) : prime[i] = False; # Function to find the first# n odd prime numbersdef solve(n) : # To store the current count # of prime numbers count = 0; i = 3; # Starting with 3 as 2 is # an even prime number while count < n : # If i is prime if (prime[i]) : # Print i and increment count print(i, end = \" \"); count += 1; i += 1 # Driver codeif __name__ == \"__main__\" : # Create the sieve SieveOfEratosthenes(); n = 6; solve(n); # This code is contributed by AnkitRai01", "e": 30468, "s": 29347, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{static int MAX = 1000000; // Create a boolean array \"prime[0..n]\" and// initialize all entries it as true.// A value in prime[i] will finally be false// if i is Not a prime, else true.static bool []prime = new bool[MAX + 1];static void SieveOfEratosthenes(){ for (int i = 0; i <= MAX; i ++) prime[i] = true; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersstatic void solve(int n){ // To store the current count // of prime numbers int count = 0; // Starting with 3 as 2 is // an even prime number for (int i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count Console.Write(i + \" \"); count++; } }} // Driver codepublic static void Main(String[] args){ // Create the sieve SieveOfEratosthenes(); int n = 6; solve(n);}} // This code is contributed by 29AjayKumar", "e": 31769, "s": 30468, "text": null }, { "code": "<script> // Javascript implementation of the approach const MAX = 1000000; // Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.let prime = new Array(MAX + 1).fill(true);function SieveOfEratosthenes(){ prime[1] = false; for (let p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (let i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // Function to find the first// n odd prime numbersfunction solve(n){ // To store the current count // of prime numbers let count = 0; // Starting with 3 as 2 is // an even prime number for (let i = 3; count < n; i++) { // If i is prime if (prime[i]) { // Print i and increment count document.write(i + \" \"); count++; } }} // Driver code // Create the sieve SieveOfEratosthenes(); let n = 6; solve(n); </script>", "e": 32877, "s": 31769, "text": null }, { "code": null, "e": 32892, "s": 32877, "text": "3 5 7 11 13 17" }, { "code": null, "e": 32925, "s": 32894, "text": "Time Complexity: O(n + MAX3/2)" }, { "code": null, "e": 32949, "s": 32925, "text": "Auxiliary Space: O(MAX)" }, { "code": null, "e": 32957, "s": 32949, "text": "ankthon" }, { "code": null, "e": 32967, "s": 32957, "text": "Rajput-Ji" }, { "code": null, "e": 32979, "s": 32967, "text": "29AjayKumar" }, { "code": null, "e": 32995, "s": 32979, "text": "subhammahato348" }, { "code": null, "e": 33003, "s": 32995, "text": "Numbers" }, { "code": null, "e": 33016, "s": 33003, "text": "Prime Number" }, { "code": null, "e": 33029, "s": 33016, "text": "Mathematical" }, { "code": null, "e": 33042, "s": 33029, "text": "Mathematical" }, { "code": null, "e": 33055, "s": 33042, "text": "Prime Number" }, { "code": null, "e": 33063, "s": 33055, "text": "Numbers" }, { "code": null, "e": 33161, "s": 33063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33205, "s": 33161, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33247, "s": 33205, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 33278, "s": 33247, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33303, "s": 33278, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33374, "s": 33303, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 33406, "s": 33374, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33439, "s": 33406, "text": "Program to multiply two matrices" }, { "code": null, "e": 33483, "s": 33439, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 33529, "s": 33483, "text": "Merge two sorted arrays with O(1) extra space" } ]
SAP Labs Interview Experience (On-Campus) - GeeksforGeeks
09 Aug, 2021 SAP Labs visited our college for hiring students for the Scholar@SAP profile. It is a WILP(Work Integrated Learning Program) course that aims to provide 2 years of work experience on industrial SAP projects as well as an M-Tech degree in Software Engineering from BITS Pilani. In the given program, weekdays are completely dedicated to corporate work and on weekends, M-Tech classes are conducted. The overall hiring process was dissected into 4 rounds – Online Coding RoundTechnical Round 1Technical Round 2HR Round Online Coding Round Technical Round 1 Technical Round 2 HR Round Online Coding Round(406 candidates) – This round is comprised of 2 coding questions and 15 multiple choice questions for which we have dedicated 90 mins with HackerRank as the platform. The difficulty level of coding questions was medium. Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum(https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/) It was a string manipulation question where the given string had to go through needful changes to meet the required constraints. The 15 MCQs were based on OOPS, DBMS, Data Structures, Computer Networks. The difficulty level of MCQs varied from easy to hard. Technical Round 1(37 candidates) – The interview platform was the HackerRank Code pair. The interviewer uploaded a problem statement in the problem section. I was given 30 mins to code and run as many test cases as I could. The problem statement was – Find the index of an element in an array such that the sum of the left array is equal to the sum of the right array (https://www.geeksforgeeks.org/find-element-array-sum-left-array-equal-sum-right-array/). Then the interviewer shared an employee database table and asked me to write a SQL query for given requirements. The SQL query was a bit complex and required a nested-nested IN operator. In the end, I was asked about my knowledge of Cloud Computing. Note – It is very important to consistently interact with the interviewer and explain our thought process even while coding. Technical Round 2(20 candidates) – It was a 30 mins interview. The interviewer touched on all the important topics like OOP, DBMS, Data Structures. OOP – Interviewer shared his screen and asked me multiple variations of access specifiers in C++. Understanding of public, private, protected was checked. Abstract class and Interface in JAVA were briefly asked. DBMS – Interviewer asked me to make a database schema of the IPL Fantasy League. I considered that one candidate can have multiple teams and added constraints to the team as it can have at max one 1 WK, 4 Bowlers, 4 Batsman, 3 All-rounders. I designed 3 tables – Leaderboards, teams, Candidates with associated attributes. Data Structures – Write a program to replace Linked List 2 in Linked List 1 at given i and j.Input: L1-(10,20,30,40,50,60,70) i j L2-(11,22,33,44,55) Output : L1-(10,20,11,22,33,44,55,60,70) Explanation: sub-list of L1 from i to j is replaced with L2. Input: L1-(10,20,30,40,50,60,70) i j L2-(11,22,33,44,55) Output : L1-(10,20,11,22,33,44,55,60,70) Explanation: sub-list of L1 from i to j is replaced with L2. HR Round(11 candidates) – There were 2 HRs in the panel. The following questions were asked – They questioned me on my resume, certifications, achievements, future plan. Explain how will you manage the job and higher studies at the same time? My knowledge about SAP was checked. Explain any one of your projects which you feel is closest to you. Questions based on strengths, weaknesses, and potential were asked. The whole and sole aim of the discussion is to scrutinize your communication skills and confidence. All the best! Marketing On-Campus SAP Labs Interview Experiences SAP Labs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus) Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
[ { "code": null, "e": 26287, "s": 26259, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26685, "s": 26287, "text": "SAP Labs visited our college for hiring students for the Scholar@SAP profile. It is a WILP(Work Integrated Learning Program) course that aims to provide 2 years of work experience on industrial SAP projects as well as an M-Tech degree in Software Engineering from BITS Pilani. In the given program, weekdays are completely dedicated to corporate work and on weekends, M-Tech classes are conducted." }, { "code": null, "e": 26742, "s": 26685, "text": "The overall hiring process was dissected into 4 rounds –" }, { "code": null, "e": 26804, "s": 26742, "text": "Online Coding RoundTechnical Round 1Technical Round 2HR Round" }, { "code": null, "e": 26824, "s": 26804, "text": "Online Coding Round" }, { "code": null, "e": 26842, "s": 26824, "text": "Technical Round 1" }, { "code": null, "e": 26860, "s": 26842, "text": "Technical Round 2" }, { "code": null, "e": 26869, "s": 26860, "text": "HR Round" }, { "code": null, "e": 27108, "s": 26869, "text": "Online Coding Round(406 candidates) – This round is comprised of 2 coding questions and 15 multiple choice questions for which we have dedicated 90 mins with HackerRank as the platform. The difficulty level of coding questions was medium." }, { "code": null, "e": 27305, "s": 27108, "text": "Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum(https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/)" }, { "code": null, "e": 27434, "s": 27305, "text": "It was a string manipulation question where the given string had to go through needful changes to meet the required constraints." }, { "code": null, "e": 27564, "s": 27434, "text": "The 15 MCQs were based on OOPS, DBMS, Data Structures, Computer Networks. The difficulty level of MCQs varied from easy to hard. " }, { "code": null, "e": 27789, "s": 27564, "text": "Technical Round 1(37 candidates) – The interview platform was the HackerRank Code pair. The interviewer uploaded a problem statement in the problem section. I was given 30 mins to code and run as many test cases as I could. " }, { "code": null, "e": 28024, "s": 27789, "text": "The problem statement was – Find the index of an element in an array such that the sum of the left array is equal to the sum of the right array (https://www.geeksforgeeks.org/find-element-array-sum-left-array-equal-sum-right-array/). " }, { "code": null, "e": 28212, "s": 28024, "text": "Then the interviewer shared an employee database table and asked me to write a SQL query for given requirements. The SQL query was a bit complex and required a nested-nested IN operator. " }, { "code": null, "e": 28275, "s": 28212, "text": "In the end, I was asked about my knowledge of Cloud Computing." }, { "code": null, "e": 28400, "s": 28275, "text": "Note – It is very important to consistently interact with the interviewer and explain our thought process even while coding." }, { "code": null, "e": 28548, "s": 28400, "text": "Technical Round 2(20 candidates) – It was a 30 mins interview. The interviewer touched on all the important topics like OOP, DBMS, Data Structures." }, { "code": null, "e": 28760, "s": 28548, "text": "OOP – Interviewer shared his screen and asked me multiple variations of access specifiers in C++. Understanding of public, private, protected was checked. Abstract class and Interface in JAVA were briefly asked." }, { "code": null, "e": 29083, "s": 28760, "text": "DBMS – Interviewer asked me to make a database schema of the IPL Fantasy League. I considered that one candidate can have multiple teams and added constraints to the team as it can have at max one 1 WK, 4 Bowlers, 4 Batsman, 3 All-rounders. I designed 3 tables – Leaderboards, teams, Candidates with associated attributes." }, { "code": null, "e": 29353, "s": 29083, "text": "Data Structures – Write a program to replace Linked List 2 in Linked List 1 at given i and j.Input: L1-(10,20,30,40,50,60,70)\n i j\nL2-(11,22,33,44,55)\nOutput : L1-(10,20,11,22,33,44,55,60,70)\nExplanation: sub-list of L1 from \ni to j is replaced with L2." }, { "code": null, "e": 29530, "s": 29353, "text": "Input: L1-(10,20,30,40,50,60,70)\n i j\nL2-(11,22,33,44,55)\nOutput : L1-(10,20,11,22,33,44,55,60,70)\nExplanation: sub-list of L1 from \ni to j is replaced with L2." }, { "code": null, "e": 29624, "s": 29530, "text": "HR Round(11 candidates) – There were 2 HRs in the panel. The following questions were asked –" }, { "code": null, "e": 29700, "s": 29624, "text": "They questioned me on my resume, certifications, achievements, future plan." }, { "code": null, "e": 29773, "s": 29700, "text": "Explain how will you manage the job and higher studies at the same time?" }, { "code": null, "e": 29809, "s": 29773, "text": "My knowledge about SAP was checked." }, { "code": null, "e": 29876, "s": 29809, "text": "Explain any one of your projects which you feel is closest to you." }, { "code": null, "e": 30044, "s": 29876, "text": "Questions based on strengths, weaknesses, and potential were asked. The whole and sole aim of the discussion is to scrutinize your communication skills and confidence." }, { "code": null, "e": 30058, "s": 30044, "text": "All the best!" }, { "code": null, "e": 30068, "s": 30058, "text": "Marketing" }, { "code": null, "e": 30078, "s": 30068, "text": "On-Campus" }, { "code": null, "e": 30087, "s": 30078, "text": "SAP Labs" }, { "code": null, "e": 30109, "s": 30087, "text": "Interview Experiences" }, { "code": null, "e": 30118, "s": 30109, "text": "SAP Labs" }, { "code": null, "e": 30216, "s": 30118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30267, "s": 30216, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 30309, "s": 30267, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 30365, "s": 30309, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 30393, "s": 30365, "text": "Amazon Interview Experience" }, { "code": null, "e": 30431, "s": 30393, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 30470, "s": 30431, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 30516, "s": 30470, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 30588, "s": 30516, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 30638, "s": 30588, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
ArrayBlockingQueue Class in Java - GeeksforGeeks
03 Jan, 2022 ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the Queue is fixed. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking. Similarly attempts to take an element from an empty queue will also be blocked. Boundness of the ArrayBlockingQueue can be achieved initially bypassing capacity as the parameter in the constructor of ArrayBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. This class is a member of the Java Collections Framework. The Hierarchy of ArrayBlockingQueue This class extends AbstractQueue<E> and implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces. Declaration public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable Here, E is the type of elements stored in the collection. Here, capacity is the size of the array blocking queue. 1. ArrayBlockingQueue(int capacity): Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy. ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity); 2. ArrayBlockingQueue(int capacity, boolean fair): Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity, boolean fair); 3. ArrayBlockingQueue(int capacity, boolean fair, Collection c): Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection’s iterator. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity, boolean fair, Collection c); Example: Java // Java program to demonstrate // ArrayBlockingQueue(int initialCapacity)// constructor import java.util.concurrent.ArrayBlockingQueue; public class ArrayBlockingQueueDemo { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue // using ArrayBlockingQueue(int initialCapacity) constructor ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println("ArrayBlockingQueue:" + abq); }} ArrayBlockingQueue:[1, 2, 3] 1. Adding Elements The add(E e) method inserts the element passed as a parameter to the method at the tail of this queue. If adding the element exceeds the capacity of the queue then the method will throw an IllegalStateException. This method returns true if adding of the element is successful else it will throw an IllegalStateException. Java // Java Program to Demonstrate adding// elements to an ArrayBlockingQueue. import java.util.concurrent.ArrayBlockingQueue; public class AddingElementsExample { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println("ArrayBlockingQueue:" + abq); }} ArrayBlockingQueue:[1, 2, 3] 2. Removing Elements The remove(Object o) method removes a single instance of the specified element from this queue if it is present. We can say that method removes an element e such that o.equals(e) if this queue contains one or more such elements. Remove() method returns true if this queue contained the specified element which we want to remove. Java // Java program to demonstrate removal of // elements from an AbstractQueue import java.util.concurrent.ArrayBlockingQueue; public class RemovingElementsExample { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println("ArrayBlockingQueue:" + abq); // remove 223 boolean response = abq.remove(2); // print Queue System.out.println("Removal of 2 :" + response); // print Queue System.out.println("queue contains " + abq); // remove all the elements abq.clear(); // print queue System.out.println("ArrayBlockingQueue:" + abq); }} ArrayBlockingQueue:[1, 2, 3] Removal of 2 :true queue contains [1, 3] ArrayBlockingQueue:[] 3. Accessing Elements The peek() method provided by the Queue interface is used to return the head of the queue. It retrieves but does not remove, the head of this queue. If the queue is empty then this method returns null. Java // Java program to demonstrate accessing// elements of ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue; public class AccessingElementsExample { public static void main(String[] args) { // Define capacity of ArrayBlockingQueue int capacity = 5; // Create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); // Add element to ArrayBlockingQueue queue.add(23); queue.add(32); queue.add(45); queue.add(12); // Print queue after adding numbers System.out.println("After adding numbers queue is "); System.out.println(queue); // Print head of queue using peek() method System.out.println("Head of queue " + queue.peek()); }} After adding numbers queue is [23, 32, 45, 12] Head of queue 23 4. Traversing The iterator() method of ArrayBlockingQueue class is used to returns an iterator of the same elements as this queue in a proper sequence. The elements returned from this method contains elements in order from first(head) to last(tail). The returned iterator is weakly consistent. Java // Java Program to Demonstrate iterating// over ArrayBlockingQueue. import java.util.concurrent.ArrayBlockingQueue;import java.util.*; public class TraversingExample { public static void main(String[] args) { // Define capacity of ArrayBlockingQueue int capacity = 5; // Create object of ArrayBlockingQueue ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(capacity); // Add 5 elements to ArrayBlockingQueue queue.offer("User"); queue.offer("Employee"); queue.offer("Manager"); queue.offer("Analyst"); queue.offer("HR"); // Print queue System.out.println("Queue is " + queue); // Call iterator() method and Create an iterator Iterator iteratorValues = queue.iterator(); // Print elements of iterator System.out.println("\nThe iterator values:"); while (iteratorValues.hasNext()) { System.out.println(iteratorValues.next()); } }} Queue is [User, Employee, Manager, Analyst, HR] The iterator values: User Employee Manager Analyst HR Here, E is the type of elements held in this collection METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION Conclusion: ArrayBlockingQueue is generally used in a thread-safe environment where you want to block two or more operating on a single resource, allowing only one thread. Also, we can block a thread using the capacity bounding factor. Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ArrayBlockingQueue.html ManasChhabra2 Ganeshchowdharysadanala akshaysingh98088 Java - util package Java-ArrayBlockingQueue Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24999, "s": 24971, "text": "\n03 Jan, 2022" }, { "code": null, "e": 25633, "s": 24999, "text": "ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the Queue is fixed. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking. Similarly attempts to take an element from an empty queue will also be blocked. Boundness of the ArrayBlockingQueue can be achieved initially bypassing capacity as the parameter in the constructor of ArrayBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. " }, { "code": null, "e": 25860, "s": 25633, "text": "The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue." }, { "code": null, "e": 26027, "s": 25860, "text": "This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. This class is a member of the Java Collections Framework." }, { "code": null, "e": 26064, "s": 26027, "text": "The Hierarchy of ArrayBlockingQueue " }, { "code": null, "e": 26196, "s": 26064, "text": "This class extends AbstractQueue<E> and implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces." }, { "code": null, "e": 26209, "s": 26196, "text": "Declaration " }, { "code": null, "e": 26311, "s": 26209, "text": "public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable" }, { "code": null, "e": 26369, "s": 26311, "text": "Here, E is the type of elements stored in the collection." }, { "code": null, "e": 26425, "s": 26369, "text": "Here, capacity is the size of the array blocking queue." }, { "code": null, "e": 26552, "s": 26425, "text": "1. ArrayBlockingQueue(int capacity): Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy. " }, { "code": null, "e": 26621, "s": 26552, "text": "ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity);" }, { "code": null, "e": 26933, "s": 26621, "text": "2. ArrayBlockingQueue(int capacity, boolean fair): Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. " }, { "code": null, "e": 27016, "s": 26933, "text": "ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity, boolean fair);" }, { "code": null, "e": 27456, "s": 27016, "text": "3. ArrayBlockingQueue(int capacity, boolean fair, Collection c): Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection’s iterator. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. " }, { "code": null, "e": 27553, "s": 27456, "text": "ArrayBlockingQueue<E> abq = new ArrayBlockingQueue<E>(int capacity, boolean fair, Collection c);" }, { "code": null, "e": 27563, "s": 27553, "text": "Example: " }, { "code": null, "e": 27568, "s": 27563, "text": "Java" }, { "code": "// Java program to demonstrate // ArrayBlockingQueue(int initialCapacity)// constructor import java.util.concurrent.ArrayBlockingQueue; public class ArrayBlockingQueueDemo { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue // using ArrayBlockingQueue(int initialCapacity) constructor ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println(\"ArrayBlockingQueue:\" + abq); }}", "e": 28235, "s": 27568, "text": null }, { "code": null, "e": 28264, "s": 28235, "text": "ArrayBlockingQueue:[1, 2, 3]" }, { "code": null, "e": 28285, "s": 28266, "text": "1. Adding Elements" }, { "code": null, "e": 28607, "s": 28285, "text": "The add(E e) method inserts the element passed as a parameter to the method at the tail of this queue. If adding the element exceeds the capacity of the queue then the method will throw an IllegalStateException. This method returns true if adding of the element is successful else it will throw an IllegalStateException. " }, { "code": null, "e": 28612, "s": 28607, "text": "Java" }, { "code": "// Java Program to Demonstrate adding// elements to an ArrayBlockingQueue. import java.util.concurrent.ArrayBlockingQueue; public class AddingElementsExample { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println(\"ArrayBlockingQueue:\" + abq); }}", "e": 29197, "s": 28612, "text": null }, { "code": null, "e": 29226, "s": 29197, "text": "ArrayBlockingQueue:[1, 2, 3]" }, { "code": null, "e": 29247, "s": 29226, "text": "2. Removing Elements" }, { "code": null, "e": 29577, "s": 29247, "text": "The remove(Object o) method removes a single instance of the specified element from this queue if it is present. We can say that method removes an element e such that o.equals(e) if this queue contains one or more such elements. Remove() method returns true if this queue contained the specified element which we want to remove. " }, { "code": null, "e": 29582, "s": 29577, "text": "Java" }, { "code": "// Java program to demonstrate removal of // elements from an AbstractQueue import java.util.concurrent.ArrayBlockingQueue; public class RemovingElementsExample { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 15; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<Integer>(capacity); // add numbers abq.add(1); abq.add(2); abq.add(3); // print queue System.out.println(\"ArrayBlockingQueue:\" + abq); // remove 223 boolean response = abq.remove(2); // print Queue System.out.println(\"Removal of 2 :\" + response); // print Queue System.out.println(\"queue contains \" + abq); // remove all the elements abq.clear(); // print queue System.out.println(\"ArrayBlockingQueue:\" + abq); }}", "e": 30526, "s": 29582, "text": null }, { "code": null, "e": 30618, "s": 30526, "text": "ArrayBlockingQueue:[1, 2, 3]\nRemoval of 2 :true\nqueue contains [1, 3]\nArrayBlockingQueue:[]" }, { "code": null, "e": 30640, "s": 30618, "text": "3. Accessing Elements" }, { "code": null, "e": 30842, "s": 30640, "text": "The peek() method provided by the Queue interface is used to return the head of the queue. It retrieves but does not remove, the head of this queue. If the queue is empty then this method returns null." }, { "code": null, "e": 30847, "s": 30842, "text": "Java" }, { "code": "// Java program to demonstrate accessing// elements of ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue; public class AccessingElementsExample { public static void main(String[] args) { // Define capacity of ArrayBlockingQueue int capacity = 5; // Create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); // Add element to ArrayBlockingQueue queue.add(23); queue.add(32); queue.add(45); queue.add(12); // Print queue after adding numbers System.out.println(\"After adding numbers queue is \"); System.out.println(queue); // Print head of queue using peek() method System.out.println(\"Head of queue \" + queue.peek()); }}", "e": 31661, "s": 30847, "text": null }, { "code": null, "e": 31726, "s": 31661, "text": "After adding numbers queue is \n[23, 32, 45, 12]\nHead of queue 23" }, { "code": null, "e": 31740, "s": 31726, "text": "4. Traversing" }, { "code": null, "e": 32020, "s": 31740, "text": "The iterator() method of ArrayBlockingQueue class is used to returns an iterator of the same elements as this queue in a proper sequence. The elements returned from this method contains elements in order from first(head) to last(tail). The returned iterator is weakly consistent." }, { "code": null, "e": 32025, "s": 32020, "text": "Java" }, { "code": "// Java Program to Demonstrate iterating// over ArrayBlockingQueue. import java.util.concurrent.ArrayBlockingQueue;import java.util.*; public class TraversingExample { public static void main(String[] args) { // Define capacity of ArrayBlockingQueue int capacity = 5; // Create object of ArrayBlockingQueue ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(capacity); // Add 5 elements to ArrayBlockingQueue queue.offer(\"User\"); queue.offer(\"Employee\"); queue.offer(\"Manager\"); queue.offer(\"Analyst\"); queue.offer(\"HR\"); // Print queue System.out.println(\"Queue is \" + queue); // Call iterator() method and Create an iterator Iterator iteratorValues = queue.iterator(); // Print elements of iterator System.out.println(\"\\nThe iterator values:\"); while (iteratorValues.hasNext()) { System.out.println(iteratorValues.next()); } }}", "e": 33030, "s": 32025, "text": null }, { "code": null, "e": 33133, "s": 33030, "text": "Queue is [User, Employee, Manager, Analyst, HR]\n\nThe iterator values:\nUser\nEmployee\nManager\nAnalyst\nHR" }, { "code": null, "e": 33189, "s": 33133, "text": "Here, E is the type of elements held in this collection" }, { "code": null, "e": 33196, "s": 33189, "text": "METHOD" }, { "code": null, "e": 33208, "s": 33196, "text": "DESCRIPTION" }, { "code": null, "e": 33215, "s": 33208, "text": "METHOD" }, { "code": null, "e": 33227, "s": 33215, "text": "DESCRIPTION" }, { "code": null, "e": 33234, "s": 33227, "text": "METHOD" }, { "code": null, "e": 33246, "s": 33234, "text": "DESCRIPTION" }, { "code": null, "e": 33253, "s": 33246, "text": "METHOD" }, { "code": null, "e": 33265, "s": 33253, "text": "DESCRIPTION" }, { "code": null, "e": 33272, "s": 33265, "text": "METHOD" }, { "code": null, "e": 33284, "s": 33272, "text": "DESCRIPTION" }, { "code": null, "e": 33291, "s": 33284, "text": "METHOD" }, { "code": null, "e": 33303, "s": 33291, "text": "DESCRIPTION" }, { "code": null, "e": 33539, "s": 33303, "text": "Conclusion: ArrayBlockingQueue is generally used in a thread-safe environment where you want to block two or more operating on a single resource, allowing only one thread. Also, we can block a thread using the capacity bounding factor." }, { "code": null, "e": 33656, "s": 33539, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ArrayBlockingQueue.html" }, { "code": null, "e": 33670, "s": 33656, "text": "ManasChhabra2" }, { "code": null, "e": 33694, "s": 33670, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 33711, "s": 33694, "text": "akshaysingh98088" }, { "code": null, "e": 33731, "s": 33711, "text": "Java - util package" }, { "code": null, "e": 33755, "s": 33731, "text": "Java-ArrayBlockingQueue" }, { "code": null, "e": 33772, "s": 33755, "text": "Java-Collections" }, { "code": null, "e": 33777, "s": 33772, "text": "Java" }, { "code": null, "e": 33782, "s": 33777, "text": "Java" }, { "code": null, "e": 33799, "s": 33782, "text": "Java-Collections" }, { "code": null, "e": 33897, "s": 33799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33912, "s": 33897, "text": "Arrays in Java" }, { "code": null, "e": 33956, "s": 33912, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33978, "s": 33956, "text": "For-each loop in Java" }, { "code": null, "e": 34029, "s": 33978, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34065, "s": 34029, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 34095, "s": 34065, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34120, "s": 34095, "text": "Reverse a string in Java" }, { "code": null, "e": 34135, "s": 34120, "text": "Stream In Java" }, { "code": null, "e": 34154, "s": 34135, "text": "Interfaces in Java" } ]
C function to Swap strings - GeeksforGeeks
06 Jul, 2018 Let us consider the below program. #include<stdio.h>void swap(char *str1, char *str2){ char *temp = str1; str1 = str2; str2 = temp;} int main(){ char *str1 = "geeks"; char *str2 = "forgeeks"; swap(str1, str2); printf("str1 is %s, str2 is %s", str1, str2); getchar(); return 0;} Output of the program is str1 is geeks, str2 is forgeeks. So the above swap() function doesn’t swap strings. The function just changes local pointer variables and the changes are not reflected outside the function. Let us see the correct ways for swapping strings: Method 1(Swap Pointers)If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other’s data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer. #include<stdio.h> /* Swaps strings by swapping pointers */ void swap1(char **str1_ptr, char **str2_ptr){ char *temp = *str1_ptr; *str1_ptr = *str2_ptr; *str2_ptr = temp;} int main(){ char *str1 = "geeks"; char *str2 = "forgeeks"; swap1(&str1, &str2); printf("str1 is %s, str2 is %s", str1, str2); getchar(); return 0;} This method cannot be applied if strings are stored using character arrays. Method 2(Swap Data)If you are using character arrays to store strings then preferred way is to swap the data of both arrays. #include<stdio.h>#include<string.h>#include<stdlib.h> /* Swaps strings by swapping data*/void swap2(char *str1, char *str2){ char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char)); strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); free(temp);} int main(){ char str1[10] = "geeks"; char str2[10] = "forgeeks"; swap2(str1, str2); printf("str1 is %s, str2 is %s", str1, str2); getchar(); return 0;} This method cannot be applied for strings stored in read-only block of memory. Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above. C Array and String Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis) SQL Interview Questions Understanding "extern" keyword in C Mutex vs Semaphore Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Substring in C++
[ { "code": null, "e": 25633, "s": 25605, "text": "\n06 Jul, 2018" }, { "code": null, "e": 25668, "s": 25633, "text": "Let us consider the below program." }, { "code": "#include<stdio.h>void swap(char *str1, char *str2){ char *temp = str1; str1 = str2; str2 = temp;} int main(){ char *str1 = \"geeks\"; char *str2 = \"forgeeks\"; swap(str1, str2); printf(\"str1 is %s, str2 is %s\", str1, str2); getchar(); return 0;}", "e": 25924, "s": 25668, "text": null }, { "code": null, "e": 26139, "s": 25924, "text": "Output of the program is str1 is geeks, str2 is forgeeks. So the above swap() function doesn’t swap strings. The function just changes local pointer variables and the changes are not reflected outside the function." }, { "code": null, "e": 26189, "s": 26139, "text": "Let us see the correct ways for swapping strings:" }, { "code": null, "e": 26509, "s": 26189, "text": "Method 1(Swap Pointers)If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other’s data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer." }, { "code": "#include<stdio.h> /* Swaps strings by swapping pointers */ void swap1(char **str1_ptr, char **str2_ptr){ char *temp = *str1_ptr; *str1_ptr = *str2_ptr; *str2_ptr = temp;} int main(){ char *str1 = \"geeks\"; char *str2 = \"forgeeks\"; swap1(&str1, &str2); printf(\"str1 is %s, str2 is %s\", str1, str2); getchar(); return 0;}", "e": 26842, "s": 26509, "text": null }, { "code": null, "e": 26918, "s": 26842, "text": "This method cannot be applied if strings are stored using character arrays." }, { "code": null, "e": 27043, "s": 26918, "text": "Method 2(Swap Data)If you are using character arrays to store strings then preferred way is to swap the data of both arrays." }, { "code": "#include<stdio.h>#include<string.h>#include<stdlib.h> /* Swaps strings by swapping data*/void swap2(char *str1, char *str2){ char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char)); strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); free(temp);} int main(){ char str1[10] = \"geeks\"; char str2[10] = \"forgeeks\"; swap2(str1, str2); printf(\"str1 is %s, str2 is %s\", str1, str2); getchar(); return 0;}", "e": 27474, "s": 27043, "text": null }, { "code": null, "e": 27553, "s": 27474, "text": "This method cannot be applied for strings stored in read-only block of memory." }, { "code": null, "e": 27699, "s": 27553, "text": "Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27718, "s": 27699, "text": "C Array and String" }, { "code": null, "e": 27727, "s": 27718, "text": "Articles" }, { "code": null, "e": 27738, "s": 27727, "text": "C Language" }, { "code": null, "e": 27836, "s": 27738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27864, "s": 27836, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 27917, "s": 27864, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 27941, "s": 27917, "text": "SQL Interview Questions" }, { "code": null, "e": 27977, "s": 27941, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 27996, "s": 27977, "text": "Mutex vs Semaphore" }, { "code": null, "e": 28012, "s": 27996, "text": "Arrays in C/C++" }, { "code": null, "e": 28090, "s": 28012, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 28113, "s": 28090, "text": "std::sort() in C++ STL" }, { "code": null, "e": 28140, "s": 28113, "text": "Bitwise Operators in C/C++" } ]
GATE | GATE-CS-2005 | Question 87 - GeeksforGeeks
28 Jun, 2021 We are given 9 tasks T1, T2.... T9. The execution of each task requires one unit of time. We can execute one task at a time. Each task Ti has a profit Pi and a deadline di Profit Pi is earned if the task is completed before the end of the dith unit of time. Task T1 T2 T3 T4 T5 T6 T7 T8 T9 Profit 15 20 30 18 18 10 23 16 25 Deadline 7 2 5 3 4 5 2 7 3 Are all tasks completed in the schedule that gives maximum profit?(A) All tasks are completed(B) T1 and T6 are left out(C) T1 and T8 are left out(D) T4 and T6 are left outAnswer: (D)Explanation: Task T1 T2 T3 T4 T5 T6 T7 T8 T9 Profit 15 20 30 18 18 10 23 16 25 Deadline 7 2 5 3 4 5 2 7 3 To maximize profit, we can finish tasks in following order T7, T2, T9, T5, T3, T8, T1Quiz of this Question GATE-CS-2005 GATE-GATE-CS-2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25953, "s": 25695, "text": "We are given 9 tasks T1, T2.... T9. The execution of each task requires one unit of time. We can execute one task at a time. Each task Ti has a profit Pi and a deadline di Profit Pi is earned if the task is completed before the end of the dith unit of time." }, { "code": null, "e": 26103, "s": 25953, "text": "Task T1 T2 T3 T4 T5 T6 T7 T8 T9\nProfit 15 20 30 18 18 10 23 16 25\nDeadline 7 2 5 3 4 5 2 7 3 " }, { "code": null, "e": 26298, "s": 26103, "text": "Are all tasks completed in the schedule that gives maximum profit?(A) All tasks are completed(B) T1 and T6 are left out(C) T1 and T8 are left out(D) T4 and T6 are left outAnswer: (D)Explanation:" }, { "code": null, "e": 26448, "s": 26298, "text": "Task T1 T2 T3 T4 T5 T6 T7 T8 T9\nProfit 15 20 30 18 18 10 23 16 25\nDeadline 7 2 5 3 4 5 2 7 3 " }, { "code": null, "e": 26555, "s": 26448, "text": "To maximize profit, we can finish tasks in following order T7, T2, T9, T5, T3, T8, T1Quiz of this Question" }, { "code": null, "e": 26568, "s": 26555, "text": "GATE-CS-2005" }, { "code": null, "e": 26586, "s": 26568, "text": "GATE-GATE-CS-2005" }, { "code": null, "e": 26591, "s": 26586, "text": "GATE" }, { "code": null, "e": 26689, "s": 26591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26723, "s": 26689, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26757, "s": 26723, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26791, "s": 26757, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26824, "s": 26791, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26860, "s": 26824, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26896, "s": 26860, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26930, "s": 26896, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26964, "s": 26930, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26998, "s": 26964, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Distributing all balls without repetition - GeeksforGeeks
29 Apr, 2022 Given N balls. For convenience, we denote the color of each ball as — lowercase letters. We have to distribute N balls among K people. They will be upset if they get two balls of the same color. We can give any number of balls to people and they won’t be upset even if they do not get any balls, but, we have to distribute all the balls, such that no one will be upset — print YES, if it is possible, and NO, otherwise. Examples: Input : 4 2 // value of N and K aabb // colors of given balls Output : YES We can give 1st and 3rd ball to the first person, and 2nd and 4th to the second. Input : 6 3 // value of N and K aacaab // colors of given balls Output : NO We need to give all balls of color a, but one ball will stay, that's why answer is NO The approach will be really simple. We will create a count array to keep the count of each color that occurs and then we will check if any color occurs more than the number of people we have. If it occurs, we will print NO else YES. The implementation of the above idea is given below. C++ Java Python3 C# Javascript // CPP program to find if its possible to// distribute balls without repetition#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to find if its possible to// distribute balls or notbool distributingBalls(int k, int n, string str){ // count array to count how many times // each color has occurred int a[MAX_CHAR] = {0}; for (int i = 0; i < n; i++){ // increasing count of each color // every time it appears a[str[i] - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color appears // more than K times if it does // we will print NO if (a[i] > k) return false; return true;} // Driver codeint main(){ long long int n = 6, k = 3; string str = "aacaab"; if (distributingBalls(k, n, str)) cout << "YES"; else cout << "NO"; return 0;} // Java program to find if its possible// to distribute balls without repetitionimport java.io.*; public class GFG { static int MAX_CHAR = 26; // function to find if its possible // to distribute balls or not static boolean distributingBalls(long k, long n, String str) { // count array to count how many // times each color has occurred int []a = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str.charAt(i) - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color appears // more than K times if it does // we will print NO if (a[i] > k) return false; return true; } // Driver code static public void main (String[] args) { long n = 6, k = 3; String str = "aacaab"; if (distributingBalls(k, n, str)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by vt_m. # Python3 program to find if its possible to# distribute balls without repetition MAX_CHAR = 26 # function to find if its possible to# distribute balls or notdef distributingBalls(k, n, string) : # count array to count how many times # each color has occurred a = [0] * MAX_CHAR for i in range(n) : # increasing count of each color # every time it appears a[ord(string[i]) - ord('a')] += 1 for i in range(MAX_CHAR) : # to check if any color appears # more than K times if it does # we will print NO if (a[i] > k) : return False return True # Driver codeif __name__ == "__main__" : n, k = 6, 3 string = "aacaab" if (distributingBalls(k, n, string)) : print("YES") else : print("NO") # This code is contributed by Ryuga // C# program to find if its possible to// distribute balls without repetitionusing System; public class GFG { static int MAX_CHAR = 26; // function to find if its possible // to distribute balls or not static bool distributingBalls(long k, long n, string str) { // count array to count how many // times each color has occurred int []a = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str[i] - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color // appears more than K // times if it does we // will print NO if (a[i] > k) return false; return true; } // Driver code static public void Main () { long n = 6, k = 3; string str = "aacaab"; if (distributingBalls(k, n, str)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed by vt_m. <script> // Javascript program to find if its possible to // distribute balls without repetition let MAX_CHAR = 26; // function to find if its possible // to distribute balls or not function distributingBalls(k, n, str) { // count array to count how many // times each color has occurred let a = new Array(MAX_CHAR); a.fill(0); for (let i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str[i].charCodeAt() - 'a'.charCodeAt()]++; } for (let i = 0; i < MAX_CHAR; i++) // to check if any color // appears more than K // times if it does we // will print NO if (a[i] > k) return false; return true; } let n = 6, k = 3; let str = "aacaab"; if (distributingBalls(k, n, str)) document.write("YES"); else document.write("NO"); </script> Output: NO This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m ankthon suresh07 surinderdawra388 School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Constructors in C++ Operator Overloading in C++ Copy Constructor in C++ Polymorphism in C++ Write a program to reverse an array or string Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching
[ { "code": null, "e": 26270, "s": 26242, "text": "\n29 Apr, 2022" }, { "code": null, "e": 26690, "s": 26270, "text": "Given N balls. For convenience, we denote the color of each ball as — lowercase letters. We have to distribute N balls among K people. They will be upset if they get two balls of the same color. We can give any number of balls to people and they won’t be upset even if they do not get any balls, but, we have to distribute all the balls, such that no one will be upset — print YES, if it is possible, and NO, otherwise." }, { "code": null, "e": 26701, "s": 26690, "text": "Examples: " }, { "code": null, "e": 27038, "s": 26701, "text": "Input : 4 2 // value of N and K\n aabb // colors of given balls\nOutput : YES\nWe can give 1st and 3rd ball to the first person,\nand 2nd and 4th to the second.\n\nInput : 6 3 // value of N and K\n aacaab // colors of given balls\nOutput : NO\nWe need to give all balls of color a, but one \nball will stay, that's why answer is NO " }, { "code": null, "e": 27271, "s": 27038, "text": "The approach will be really simple. We will create a count array to keep the count of each color that occurs and then we will check if any color occurs more than the number of people we have. If it occurs, we will print NO else YES." }, { "code": null, "e": 27326, "s": 27271, "text": "The implementation of the above idea is given below. " }, { "code": null, "e": 27330, "s": 27326, "text": "C++" }, { "code": null, "e": 27335, "s": 27330, "text": "Java" }, { "code": null, "e": 27343, "s": 27335, "text": "Python3" }, { "code": null, "e": 27346, "s": 27343, "text": "C#" }, { "code": null, "e": 27357, "s": 27346, "text": "Javascript" }, { "code": "// CPP program to find if its possible to// distribute balls without repetition#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // function to find if its possible to// distribute balls or notbool distributingBalls(int k, int n, string str){ // count array to count how many times // each color has occurred int a[MAX_CHAR] = {0}; for (int i = 0; i < n; i++){ // increasing count of each color // every time it appears a[str[i] - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color appears // more than K times if it does // we will print NO if (a[i] > k) return false; return true;} // Driver codeint main(){ long long int n = 6, k = 3; string str = \"aacaab\"; if (distributingBalls(k, n, str)) cout << \"YES\"; else cout << \"NO\"; return 0;}", "e": 28266, "s": 27357, "text": null }, { "code": "// Java program to find if its possible// to distribute balls without repetitionimport java.io.*; public class GFG { static int MAX_CHAR = 26; // function to find if its possible // to distribute balls or not static boolean distributingBalls(long k, long n, String str) { // count array to count how many // times each color has occurred int []a = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str.charAt(i) - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color appears // more than K times if it does // we will print NO if (a[i] > k) return false; return true; } // Driver code static public void main (String[] args) { long n = 6, k = 3; String str = \"aacaab\"; if (distributingBalls(k, n, str)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by vt_m.", "e": 29462, "s": 28266, "text": null }, { "code": "# Python3 program to find if its possible to# distribute balls without repetition MAX_CHAR = 26 # function to find if its possible to# distribute balls or notdef distributingBalls(k, n, string) : # count array to count how many times # each color has occurred a = [0] * MAX_CHAR for i in range(n) : # increasing count of each color # every time it appears a[ord(string[i]) - ord('a')] += 1 for i in range(MAX_CHAR) : # to check if any color appears # more than K times if it does # we will print NO if (a[i] > k) : return False return True # Driver codeif __name__ == \"__main__\" : n, k = 6, 3 string = \"aacaab\" if (distributingBalls(k, n, string)) : print(\"YES\") else : print(\"NO\") # This code is contributed by Ryuga", "e": 30305, "s": 29462, "text": null }, { "code": "// C# program to find if its possible to// distribute balls without repetitionusing System; public class GFG { static int MAX_CHAR = 26; // function to find if its possible // to distribute balls or not static bool distributingBalls(long k, long n, string str) { // count array to count how many // times each color has occurred int []a = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str[i] - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color // appears more than K // times if it does we // will print NO if (a[i] > k) return false; return true; } // Driver code static public void Main () { long n = 6, k = 3; string str = \"aacaab\"; if (distributingBalls(k, n, str)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by vt_m.", "e": 31482, "s": 30305, "text": null }, { "code": "<script> // Javascript program to find if its possible to // distribute balls without repetition let MAX_CHAR = 26; // function to find if its possible // to distribute balls or not function distributingBalls(k, n, str) { // count array to count how many // times each color has occurred let a = new Array(MAX_CHAR); a.fill(0); for (let i = 0; i < n; i++) { // increasing count of each // color every time it appears a[str[i].charCodeAt() - 'a'.charCodeAt()]++; } for (let i = 0; i < MAX_CHAR; i++) // to check if any color // appears more than K // times if it does we // will print NO if (a[i] > k) return false; return true; } let n = 6, k = 3; let str = \"aacaab\"; if (distributingBalls(k, n, str)) document.write(\"YES\"); else document.write(\"NO\"); </script>", "e": 32540, "s": 31482, "text": null }, { "code": null, "e": 32550, "s": 32540, "text": "Output: " }, { "code": null, "e": 32553, "s": 32550, "text": "NO" }, { "code": null, "e": 32975, "s": 32553, "text": "This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32980, "s": 32975, "text": "vt_m" }, { "code": null, "e": 32988, "s": 32980, "text": "ankthon" }, { "code": null, "e": 32997, "s": 32988, "text": "suresh07" }, { "code": null, "e": 33014, "s": 32997, "text": "surinderdawra388" }, { "code": null, "e": 33033, "s": 33014, "text": "School Programming" }, { "code": null, "e": 33041, "s": 33033, "text": "Strings" }, { "code": null, "e": 33049, "s": 33041, "text": "Strings" }, { "code": null, "e": 33147, "s": 33049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33166, "s": 33147, "text": "Interfaces in Java" }, { "code": null, "e": 33186, "s": 33166, "text": "Constructors in C++" }, { "code": null, "e": 33214, "s": 33186, "text": "Operator Overloading in C++" }, { "code": null, "e": 33238, "s": 33214, "text": "Copy Constructor in C++" }, { "code": null, "e": 33258, "s": 33238, "text": "Polymorphism in C++" }, { "code": null, "e": 33304, "s": 33258, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33364, "s": 33304, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33439, "s": 33364, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 33496, "s": 33439, "text": "Python program to check if a string is palindrome or not" } ]