title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
string capitalize() in Python - GeeksforGeeks
|
02 Dec, 2020
In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters.
Syntax:
string_name.capitalize()
string_name: It is the name of string of
whose first character we want
to capitalize.
Parameter: The capitalize() function does not takes any parameter. Return value: The capitalize() function returns a string with the first character in the capital. Below is the python program to illustrate capitalize() function:
Python
# Python program to demonstrate the# use of capitalize() function # capitalize() first letter of string# and make other letters lowercasename = "geeks FOR geeks" print(name.capitalize()) # demonstration of individual words# capitalization to generate camel casename1 = "geeks"name2 = "for"name3 = "geeks"print(name1.capitalize() + name2.capitalize() + name3.capitalize())
Output:
Geeks for geeks
GeeksForGeeks
tim22
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 23822,
"s": 23794,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 24042,
"s": 23822,
"text": "In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters. "
},
{
"code": null,
"e": 24051,
"s": 24042,
"text": "Syntax: "
},
{
"code": null,
"e": 24190,
"s": 24051,
"text": "string_name.capitalize() \n\nstring_name: It is the name of string of\n whose first character we want\n to capitalize."
},
{
"code": null,
"e": 24422,
"s": 24190,
"text": "Parameter: The capitalize() function does not takes any parameter. Return value: The capitalize() function returns a string with the first character in the capital. Below is the python program to illustrate capitalize() function: "
},
{
"code": null,
"e": 24429,
"s": 24422,
"text": "Python"
},
{
"code": "# Python program to demonstrate the# use of capitalize() function # capitalize() first letter of string# and make other letters lowercasename = \"geeks FOR geeks\" print(name.capitalize()) # demonstration of individual words# capitalization to generate camel casename1 = \"geeks\"name2 = \"for\"name3 = \"geeks\"print(name1.capitalize() + name2.capitalize() + name3.capitalize())",
"e": 24825,
"s": 24429,
"text": null
},
{
"code": null,
"e": 24835,
"s": 24825,
"text": "Output: "
},
{
"code": null,
"e": 24865,
"s": 24835,
"text": "Geeks for geeks\nGeeksForGeeks"
},
{
"code": null,
"e": 24873,
"s": 24867,
"text": "tim22"
},
{
"code": null,
"e": 24887,
"s": 24873,
"text": "python-string"
},
{
"code": null,
"e": 24894,
"s": 24887,
"text": "Python"
},
{
"code": null,
"e": 24992,
"s": 24894,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25020,
"s": 24992,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 25070,
"s": 25020,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 25092,
"s": 25070,
"text": "Python map() function"
},
{
"code": null,
"e": 25136,
"s": 25092,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 25154,
"s": 25136,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25177,
"s": 25154,
"text": "Taking input in Python"
},
{
"code": null,
"e": 25212,
"s": 25177,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25234,
"s": 25212,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25266,
"s": 25234,
"text": "How to Install PIP on Windows ?"
}
] |
How to enable or disable nested checkboxes in jQuery ? - GeeksforGeeks
|
10 Dec, 2020
In this article, we will see how to enable or disable nested checkboxes in jQuery. To do that, we select all child checkboxes and add disabled attributes to them with the help of the attr() method in jQuery so that all checkboxes will be disabled.
Syntax:
// Select all child input of type checkbox
// with class child-checkbox
// And add the disabled attribute to them
$('.child-checkbox input[type=checkbox]')
.attr('disabled', true);
After that, we add a click event listener to the parent checkbox, so when we click on the parent checkbox, if it is checked, all of its child checkboxes become enable. Else it’s all child checkboxes become disable.
Below is the implementation of this approach :
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title> How to enable or disable nested checkboxes in jQuery? </title> <!-- Link of JQuery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script></head> <body> <div class="container"> <div class="parent-checkbox"> <input type="checkbox"> Govt. employe </div> <div class="child-checkbox"> <input type="checkbox"> ldc <input type="checkbox"> clerk <input type="checkbox"> watchmen </div> </div> <script> // Select child-checkbox classes all checkbox // And add disabled attributes to them $('.child-checkbox input[type=checkbox]'). attr('disabled', true); // When we check parent-checkbox then remove disabled // Attributes to its child checkboxes $(document).on('click', '.parent-checkbox input[type=checkbox]', function (event) { // If parent-checkbox is checked add // disabled attributes to its child if ($(this).is(":checked")) { $(this).closest(".container"). find(".child-checkbox > input[type=checkbox]"). attr("disabled", false); } else { // Else add disabled attrubutes to its // all child checkboxes $(this).closest(".container"). find(".child-checkbox > input[type=checkbox]"). attr("disabled", true); } }); </script></body> </html>
Output:
When parent checkbox disable:
When parent checkbox enable:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Form validation using jQuery
Making a div vertically scrollable using CSS
CSS | :not(:last-child):after Selector
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 24921,
"s": 24893,
"text": "\n10 Dec, 2020"
},
{
"code": null,
"e": 25169,
"s": 24921,
"text": "In this article, we will see how to enable or disable nested checkboxes in jQuery. To do that, we select all child checkboxes and add disabled attributes to them with the help of the attr() method in jQuery so that all checkboxes will be disabled."
},
{
"code": null,
"e": 25177,
"s": 25169,
"text": "Syntax:"
},
{
"code": null,
"e": 25362,
"s": 25177,
"text": "// Select all child input of type checkbox\n// with class child-checkbox\n// And add the disabled attribute to them\n$('.child-checkbox input[type=checkbox]')\n .attr('disabled', true);"
},
{
"code": null,
"e": 25577,
"s": 25362,
"text": "After that, we add a click event listener to the parent checkbox, so when we click on the parent checkbox, if it is checked, all of its child checkboxes become enable. Else it’s all child checkboxes become disable."
},
{
"code": null,
"e": 25624,
"s": 25577,
"text": "Below is the implementation of this approach :"
},
{
"code": null,
"e": 25633,
"s": 25624,
"text": "Example:"
},
{
"code": null,
"e": 25638,
"s": 25633,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> How to enable or disable nested checkboxes in jQuery? </title> <!-- Link of JQuery cdn --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script></head> <body> <div class=\"container\"> <div class=\"parent-checkbox\"> <input type=\"checkbox\"> Govt. employe </div> <div class=\"child-checkbox\"> <input type=\"checkbox\"> ldc <input type=\"checkbox\"> clerk <input type=\"checkbox\"> watchmen </div> </div> <script> // Select child-checkbox classes all checkbox // And add disabled attributes to them $('.child-checkbox input[type=checkbox]'). attr('disabled', true); // When we check parent-checkbox then remove disabled // Attributes to its child checkboxes $(document).on('click', '.parent-checkbox input[type=checkbox]', function (event) { // If parent-checkbox is checked add // disabled attributes to its child if ($(this).is(\":checked\")) { $(this).closest(\".container\"). find(\".child-checkbox > input[type=checkbox]\"). attr(\"disabled\", false); } else { // Else add disabled attrubutes to its // all child checkboxes $(this).closest(\".container\"). find(\".child-checkbox > input[type=checkbox]\"). attr(\"disabled\", true); } }); </script></body> </html>",
"e": 27400,
"s": 25638,
"text": null
},
{
"code": null,
"e": 27408,
"s": 27400,
"text": "Output:"
},
{
"code": null,
"e": 27438,
"s": 27408,
"text": "When parent checkbox disable:"
},
{
"code": null,
"e": 27467,
"s": 27438,
"text": "When parent checkbox enable:"
},
{
"code": null,
"e": 27604,
"s": 27467,
"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": 27613,
"s": 27604,
"text": "CSS-Misc"
},
{
"code": null,
"e": 27623,
"s": 27613,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27635,
"s": 27623,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 27642,
"s": 27635,
"text": "Picked"
},
{
"code": null,
"e": 27646,
"s": 27642,
"text": "CSS"
},
{
"code": null,
"e": 27651,
"s": 27646,
"text": "HTML"
},
{
"code": null,
"e": 27658,
"s": 27651,
"text": "JQuery"
},
{
"code": null,
"e": 27675,
"s": 27658,
"text": "Web Technologies"
},
{
"code": null,
"e": 27702,
"s": 27675,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27707,
"s": 27702,
"text": "HTML"
},
{
"code": null,
"e": 27805,
"s": 27707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27846,
"s": 27805,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27883,
"s": 27846,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27912,
"s": 27883,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27957,
"s": 27912,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 27996,
"s": 27957,
"text": "CSS | :not(:last-child):after Selector"
},
{
"code": null,
"e": 28056,
"s": 27996,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28117,
"s": 28056,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28170,
"s": 28117,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28220,
"s": 28170,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Check if a File is Hidden in Java - GeeksforGeeks
|
18 Apr, 2022
isHidden() method of File class in Java can use be used to check if a file is hidden or not. This method returns a boolean value – true or false.
Syntax:
public static boolean isHidden(Path path)
throws IOException
Parameters: Path to the file to test.
Return Type: A boolean value, true if file is found hidden else returns false as a file is not found hidden
Exceptions Thrown:
IOException: If an I/O error occurs
SecurityException: In the case of the default provider, and a security manager is installed, the checkRead() method is invoked to check read access to the file.
Remember: Depending on the implementation the isHidden() method may require to access the file system to determine if the file is considered hidden.
Example:
Java
// Java Program to Check if Given File is Hidden or Not// Using isHidden() Method of File class // Importing required classesimport java.io.File;import java.io.IOException; // Main class// HiddenFileCheckpublic class GFG { // Main driver method public static void main(String[] args) throws IOException, SecurityException { // Creating a file by // creating an object of File class File file = new File( "/users/mayanksolanki/Desktop/demo.rtf"); // Checking whether file is hidden or not // using isHidden() method if (file.isHidden()) // Print statement as file is found hidden System.out.println( "The specified file is hidden"); else // Print statement as file is found as not // hidden System.out.println( "The specified file is not hidden"); }}
Output:
Output Explanation: As it can easily be visualized from the background of the output that the ‘demo.rtf’ file popping icon is clearly seen. The code reflects that a specific file is not hidden on the terminal output as seen above.
Note: The precise definition of hidden is a platform or provider-dependent.
UNIX: A file is hidden if its name begins with a period character (‘.’).
Windows: A file is hidden if it is not a directory and the DOS hidden attribute is set.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
java-file-handling
Java-I/O
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23972,
"s": 23944,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24118,
"s": 23972,
"text": "isHidden() method of File class in Java can use be used to check if a file is hidden or not. This method returns a boolean value – true or false."
},
{
"code": null,
"e": 24126,
"s": 24118,
"text": "Syntax:"
},
{
"code": null,
"e": 24188,
"s": 24126,
"text": "public static boolean isHidden(Path path) \nthrows IOException"
},
{
"code": null,
"e": 24226,
"s": 24188,
"text": "Parameters: Path to the file to test."
},
{
"code": null,
"e": 24335,
"s": 24226,
"text": "Return Type: A boolean value, true if file is found hidden else returns false as a file is not found hidden "
},
{
"code": null,
"e": 24354,
"s": 24335,
"text": "Exceptions Thrown:"
},
{
"code": null,
"e": 24390,
"s": 24354,
"text": "IOException: If an I/O error occurs"
},
{
"code": null,
"e": 24551,
"s": 24390,
"text": "SecurityException: In the case of the default provider, and a security manager is installed, the checkRead() method is invoked to check read access to the file."
},
{
"code": null,
"e": 24700,
"s": 24551,
"text": "Remember: Depending on the implementation the isHidden() method may require to access the file system to determine if the file is considered hidden."
},
{
"code": null,
"e": 24709,
"s": 24700,
"text": "Example:"
},
{
"code": null,
"e": 24714,
"s": 24709,
"text": "Java"
},
{
"code": "// Java Program to Check if Given File is Hidden or Not// Using isHidden() Method of File class // Importing required classesimport java.io.File;import java.io.IOException; // Main class// HiddenFileCheckpublic class GFG { // Main driver method public static void main(String[] args) throws IOException, SecurityException { // Creating a file by // creating an object of File class File file = new File( \"/users/mayanksolanki/Desktop/demo.rtf\"); // Checking whether file is hidden or not // using isHidden() method if (file.isHidden()) // Print statement as file is found hidden System.out.println( \"The specified file is hidden\"); else // Print statement as file is found as not // hidden System.out.println( \"The specified file is not hidden\"); }}",
"e": 25633,
"s": 24714,
"text": null
},
{
"code": null,
"e": 25642,
"s": 25633,
"text": "Output: "
},
{
"code": null,
"e": 25873,
"s": 25642,
"text": "Output Explanation: As it can easily be visualized from the background of the output that the ‘demo.rtf’ file popping icon is clearly seen. The code reflects that a specific file is not hidden on the terminal output as seen above."
},
{
"code": null,
"e": 25949,
"s": 25873,
"text": "Note: The precise definition of hidden is a platform or provider-dependent."
},
{
"code": null,
"e": 26022,
"s": 25949,
"text": "UNIX: A file is hidden if its name begins with a period character (‘.’)."
},
{
"code": null,
"e": 26111,
"s": 26022,
"text": "Windows: A file is hidden if it is not a directory and the DOS hidden attribute is set. "
},
{
"code": null,
"e": 26531,
"s": 26111,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26545,
"s": 26531,
"text": "solankimayank"
},
{
"code": null,
"e": 26564,
"s": 26545,
"text": "java-file-handling"
},
{
"code": null,
"e": 26573,
"s": 26564,
"text": "Java-I/O"
},
{
"code": null,
"e": 26586,
"s": 26573,
"text": "Java-Library"
},
{
"code": null,
"e": 26591,
"s": 26586,
"text": "Java"
},
{
"code": null,
"e": 26596,
"s": 26591,
"text": "Java"
},
{
"code": null,
"e": 26694,
"s": 26596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26709,
"s": 26694,
"text": "Stream In Java"
},
{
"code": null,
"e": 26755,
"s": 26709,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26776,
"s": 26755,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26795,
"s": 26776,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26825,
"s": 26795,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26842,
"s": 26825,
"text": "Generics in Java"
},
{
"code": null,
"e": 26885,
"s": 26842,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26914,
"s": 26885,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26935,
"s": 26914,
"text": "Introduction to Java"
}
] |
TPOT Automated Machine Learning in Python | by Jeff Hale | Towards Data Science
|
In this post I’m sharing some of my explorations with TPOT, an automated machine learning (autoML) tool in Python. The goal is to see what TPOT can do and if it merits becoming part of your machine learning workflow.
Automated machine learning doesn’t replace the data scientist, (at least not yet) but it might be able to help you find good models faster. TPOT bills itself as your Data Science Assistant.
TPOT is meant to be an assistant that gives you ideas on how to solve a particular machine learning problem by exploring pipeline configurations that you might have never considered, then leaves the fine-tuning to more constrained parameter tuning techniques such as grid search.
So TPOT helps you find good algorithms. Note that it isn’t designed for automating deep learning — something like AutoKeras might be helpful there.
TPOT is built on the scikit learn library and follows the scikit learn API closely. It can be used for regression and classification tasks and has special implementations for medical research.
TPOT is open source, well documented, and under active development. It’s development was spearheaded by researchers at the University of Pennsylvania. TPOT appears to be one of the most popular autoML libraries, with nearly 4,500 GitHub stars as of August 2018.
TPOT has what its developers call a genetic search algorithm to find the best parameters and model ensembles. It could also be thought of as a natural selection or evolutionary algorithm. TPOT tries a pipeline, evaluates its performance, and randomly changes parts of the pipeline in search of better performing algorithms.
AutoML algorithms aren’t as simple as fitting one model on the dataset; they are considering multiple machine learning algorithms (random forests, linear models, SVMs, etc.) in a pipeline with multiple preprocessing steps (missing value imputation, scaling, PCA, feature selection, etc.), the hyperparameters for all of the models and preprocessing steps, as well as multiple ways to ensemble or stack the algorithms within the pipeline. (source: TPOT docs)
This power of TPOT comes from evaluating all kinds of possible pipelines automatically and efficiently. Doing this manually is cumbersome and slower.
Instantiating, fitting, and scoring the TPOT classifier is similar to any other sklearn classifier. Here’s the format:
tpot = TPOTClassifier()tpot.fit(X_train, y_train)tpot.score(X_test, y_test)
TPOT comes with its own variation of one-hot encoding. Note that it could add it to a pipeline automatically because it treats features with fewer than 10 unique values as categorical. If you want to use your own encoding strategy you can encode your data and then feed it into TPOT.
You can choose the scoring criterion for tpot.score (although a bug with Jupyter and multiple processor cores prevents you from having a custom scoring criterion with multiple processor cores in a Jupyter notebook).
It appears that you can’t alter the scoring criteria TPOT uses internally as it searches for the best pipeline, just the scoring criteria for use on the test set after TPOT has chosen the best algorithms. This is an area where some users might want more control. Perhaps this option will be added in a future version.
TPOT writes information about the best performing algorithm and it’s accuracy score to a file with tpot.export(). You can choose the level of verboseness you would like to see as TPOT runs and have it write pipelines to an output file as it runs in case it terminates early for some reason (e.g. your Kaggle Kernel crashes).
The short answer is that it depends.
TPOT was designed to run for a while — hours or even a day. Although less complex problems with smaller datasets can see great results in minutes. You can adjust several parameters for TPOT to finish its searches faster, but at the expense of a less thorough search for an optimal pipeline. It was not designed to be a comprehensive search of preprocessing steps, feature selection, algorithms, and parameters, but it can come close if you set its parameters to be more exhaustive.
As the docs explain:
...TPOT will take a while to run on larger datasets, but it’s important to realize why. With the default TPOT settings (100 generations with 100 population size), TPOT will evaluate 10,000 pipeline configurations before finishing. To put this number into context, think about a grid search of 10,000 hyperparameter combinations for a machine learning algorithm and how long that grid search will take. That is 10,000 model configurations to evaluate with 10-fold cross-validation, which means that roughly 100,000 models are fit and evaluated on the training data in one grid search.
Some of the data sets we’ll see below only need a few minutes to find algorithms that score well; others might need days.
Here are the default TPOTClassifier parameters:
generations=100, population_size=100, offspring_size=None # Jeff notes this gets set to population_sizemutation_rate=0.9, crossover_rate=0.1, scoring="Accuracy", # for Classificationcv=5, subsample=1.0, n_jobs=1,max_time_mins=None, max_eval_time_mins=5,random_state=None, config_dict=None,warm_start=False, memory=None,periodic_checkpoint_folder=None, early_stop=Noneverbosity=0disable_update_check=False
A description of each parameter can be found the docs. Here are a few key ones that determine the number of pipelines TPOT will search through:
generations: int, optional (default: 100) Number of iterations to the run pipeline optimization process. Generally, TPOT will work better when you give it more generations(and therefore time) to optimize the pipeline. TPOT will evaluate POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE pipelines in total (emphasis mine).population_size: int, optional (default: 100) Number of individuals to retain in the GP population every generation. Generally, TPOT will work better when you give it more individuals (and therefore time) to optimize the pipeline. offspring_size: int, optional (default: None)Number of offspring to produce in each GP generation. By default, offspring_size = population_size.
When starting out with TPOT it’s worth setting verbosity=3 and periodic_checkpoint_folder=“any_string_you_like” so that you can watch the models evolve and training scores improve. You’ll see some errors as some combinations of pipeline elements are incompatible, but don’t sweat that.
If you’re running on multiple cores and not using a custom scoring function, set n_jobs=-1 to use all available cores and speed up TPOT.
Here are the classification algorithms and parameters TPOT chooses from as of version 0.9:
‘sklearn.naive_bayes.BernoulliNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.naive_bayes.MultinomialNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.tree.DecisionTreeClassifier’: { ‘criterion’: [“gini”, “entropy”], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21) }, ‘sklearn.ensemble.ExtraTreesClassifier’: { ‘n_estimators’: [100], ‘criterion’: [“gini”, “entropy”], ‘max_features’: np.arange(0.05, 1.01, 0.05), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘bootstrap’: [True, False] },‘sklearn.ensemble.RandomForestClassifier’: { ‘n_estimators’: [100], ‘criterion’: [“gini”, “entropy”], ‘max_features’: np.arange(0.05, 1.01, 0.05), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘bootstrap’: [True, False] }, ‘sklearn.ensemble.GradientBoostingClassifier’: { ‘n_estimators’: [100], ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘max_features’: np.arange(0.05, 1.01, 0.05) },‘sklearn.neighbors.KNeighborsClassifier’: { ‘n_neighbors’: range(1, 101), ‘weights’: [“uniform”, “distance”], ‘p’: [1, 2] }, ‘sklearn.svm.LinearSVC’: { ‘penalty’: [“l1”, “l2”], ‘loss’: [“hinge”, “squared_hinge”], ‘dual’: [True, False], ‘tol’: [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.] }, ‘sklearn.linear_model.LogisticRegression’: { ‘penalty’: [“l1”, “l2”], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.], ‘dual’: [True, False] }, ‘xgboost.XGBClassifier’: { ‘n_estimators’: [100], ‘max_depth’: range(1, 11), ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘min_child_weight’: range(1, 21), ‘nthread’: [1] }
And TPOT can stack classifiers, including the same classifier multiple times. One of the core developers of TPOT explains how it works in this issue:
The pipeline ExtraTreesClassifier(ExtraTreesClassifier(input_matrix, True, 'entropy', 0.10000000000000001, 13, 6), True, 'gini', 0.75, 17, 4) does the following:
Fit all of the original features using an ExtraTreesClassifier
Take the predictions from that ExtraTreesClassifier and create a new feature using those predictions
Pass the original features plus the new “predicted feature” to the 2nd ExtraTreesClassifier and use its predictions as the final predictions of the pipeline
This process is called stacking classifiers, which is a fairly common tactic in machine learning.
And here are the 11 preprocessors that could be applied by TPOT as of version 0.9.
‘sklearn.preprocessing.Binarizer’: { ‘threshold’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.decomposition.FastICA’: { ‘tol’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.cluster.FeatureAgglomeration’: { ‘linkage’: [‘ward’, ‘complete’, ‘average’], ‘affinity’: [‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’, ‘cosine’] }, ‘sklearn.preprocessing.MaxAbsScaler’: { }, ‘sklearn.preprocessing.MinMaxScaler’: { }, ‘sklearn.preprocessing.Normalizer’: { ‘norm’: [‘l1’, ‘l2’, ‘max’] }, ‘sklearn.kernel_approximation.Nystroem’: { ‘kernel’: [‘rbf’, ‘cosine’, ‘chi2’, ‘laplacian’, ‘polynomial’, ‘poly’, ‘linear’, ‘additive_chi2’, ‘sigmoid’], ‘gamma’: np.arange(0.0, 1.01, 0.05), ‘n_components’: range(1, 11) }, ‘sklearn.decomposition.PCA’: { ‘svd_solver’: [‘randomized’], ‘iterated_power’: range(1, 11) }, ‘sklearn.preprocessing.PolynomialFeatures’: { ‘degree’: [2], ‘include_bias’: [False], ‘interaction_only’: [False] }, ‘sklearn.kernel_approximation.RBFSampler’: { ‘gamma’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.preprocessing.RobustScaler’: { }, ‘sklearn.preprocessing.StandardScaler’: { }, ‘tpot.builtins.ZeroCount’: { }, ‘tpot.builtins.OneHotEncoder’: { ‘minimum_fraction’: [0.05, 0.1, 0.15, 0.2, 0.25], ‘sparse’: [False] } (emphasis mine)
That’s a pretty comprehensive list of sklearn ml algorithms and even a few you might not have used for preprocessing, including Nystroem and RBFSampler. The final preprocessing algorithm listed is the custom OneHotEncoder mentioned before. Note that the list contains no neural network algorithms.
The number of combinations appears to be nearly infinite — you can stack algorithms, including instances of the same algorithm. There may be an internal cap on the number of steps in the pipeline, but suffice to say there are a plethora of possible pipelines.
TPOT will likely not result in the same algorithm selection if you run it twice (maybe not even if random_state is set, I found, as discussed below). As the docs explain:
If you’re working with a reasonably complex dataset or run TPOT for a short amount of time, different TPOT runs may result in different pipeline recommendations. TPOT’s optimization algorithm is stochastic in nature, which means that it uses randomness (in part) to search the possible pipeline space. When two TPOT runs recommend different pipelines, this means that the TPOT runs didn’t converge due to lack of time or that multiple pipelines perform more-or-less the same on your dataset.
Less talk — more action. Let’s try out TPOT on some data!
First we’ll look at a classification task — the popular handwriting digit classification task from MNIST included in sklearn’s datasets. The MNIST database contains 70,000 images of handwritten Arabic digits in 28x28 pixels, labeled from 0 to 9.
TPOT comes standard on the Kaggle Docker image, so you only need to import it if you’re using Kaggle — you don’t need to install it.
Here’s my code — available on this Kaggle Kernel, in a slightly different form and possibly with a few modifications.
# import the usual stuffimport numpy as np import pandas as pd import matplotlib.pyplot as pltimport seaborn as snsimport os# import TPOT and sklearn stufffrom tpot import TPOTClassifierfrom sklearn.datasets import load_digitsfrom sklearn.model_selection import train_test_splitimport sklearn.metrics# create train and test setsdigits = load_digits()X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, train_size=0.75, test_size=0.25, random_state=34)tpot = TPOTClassifier(verbosity=3, scoring="balanced_accuracy", random_state=23, periodic_checkpoint_folder="tpot_mnst1.txt", n_jobs=-1, generations=10, population_size=100)# run three iterations and time themfor x in range(3): start_time = timeit.default_timer() tpot.fit(X_train, y_train) elapsed = timeit.default_timer() - start_time times.append(elapsed) winning_pipes.append(tpot.fitted_pipeline_) scores.append(tpot.score(X_test, y_test)) tpot.export('tpot_mnist_pipeline.py')times = [time/60 for time in times]print('Times:', times)print('Scores:', scores) print('Winning pipelines:', winning_pipes)
As mentioned above, the total number of pipelines is equal to POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE.
For example, if you set population_size=20 and generations=5, then offspring_size=20 (because offspring_size equals population_size by default. And you’ll have a total of 120 pipelines because 20 + (5 * 20 ) = 120.
You can see it doesn’t take much code at all to run this data set — and that includes a loop to time and test it repeatedly.
With 10 possible classes and no reason to prefer one outcome to another, accuracy — the TPOT classification default — is a fine metric for this task.
Here’s the relevant code section.
digits = load_digits()X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, train_size=0.75, test_size=0.25, random_state=34)tpot = TPOTClassifier(verbosity=3, scoring=”accuracy”, random_state=32, periodic_checkpoint_folder=”tpot_results.txt”, n_jobs=-1, generations=5, population_size=10, early_stop=5)
And here are the results:
Times: [4.740584810283326, 3.497970838083226, 3.4362493358499098]Scores: [0.9733333333333334, 0.9644444444444444, 0.9666666666666667]Winning pipelines: [Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.1, loss='deviance', max_depth=7, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))])]
Note that with only 60 pipelines — far less than what TPOT suggests — we were able to see pretty good scores — over 97% accuracy on the test set in one case.
Does TPOT find the same winning pipeline every time with the same random_state set? Not necessarily. Individually algorithms such as RandomForrestClassifier() have their own random_state parameters that don’t get set.
TPOT doesn’t always find the same result if you instantiate one classifier and then fit it repeatedly like we do in the for loop in the code above. I ran three very small sets of 60 pipelines with random_state set and Kaggle’s GPU setting on. Note that we get slightly different pipelines and thus slightly different test set scores on the three test sets.
Here’s another example of a small number of pipelines with random state set and using Kaggle’s CPU setting.
Times: [2.8874817832668973, 0.043678393283335025, 0.04388708711679404]Scores: [0.9622222222222222, 0.9622222222222222, 0.9622222222222222]Winning pipelines: [Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))])]
The same pipeline was found each of the three times.
Note that the run time is much faster after the first iteration. TPOT does seem to remember when it has seen an algorithm and doesn’t rerun it, even if it’s a second fit and you’ve set memory=False. Here’s what you’ll see if you set the verbosity=3 when it finds such a previously evaluated pipeline:
Pipeline encountered that has previously been evaluated during the optimization process. Using the score from the previous evaluation.
How does TPOT do if you make a large number of pipelines? To really see the power of TPOT for the MNIST digits task, you need over 500 total pipelines to run. This will take at least an hour if you’re running it on Kaggle. Then you will see higher accuracy scores and might see more complex models.
Chained, or stacked, ensembles where the outputs of one machine learning algorithm feed into another are what you’ll likely see if you have a larger number of pipelines and a non-trivial task.
0.9950861171999883knn = KNeighborsClassifier( DecisionTreeClassifier( OneHotEncoder(input_matrix, OneHotEncoder__minimum_fraction=0.15, OneHotEncoder__sparse=False), DecisionTreeClassifier__criterion=gini, DecisionTreeClassifier__max_depth=5, DecisionTreeClassifier__min_samples_leaf=20, DecisionTreeClassifier__min_samples_split=17), KNeighborsClassifier__n_neighbors=1, KNeighborsClassifier__p=2, KNeighborsClassifier__weights=distance)
This is .995 average internal CV accuracy score after running for over an hour and generating over 600 pipelines. The kernel crashed before completion, so I didn’t get to see a test set score and couldn’t get an outputted model, but this looks quite promising for TPOT.
The algorithm uses a DecisionTreeClassifier with TPOT’s custom OneHotEncoder categorical encodings feeding into KNeighborsClassifier.
Here’s a similar internal score with a different pipeline resulting from a different random_state after nearly 800 pipelines.
0.9903723557310828 KNeighborsClassifier(Normalizer(OneHotEncoder(RandomForestClassifier(MinMaxScaler(input_matrix), RandomForestClassifier__bootstrap=True, RandomForestClassifier__criterion=entropy, RandomForestClassifier__max_features=0.55, RandomForestClassifier__min_samples_leaf=6, RandomForestClassifier__min_samples_split=15, RandomForestClassifier__n_estimators=100), OneHotEncoder__minimum_fraction=0.2, OneHotEncoder__sparse=False), Normalizer__norm=max), KNeighborsClassifier__n_neighbors=4, KNeighborsClassifier__p=2, KNeighborsClassifier__weights=distance)
TPOT found a pipeline with KNN, One Hot encoding, normalization, and random forest. It took two and a half hours. Previous one was faster and scored better, but sometimes that’s what happens with the stochastic nature of TPOT’s genetic search algorithm. 😉
TPOT can perform really well on this image recognition task if you give it enough time.TPOT works better with more pipelines.If you need reproducibility for a task, TPOT isn’t the tool you want.
TPOT can perform really well on this image recognition task if you give it enough time.
TPOT works better with more pipelines.
If you need reproducibility for a task, TPOT isn’t the tool you want.
For a second dataset I chose the popular mushroom classification task. The goal is to determine correctly whether a mushroom is poisonous based on its labels. This is not an image classification task. It’s set up as a binary task so that all potentially dangerous mushrooms are grouped as one category and safe to eat mushrooms as another category.
My code is available on this Kaggle Kernel.
TPOT can routinely fit a perfect model quickly on this data set. It did so in under two minutes. This is much better performance and speed than when I tested this dataset without TPOT with many scikit-learn classification algorithms, a wide range of nominal data encodings, and no parameter tuning.
On three runs with the same TPOTClassifier instance and the same random state set here’s what TPOT found:
Times: [1.854785452616731, 1.5694829618000463, 1.3383520993001488]Scores: [1.0, 1.0, 1.0]
Interestingly, it found a different best algorithm each time. It found a DecisionTreeClassifier, then a KNeighorsClassifier, and then a Stacked RandomForestClassifier with BernoulliNB.
Let’s dig into reproducibility a bit more. Let’s run it again with everything exactly the same settings.
Times: [1.8664863013502326, 1.5520636909670429, 1.3386059726501116]Scores: [1.0, 1.0, 1.0]
We see the same set of three pipelines, very similar times, and the same scores on the test set.
Now let’s try splitting the cell into multiple different cells and instantiating a TPOT instance in each one. Here’s the code:
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=0.25, random_state=25)tpot = TPOTClassifier( verbosity=3, scoring=”accuracy”, random_state=25, periodic_checkpoint_folder=”tpot_mushroom_results.txt”, n_jobs=-1, generations=5, population_size=10, early_stop = 5)
The result of the second run now matches the result of the first one and took almost the same time (Score = 1.0, Time = 1.9 minutes, pipeline = Decision Tree Classifier). The key for higher reproducibility is that we are instantiating a new instance of the TPOT classifier in each cell.
Time results from 10 sets of 30 pipelines with random_state on train_test_split and TPOT set to 10 are below. All pipelines correctly classified all mushrooms on the test set. TPOT was quite fast on this fairly easy-to-learn task.
TPOT performs well and quickly for this basic classification task.
As a comparison, this Kaggle kernel on the mushroom set in R is very nice and explores a variety of algorithms and gets very close to perfect accuracy. But it doesn’t quite reach 100% and it certainly took quite a bit more time to prepare and train than our implementation of TPOT.
I would strongly consider TPOT as a time saver for a task like this in the future, at least as a first step.
Next we turn to a regression task to see how TPOT performs. We’ll predict housing property sale values with the popular Ames, Iowa Housing Price Prediction dataset. My code is available on this Kaggle Kernel.
For this task, I did some basic imputation of missing values first. I filled missing numeric column values with the most frequent value for the column, because some of those columns contain ordinal data. With more time I’d categorize the columns and use different imputation strategies depending on interval, ordinal, or nominal data types.
String column missing values were filled with a “missing” label prior to ordinal encoding because not all columns had a most frequent value. TPOT’s one hot encoding algorithm would then make one more dimension per feature that would indicate that the data had a missing value for that feature.
TPOTRegressor uses mean squared error scoring by default.
Here’s a run with only 60 pipelines.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .25, random_state = 33)# instantiate tpot tpot = TPOTRegressor(verbosity=3, random_state=25, n_jobs=-1, generations=5, population_size=10, early_stop = 5, memory = None)times = []scores = []winning_pipes = []# run 3 iterationsfor x in range(3): start_time = timeit.default_timer() tpot.fit(X_train, y_train) elapsed = timeit.default_timer() - start_time times.append(elapsed) winning_pipes.append(tpot.fitted_pipeline_) scores.append(tpot.score(X_test, y_test)) tpot.export('tpot_ames.py')# output resultstimes = [time/60 for time in times]print('Times:', times)print('Scores:', scores) print('Winning pipelines:', winning_pipes)
The results of these three little runs.
Times: [3.8920086714831994, 1.4063017464330188, 1.2469199204002508]Scores: [-905092886.3009057, -922269561.2683483, -949881926.6436856]Winning pipelines: [Pipeline(memory=None, steps=[('zerocount', ZeroCount()), ('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=18, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))]), Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=11, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))]), Pipeline(memory=None, steps=[('stackingestimator', StackingEstimator(estimator=RidgeCV(alphas=array([ 0.1, 1. , 10. ]), cv=None, fit_intercept=True, gcv_mode=None, normalize=False, scoring=None, store_cv_values=False))), ('maxabsscaler-1', MaxAbsScaler(copy=True)), ('maxabsscaler-2', MaxAbsScaler(copy=True)), ('xgbr... reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))])]
The runs finished pretty quickly and found different winning pipelines each time. Taking the square root of the scores gives us the Root Mean Squared Error (RMSE). The RMSE was around $30,000 on average.
Trying with 60 pipelines and a random_state = 20 for train_test_split and TPOTRegressor.
Times: [9.691357856966594, 1.8972856383004304, 2.5272325469001466]Scores: [-1061075530.3715296, -695536167.1288683, -783733389.9523941]Winning pipelines: [Pipeline(memory=None, steps=[('stackingestimator-1', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=12, min_sample...0.6000000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=7, min_child_weight=3, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1.0))]), Pipeline(memory=None, steps=[('stackingestimator', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=12, min_samples_...ators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False))])]
Led to very different pipelines and scores.
Let’s try one longer run with 720 pipelines
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .25, random_state = 20)tpot = TPOTRegressor(verbosity=3, random_state=10, #scoring=rmsle, periodic_checkpoint_folder=”any_string”, n_jobs=-1, generations=8, population_size=80, early_stop=5)
Results:
Times: [43.206709423016584]Scores: [-644910660.5815958] Winning pipelines: [Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=8, min_child_weight=3, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.8500000000000001))])]
RMSE is the best yet. It took the better part of an hour to converge, and we’re still running far smaller pipelines than recommended. 🤔
Next let’s try using Root Mean Squared Logarithmic Error, a custom scoring parameter Kaggle uses for this competition. This was run in another very small iteration with 30 pipelines in three runs with random_state=20. We couldn’t use more than one CPU core because of a bug with custom scoring parameters in Jupyter in some algorithms included in TPOT.
Times: [1.6125734224997965, 1.2910610851162345, 0.9708147236000514]Scores: [-0.15007242511943228, -0.14164770517342357, -0.15506057088945932]Winning pipelines: [Pipeline(memory=None, steps=[('maxabsscaler', MaxAbsScaler(copy=True)), ('stackingestimator', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, ...0.6000000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('extratreesregressor', ExtraTreesRegressor(bootstrap=False, criterion='mse', max_depth=None, max_features=0.6500000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=7, min_samples_split=10, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('ridgecv', RidgeCV(alphas=array([ 0.1, 1. , 10. ]), cv=None, fit_intercept=True, gcv_mode=None, normalize=False, scoring=None, store_cv_values=False))])]
Those scores aren’t terrible. The output file from tpot.export from this small run is below.
import numpy as np import pandas as pd from sklearn.linear_model import ElasticNetCV, LassoLarsCV from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline, make_union from tpot.builtins import StackingEstimator # NOTE: Make sure that the class is labeled 'target' in the data file tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64) features = tpot_data.drop('target', axis=1).values training_features, testing_features, training_target, testing_target = train_test_split(features, tpot_data['target'].values, random_state=42) # Score on the training set was:-0.169929041242275 exported_pipeline = make_pipeline( StackingEstimator(estimator=LassoLarsCV(normalize=False)), ElasticNetCV(l1_ratio=0.75, tol=0.01) exported_pipeline.fit(training_features, training_target) results = exported_pipeline.predict(testing_features)
In the future I’d like to do some longer runs with TPOT on this data set to see how it performs. I’d also like to see how some manual feature engineering and various encoding strategies can improve our model performance.
I love Kaggle’s kernels, but if you want to run an algorithm such as TPOT for a few hours, it can be super frustrating. Kernels frequently crash when running, you sometimes can’t tell if your attempted commit is hanging, and you can’t control your environment as much as you might like.
There’s nothing like getting to 700 out of 720 pipeline iterations and having Kaggle disconnect. My Kaggle CPU utilization rate was often showed 400%+ and there were many restarts required during this exercise.
A few other things to be aware of:
I found I needed to convert my Pandas DataFrame to a Numpy Array to avoid an XGBoost issue on the regression task. This is a known issue with Pandas and XGBoost.
A Kaggle kernel is running a Jupyter notebook under the hood. Custom scoring classifiers in TPOT don’t work when n_jobs is > 1 in a Jupyter notebook. This is a known issue.
Kaggle will only let your kernel code write to an output file when you commit your code. And you can’t see TPOT’s temporary output when committing. Make sure you just have the file name in quotes — no slashes. The file will show up on the Output tab.
Turning on the GPU setting on Kaggle didn’t speed things up for most of these analyses, but likely would for deep learning.
Kaggle’s 6 hours of possible run time and GPU setting make it possible to experiment with TPOT for free with no configuration on non-huge data sets. It’s hard to pass up free.
For more time and speed you can use something like Paperspace. I set TPOT up on Paperspace and it was pretty pain-free, although not money-free. If you need a cloud solution to run TPOT, I suggest playing around with it on Kaggle first and then moving off Kaggle if you need more than a few hours of running time or more power.
There are so many interesting directions to explore with TPOT and autoML. I’d like to compare TPOT with autoSKlearn, MLBox, Auto-Keras, and others. I’d also like to see how it performs with a greater variety of data, other imputation strategies, and other encoding strategies. A comparison with LightGBM, CatBoost , and deep learning algorithms would also be interesting. The exciting thing about this moment in machine learning is that there are so many areas to explore. Follow me to make sure you don’t miss future analysis.
For most data sets there’s still a lot of data cleaning, feature engineering, and final model selection to do — not to mention the most important step of asking the right questions up front. Then you might need to productionize your model. And TPOT isn’t doing exhaustive searches yet. So TPOT isn’t going to replace the data scientist role — but this tool might make your final machine learning algorithms better faster.
If you’ve used TPOT or other autoML tools please share your experience in the comments.
I hope you found this introduction to TPOT to be helpful. If you did, please share it on your favorite social media so other folks can find it, too. 😀
I write about Python, SQL, and other tech topics. If any of that’s of interest to you, sign up for my mailing list of awesome data science resources and read more to help you grow your skills here. 👍
Happy TPOTing! 🚀
|
[
{
"code": null,
"e": 389,
"s": 172,
"text": "In this post I’m sharing some of my explorations with TPOT, an automated machine learning (autoML) tool in Python. The goal is to see what TPOT can do and if it merits becoming part of your machine learning workflow."
},
{
"code": null,
"e": 579,
"s": 389,
"text": "Automated machine learning doesn’t replace the data scientist, (at least not yet) but it might be able to help you find good models faster. TPOT bills itself as your Data Science Assistant."
},
{
"code": null,
"e": 859,
"s": 579,
"text": "TPOT is meant to be an assistant that gives you ideas on how to solve a particular machine learning problem by exploring pipeline configurations that you might have never considered, then leaves the fine-tuning to more constrained parameter tuning techniques such as grid search."
},
{
"code": null,
"e": 1007,
"s": 859,
"text": "So TPOT helps you find good algorithms. Note that it isn’t designed for automating deep learning — something like AutoKeras might be helpful there."
},
{
"code": null,
"e": 1200,
"s": 1007,
"text": "TPOT is built on the scikit learn library and follows the scikit learn API closely. It can be used for regression and classification tasks and has special implementations for medical research."
},
{
"code": null,
"e": 1462,
"s": 1200,
"text": "TPOT is open source, well documented, and under active development. It’s development was spearheaded by researchers at the University of Pennsylvania. TPOT appears to be one of the most popular autoML libraries, with nearly 4,500 GitHub stars as of August 2018."
},
{
"code": null,
"e": 1786,
"s": 1462,
"text": "TPOT has what its developers call a genetic search algorithm to find the best parameters and model ensembles. It could also be thought of as a natural selection or evolutionary algorithm. TPOT tries a pipeline, evaluates its performance, and randomly changes parts of the pipeline in search of better performing algorithms."
},
{
"code": null,
"e": 2244,
"s": 1786,
"text": "AutoML algorithms aren’t as simple as fitting one model on the dataset; they are considering multiple machine learning algorithms (random forests, linear models, SVMs, etc.) in a pipeline with multiple preprocessing steps (missing value imputation, scaling, PCA, feature selection, etc.), the hyperparameters for all of the models and preprocessing steps, as well as multiple ways to ensemble or stack the algorithms within the pipeline. (source: TPOT docs)"
},
{
"code": null,
"e": 2394,
"s": 2244,
"text": "This power of TPOT comes from evaluating all kinds of possible pipelines automatically and efficiently. Doing this manually is cumbersome and slower."
},
{
"code": null,
"e": 2513,
"s": 2394,
"text": "Instantiating, fitting, and scoring the TPOT classifier is similar to any other sklearn classifier. Here’s the format:"
},
{
"code": null,
"e": 2589,
"s": 2513,
"text": "tpot = TPOTClassifier()tpot.fit(X_train, y_train)tpot.score(X_test, y_test)"
},
{
"code": null,
"e": 2873,
"s": 2589,
"text": "TPOT comes with its own variation of one-hot encoding. Note that it could add it to a pipeline automatically because it treats features with fewer than 10 unique values as categorical. If you want to use your own encoding strategy you can encode your data and then feed it into TPOT."
},
{
"code": null,
"e": 3089,
"s": 2873,
"text": "You can choose the scoring criterion for tpot.score (although a bug with Jupyter and multiple processor cores prevents you from having a custom scoring criterion with multiple processor cores in a Jupyter notebook)."
},
{
"code": null,
"e": 3407,
"s": 3089,
"text": "It appears that you can’t alter the scoring criteria TPOT uses internally as it searches for the best pipeline, just the scoring criteria for use on the test set after TPOT has chosen the best algorithms. This is an area where some users might want more control. Perhaps this option will be added in a future version."
},
{
"code": null,
"e": 3732,
"s": 3407,
"text": "TPOT writes information about the best performing algorithm and it’s accuracy score to a file with tpot.export(). You can choose the level of verboseness you would like to see as TPOT runs and have it write pipelines to an output file as it runs in case it terminates early for some reason (e.g. your Kaggle Kernel crashes)."
},
{
"code": null,
"e": 3769,
"s": 3732,
"text": "The short answer is that it depends."
},
{
"code": null,
"e": 4251,
"s": 3769,
"text": "TPOT was designed to run for a while — hours or even a day. Although less complex problems with smaller datasets can see great results in minutes. You can adjust several parameters for TPOT to finish its searches faster, but at the expense of a less thorough search for an optimal pipeline. It was not designed to be a comprehensive search of preprocessing steps, feature selection, algorithms, and parameters, but it can come close if you set its parameters to be more exhaustive."
},
{
"code": null,
"e": 4272,
"s": 4251,
"text": "As the docs explain:"
},
{
"code": null,
"e": 4856,
"s": 4272,
"text": "...TPOT will take a while to run on larger datasets, but it’s important to realize why. With the default TPOT settings (100 generations with 100 population size), TPOT will evaluate 10,000 pipeline configurations before finishing. To put this number into context, think about a grid search of 10,000 hyperparameter combinations for a machine learning algorithm and how long that grid search will take. That is 10,000 model configurations to evaluate with 10-fold cross-validation, which means that roughly 100,000 models are fit and evaluated on the training data in one grid search."
},
{
"code": null,
"e": 4978,
"s": 4856,
"text": "Some of the data sets we’ll see below only need a few minutes to find algorithms that score well; others might need days."
},
{
"code": null,
"e": 5026,
"s": 4978,
"text": "Here are the default TPOTClassifier parameters:"
},
{
"code": null,
"e": 5433,
"s": 5026,
"text": "generations=100, population_size=100, offspring_size=None # Jeff notes this gets set to population_sizemutation_rate=0.9, crossover_rate=0.1, scoring=\"Accuracy\", # for Classificationcv=5, subsample=1.0, n_jobs=1,max_time_mins=None, max_eval_time_mins=5,random_state=None, config_dict=None,warm_start=False, memory=None,periodic_checkpoint_folder=None, early_stop=Noneverbosity=0disable_update_check=False"
},
{
"code": null,
"e": 5577,
"s": 5433,
"text": "A description of each parameter can be found the docs. Here are a few key ones that determine the number of pipelines TPOT will search through:"
},
{
"code": null,
"e": 6315,
"s": 5577,
"text": "generations: int, optional (default: 100) Number of iterations to the run pipeline optimization process. Generally, TPOT will work better when you give it more generations(and therefore time) to optimize the pipeline. TPOT will evaluate POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE pipelines in total (emphasis mine).population_size: int, optional (default: 100) Number of individuals to retain in the GP population every generation. Generally, TPOT will work better when you give it more individuals (and therefore time) to optimize the pipeline. offspring_size: int, optional (default: None)Number of offspring to produce in each GP generation. By default, offspring_size = population_size."
},
{
"code": null,
"e": 6601,
"s": 6315,
"text": "When starting out with TPOT it’s worth setting verbosity=3 and periodic_checkpoint_folder=“any_string_you_like” so that you can watch the models evolve and training scores improve. You’ll see some errors as some combinations of pipeline elements are incompatible, but don’t sweat that."
},
{
"code": null,
"e": 6738,
"s": 6601,
"text": "If you’re running on multiple cores and not using a custom scoring function, set n_jobs=-1 to use all available cores and speed up TPOT."
},
{
"code": null,
"e": 6829,
"s": 6738,
"text": "Here are the classification algorithms and parameters TPOT chooses from as of version 0.9:"
},
{
"code": null,
"e": 8733,
"s": 6829,
"text": "‘sklearn.naive_bayes.BernoulliNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.naive_bayes.MultinomialNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.tree.DecisionTreeClassifier’: { ‘criterion’: [“gini”, “entropy”], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21) }, ‘sklearn.ensemble.ExtraTreesClassifier’: { ‘n_estimators’: [100], ‘criterion’: [“gini”, “entropy”], ‘max_features’: np.arange(0.05, 1.01, 0.05), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘bootstrap’: [True, False] },‘sklearn.ensemble.RandomForestClassifier’: { ‘n_estimators’: [100], ‘criterion’: [“gini”, “entropy”], ‘max_features’: np.arange(0.05, 1.01, 0.05), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘bootstrap’: [True, False] }, ‘sklearn.ensemble.GradientBoostingClassifier’: { ‘n_estimators’: [100], ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘max_features’: np.arange(0.05, 1.01, 0.05) },‘sklearn.neighbors.KNeighborsClassifier’: { ‘n_neighbors’: range(1, 101), ‘weights’: [“uniform”, “distance”], ‘p’: [1, 2] }, ‘sklearn.svm.LinearSVC’: { ‘penalty’: [“l1”, “l2”], ‘loss’: [“hinge”, “squared_hinge”], ‘dual’: [True, False], ‘tol’: [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.] }, ‘sklearn.linear_model.LogisticRegression’: { ‘penalty’: [“l1”, “l2”], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.], ‘dual’: [True, False] }, ‘xgboost.XGBClassifier’: { ‘n_estimators’: [100], ‘max_depth’: range(1, 11), ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘min_child_weight’: range(1, 21), ‘nthread’: [1] }"
},
{
"code": null,
"e": 8883,
"s": 8733,
"text": "And TPOT can stack classifiers, including the same classifier multiple times. One of the core developers of TPOT explains how it works in this issue:"
},
{
"code": null,
"e": 9045,
"s": 8883,
"text": "The pipeline ExtraTreesClassifier(ExtraTreesClassifier(input_matrix, True, 'entropy', 0.10000000000000001, 13, 6), True, 'gini', 0.75, 17, 4) does the following:"
},
{
"code": null,
"e": 9108,
"s": 9045,
"text": "Fit all of the original features using an ExtraTreesClassifier"
},
{
"code": null,
"e": 9209,
"s": 9108,
"text": "Take the predictions from that ExtraTreesClassifier and create a new feature using those predictions"
},
{
"code": null,
"e": 9366,
"s": 9209,
"text": "Pass the original features plus the new “predicted feature” to the 2nd ExtraTreesClassifier and use its predictions as the final predictions of the pipeline"
},
{
"code": null,
"e": 9464,
"s": 9366,
"text": "This process is called stacking classifiers, which is a fairly common tactic in machine learning."
},
{
"code": null,
"e": 9547,
"s": 9464,
"text": "And here are the 11 preprocessors that could be applied by TPOT as of version 0.9."
},
{
"code": null,
"e": 10761,
"s": 9547,
"text": "‘sklearn.preprocessing.Binarizer’: { ‘threshold’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.decomposition.FastICA’: { ‘tol’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.cluster.FeatureAgglomeration’: { ‘linkage’: [‘ward’, ‘complete’, ‘average’], ‘affinity’: [‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’, ‘cosine’] }, ‘sklearn.preprocessing.MaxAbsScaler’: { }, ‘sklearn.preprocessing.MinMaxScaler’: { }, ‘sklearn.preprocessing.Normalizer’: { ‘norm’: [‘l1’, ‘l2’, ‘max’] }, ‘sklearn.kernel_approximation.Nystroem’: { ‘kernel’: [‘rbf’, ‘cosine’, ‘chi2’, ‘laplacian’, ‘polynomial’, ‘poly’, ‘linear’, ‘additive_chi2’, ‘sigmoid’], ‘gamma’: np.arange(0.0, 1.01, 0.05), ‘n_components’: range(1, 11) }, ‘sklearn.decomposition.PCA’: { ‘svd_solver’: [‘randomized’], ‘iterated_power’: range(1, 11) }, ‘sklearn.preprocessing.PolynomialFeatures’: { ‘degree’: [2], ‘include_bias’: [False], ‘interaction_only’: [False] }, ‘sklearn.kernel_approximation.RBFSampler’: { ‘gamma’: np.arange(0.0, 1.01, 0.05) }, ‘sklearn.preprocessing.RobustScaler’: { }, ‘sklearn.preprocessing.StandardScaler’: { }, ‘tpot.builtins.ZeroCount’: { }, ‘tpot.builtins.OneHotEncoder’: { ‘minimum_fraction’: [0.05, 0.1, 0.15, 0.2, 0.25], ‘sparse’: [False] } (emphasis mine)"
},
{
"code": null,
"e": 11059,
"s": 10761,
"text": "That’s a pretty comprehensive list of sklearn ml algorithms and even a few you might not have used for preprocessing, including Nystroem and RBFSampler. The final preprocessing algorithm listed is the custom OneHotEncoder mentioned before. Note that the list contains no neural network algorithms."
},
{
"code": null,
"e": 11319,
"s": 11059,
"text": "The number of combinations appears to be nearly infinite — you can stack algorithms, including instances of the same algorithm. There may be an internal cap on the number of steps in the pipeline, but suffice to say there are a plethora of possible pipelines."
},
{
"code": null,
"e": 11490,
"s": 11319,
"text": "TPOT will likely not result in the same algorithm selection if you run it twice (maybe not even if random_state is set, I found, as discussed below). As the docs explain:"
},
{
"code": null,
"e": 11982,
"s": 11490,
"text": "If you’re working with a reasonably complex dataset or run TPOT for a short amount of time, different TPOT runs may result in different pipeline recommendations. TPOT’s optimization algorithm is stochastic in nature, which means that it uses randomness (in part) to search the possible pipeline space. When two TPOT runs recommend different pipelines, this means that the TPOT runs didn’t converge due to lack of time or that multiple pipelines perform more-or-less the same on your dataset."
},
{
"code": null,
"e": 12040,
"s": 11982,
"text": "Less talk — more action. Let’s try out TPOT on some data!"
},
{
"code": null,
"e": 12286,
"s": 12040,
"text": "First we’ll look at a classification task — the popular handwriting digit classification task from MNIST included in sklearn’s datasets. The MNIST database contains 70,000 images of handwritten Arabic digits in 28x28 pixels, labeled from 0 to 9."
},
{
"code": null,
"e": 12419,
"s": 12286,
"text": "TPOT comes standard on the Kaggle Docker image, so you only need to import it if you’re using Kaggle — you don’t need to install it."
},
{
"code": null,
"e": 12537,
"s": 12419,
"text": "Here’s my code — available on this Kaggle Kernel, in a slightly different form and possibly with a few modifications."
},
{
"code": null,
"e": 13778,
"s": 12537,
"text": "# import the usual stuffimport numpy as np import pandas as pd import matplotlib.pyplot as pltimport seaborn as snsimport os# import TPOT and sklearn stufffrom tpot import TPOTClassifierfrom sklearn.datasets import load_digitsfrom sklearn.model_selection import train_test_splitimport sklearn.metrics# create train and test setsdigits = load_digits()X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, train_size=0.75, test_size=0.25, random_state=34)tpot = TPOTClassifier(verbosity=3, scoring=\"balanced_accuracy\", random_state=23, periodic_checkpoint_folder=\"tpot_mnst1.txt\", n_jobs=-1, generations=10, population_size=100)# run three iterations and time themfor x in range(3): start_time = timeit.default_timer() tpot.fit(X_train, y_train) elapsed = timeit.default_timer() - start_time times.append(elapsed) winning_pipes.append(tpot.fitted_pipeline_) scores.append(tpot.score(X_test, y_test)) tpot.export('tpot_mnist_pipeline.py')times = [time/60 for time in times]print('Times:', times)print('Scores:', scores) print('Winning pipelines:', winning_pipes)"
},
{
"code": null,
"e": 13888,
"s": 13778,
"text": "As mentioned above, the total number of pipelines is equal to POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE."
},
{
"code": null,
"e": 14103,
"s": 13888,
"text": "For example, if you set population_size=20 and generations=5, then offspring_size=20 (because offspring_size equals population_size by default. And you’ll have a total of 120 pipelines because 20 + (5 * 20 ) = 120."
},
{
"code": null,
"e": 14228,
"s": 14103,
"text": "You can see it doesn’t take much code at all to run this data set — and that includes a loop to time and test it repeatedly."
},
{
"code": null,
"e": 14378,
"s": 14228,
"text": "With 10 possible classes and no reason to prefer one outcome to another, accuracy — the TPOT classification default — is a fine metric for this task."
},
{
"code": null,
"e": 14412,
"s": 14378,
"text": "Here’s the relevant code section."
},
{
"code": null,
"e": 14748,
"s": 14412,
"text": "digits = load_digits()X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, train_size=0.75, test_size=0.25, random_state=34)tpot = TPOTClassifier(verbosity=3, scoring=”accuracy”, random_state=32, periodic_checkpoint_folder=”tpot_results.txt”, n_jobs=-1, generations=5, population_size=10, early_stop=5)"
},
{
"code": null,
"e": 14774,
"s": 14748,
"text": "And here are the results:"
},
{
"code": null,
"e": 16212,
"s": 14774,
"text": "Times: [4.740584810283326, 3.497970838083226, 3.4362493358499098]Scores: [0.9733333333333334, 0.9644444444444444, 0.9666666666666667]Winning pipelines: [Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.1, loss='deviance', max_depth=7, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_...auto', random_state=None, subsample=0.9500000000000001, verbose=0, warm_start=False))])]"
},
{
"code": null,
"e": 16370,
"s": 16212,
"text": "Note that with only 60 pipelines — far less than what TPOT suggests — we were able to see pretty good scores — over 97% accuracy on the test set in one case."
},
{
"code": null,
"e": 16588,
"s": 16370,
"text": "Does TPOT find the same winning pipeline every time with the same random_state set? Not necessarily. Individually algorithms such as RandomForrestClassifier() have their own random_state parameters that don’t get set."
},
{
"code": null,
"e": 16945,
"s": 16588,
"text": "TPOT doesn’t always find the same result if you instantiate one classifier and then fit it repeatedly like we do in the for loop in the code above. I ran three very small sets of 60 pipelines with random_state set and Kaggle’s GPU setting on. Note that we get slightly different pipelines and thus slightly different test set scores on the three test sets."
},
{
"code": null,
"e": 17053,
"s": 16945,
"text": "Here’s another example of a small number of pipelines with random state set and using Kaggle’s CPU setting."
},
{
"code": null,
"e": 18492,
"s": 17053,
"text": "Times: [2.8874817832668973, 0.043678393283335025, 0.04388708711679404]Scores: [0.9622222222222222, 0.9622222222222222, 0.9622222222222222]Winning pipelines: [Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('gradientboostingclassifier', GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.5, loss='deviance', max_depth=2, max_features=0.15000000000000002, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,....9500000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))])]"
},
{
"code": null,
"e": 18545,
"s": 18492,
"text": "The same pipeline was found each of the three times."
},
{
"code": null,
"e": 18846,
"s": 18545,
"text": "Note that the run time is much faster after the first iteration. TPOT does seem to remember when it has seen an algorithm and doesn’t rerun it, even if it’s a second fit and you’ve set memory=False. Here’s what you’ll see if you set the verbosity=3 when it finds such a previously evaluated pipeline:"
},
{
"code": null,
"e": 18981,
"s": 18846,
"text": "Pipeline encountered that has previously been evaluated during the optimization process. Using the score from the previous evaluation."
},
{
"code": null,
"e": 19280,
"s": 18981,
"text": "How does TPOT do if you make a large number of pipelines? To really see the power of TPOT for the MNIST digits task, you need over 500 total pipelines to run. This will take at least an hour if you’re running it on Kaggle. Then you will see higher accuracy scores and might see more complex models."
},
{
"code": null,
"e": 19473,
"s": 19280,
"text": "Chained, or stacked, ensembles where the outputs of one machine learning algorithm feed into another are what you’ll likely see if you have a larger number of pipelines and a non-trivial task."
},
{
"code": null,
"e": 20005,
"s": 19473,
"text": "0.9950861171999883knn = KNeighborsClassifier( DecisionTreeClassifier( OneHotEncoder(input_matrix, OneHotEncoder__minimum_fraction=0.15, OneHotEncoder__sparse=False), DecisionTreeClassifier__criterion=gini, DecisionTreeClassifier__max_depth=5, DecisionTreeClassifier__min_samples_leaf=20, DecisionTreeClassifier__min_samples_split=17), KNeighborsClassifier__n_neighbors=1, KNeighborsClassifier__p=2, KNeighborsClassifier__weights=distance)"
},
{
"code": null,
"e": 20275,
"s": 20005,
"text": "This is .995 average internal CV accuracy score after running for over an hour and generating over 600 pipelines. The kernel crashed before completion, so I didn’t get to see a test set score and couldn’t get an outputted model, but this looks quite promising for TPOT."
},
{
"code": null,
"e": 20409,
"s": 20275,
"text": "The algorithm uses a DecisionTreeClassifier with TPOT’s custom OneHotEncoder categorical encodings feeding into KNeighborsClassifier."
},
{
"code": null,
"e": 20535,
"s": 20409,
"text": "Here’s a similar internal score with a different pipeline resulting from a different random_state after nearly 800 pipelines."
},
{
"code": null,
"e": 21104,
"s": 20535,
"text": "0.9903723557310828 KNeighborsClassifier(Normalizer(OneHotEncoder(RandomForestClassifier(MinMaxScaler(input_matrix), RandomForestClassifier__bootstrap=True, RandomForestClassifier__criterion=entropy, RandomForestClassifier__max_features=0.55, RandomForestClassifier__min_samples_leaf=6, RandomForestClassifier__min_samples_split=15, RandomForestClassifier__n_estimators=100), OneHotEncoder__minimum_fraction=0.2, OneHotEncoder__sparse=False), Normalizer__norm=max), KNeighborsClassifier__n_neighbors=4, KNeighborsClassifier__p=2, KNeighborsClassifier__weights=distance)"
},
{
"code": null,
"e": 21360,
"s": 21104,
"text": "TPOT found a pipeline with KNN, One Hot encoding, normalization, and random forest. It took two and a half hours. Previous one was faster and scored better, but sometimes that’s what happens with the stochastic nature of TPOT’s genetic search algorithm. 😉"
},
{
"code": null,
"e": 21555,
"s": 21360,
"text": "TPOT can perform really well on this image recognition task if you give it enough time.TPOT works better with more pipelines.If you need reproducibility for a task, TPOT isn’t the tool you want."
},
{
"code": null,
"e": 21643,
"s": 21555,
"text": "TPOT can perform really well on this image recognition task if you give it enough time."
},
{
"code": null,
"e": 21682,
"s": 21643,
"text": "TPOT works better with more pipelines."
},
{
"code": null,
"e": 21752,
"s": 21682,
"text": "If you need reproducibility for a task, TPOT isn’t the tool you want."
},
{
"code": null,
"e": 22101,
"s": 21752,
"text": "For a second dataset I chose the popular mushroom classification task. The goal is to determine correctly whether a mushroom is poisonous based on its labels. This is not an image classification task. It’s set up as a binary task so that all potentially dangerous mushrooms are grouped as one category and safe to eat mushrooms as another category."
},
{
"code": null,
"e": 22145,
"s": 22101,
"text": "My code is available on this Kaggle Kernel."
},
{
"code": null,
"e": 22444,
"s": 22145,
"text": "TPOT can routinely fit a perfect model quickly on this data set. It did so in under two minutes. This is much better performance and speed than when I tested this dataset without TPOT with many scikit-learn classification algorithms, a wide range of nominal data encodings, and no parameter tuning."
},
{
"code": null,
"e": 22550,
"s": 22444,
"text": "On three runs with the same TPOTClassifier instance and the same random state set here’s what TPOT found:"
},
{
"code": null,
"e": 22640,
"s": 22550,
"text": "Times: [1.854785452616731, 1.5694829618000463, 1.3383520993001488]Scores: [1.0, 1.0, 1.0]"
},
{
"code": null,
"e": 22825,
"s": 22640,
"text": "Interestingly, it found a different best algorithm each time. It found a DecisionTreeClassifier, then a KNeighorsClassifier, and then a Stacked RandomForestClassifier with BernoulliNB."
},
{
"code": null,
"e": 22930,
"s": 22825,
"text": "Let’s dig into reproducibility a bit more. Let’s run it again with everything exactly the same settings."
},
{
"code": null,
"e": 23021,
"s": 22930,
"text": "Times: [1.8664863013502326, 1.5520636909670429, 1.3386059726501116]Scores: [1.0, 1.0, 1.0]"
},
{
"code": null,
"e": 23118,
"s": 23021,
"text": "We see the same set of three pipelines, very similar times, and the same scores on the test set."
},
{
"code": null,
"e": 23245,
"s": 23118,
"text": "Now let’s try splitting the cell into multiple different cells and instantiating a TPOT instance in each one. Here’s the code:"
},
{
"code": null,
"e": 23557,
"s": 23245,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=0.25, random_state=25)tpot = TPOTClassifier( verbosity=3, scoring=”accuracy”, random_state=25, periodic_checkpoint_folder=”tpot_mushroom_results.txt”, n_jobs=-1, generations=5, population_size=10, early_stop = 5)"
},
{
"code": null,
"e": 23844,
"s": 23557,
"text": "The result of the second run now matches the result of the first one and took almost the same time (Score = 1.0, Time = 1.9 minutes, pipeline = Decision Tree Classifier). The key for higher reproducibility is that we are instantiating a new instance of the TPOT classifier in each cell."
},
{
"code": null,
"e": 24075,
"s": 23844,
"text": "Time results from 10 sets of 30 pipelines with random_state on train_test_split and TPOT set to 10 are below. All pipelines correctly classified all mushrooms on the test set. TPOT was quite fast on this fairly easy-to-learn task."
},
{
"code": null,
"e": 24142,
"s": 24075,
"text": "TPOT performs well and quickly for this basic classification task."
},
{
"code": null,
"e": 24424,
"s": 24142,
"text": "As a comparison, this Kaggle kernel on the mushroom set in R is very nice and explores a variety of algorithms and gets very close to perfect accuracy. But it doesn’t quite reach 100% and it certainly took quite a bit more time to prepare and train than our implementation of TPOT."
},
{
"code": null,
"e": 24533,
"s": 24424,
"text": "I would strongly consider TPOT as a time saver for a task like this in the future, at least as a first step."
},
{
"code": null,
"e": 24742,
"s": 24533,
"text": "Next we turn to a regression task to see how TPOT performs. We’ll predict housing property sale values with the popular Ames, Iowa Housing Price Prediction dataset. My code is available on this Kaggle Kernel."
},
{
"code": null,
"e": 25083,
"s": 24742,
"text": "For this task, I did some basic imputation of missing values first. I filled missing numeric column values with the most frequent value for the column, because some of those columns contain ordinal data. With more time I’d categorize the columns and use different imputation strategies depending on interval, ordinal, or nominal data types."
},
{
"code": null,
"e": 25377,
"s": 25083,
"text": "String column missing values were filled with a “missing” label prior to ordinal encoding because not all columns had a most frequent value. TPOT’s one hot encoding algorithm would then make one more dimension per feature that would indicate that the data had a missing value for that feature."
},
{
"code": null,
"e": 25435,
"s": 25377,
"text": "TPOTRegressor uses mean squared error scoring by default."
},
{
"code": null,
"e": 25472,
"s": 25435,
"text": "Here’s a run with only 60 pipelines."
},
{
"code": null,
"e": 26326,
"s": 25472,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .25, random_state = 33)# instantiate tpot tpot = TPOTRegressor(verbosity=3, random_state=25, n_jobs=-1, generations=5, population_size=10, early_stop = 5, memory = None)times = []scores = []winning_pipes = []# run 3 iterationsfor x in range(3): start_time = timeit.default_timer() tpot.fit(X_train, y_train) elapsed = timeit.default_timer() - start_time times.append(elapsed) winning_pipes.append(tpot.fitted_pipeline_) scores.append(tpot.score(X_test, y_test)) tpot.export('tpot_ames.py')# output resultstimes = [time/60 for time in times]print('Times:', times)print('Scores:', scores) print('Winning pipelines:', winning_pipes)"
},
{
"code": null,
"e": 26366,
"s": 26326,
"text": "The results of these three little runs."
},
{
"code": null,
"e": 27841,
"s": 26366,
"text": "Times: [3.8920086714831994, 1.4063017464330188, 1.2469199204002508]Scores: [-905092886.3009057, -922269561.2683483, -949881926.6436856]Winning pipelines: [Pipeline(memory=None, steps=[('zerocount', ZeroCount()), ('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=18, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))]), Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=11, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))]), Pipeline(memory=None, steps=[('stackingestimator', StackingEstimator(estimator=RidgeCV(alphas=array([ 0.1, 1. , 10. ]), cv=None, fit_intercept=True, gcv_mode=None, normalize=False, scoring=None, store_cv_values=False))), ('maxabsscaler-1', MaxAbsScaler(copy=True)), ('maxabsscaler-2', MaxAbsScaler(copy=True)), ('xgbr... reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.5))])]"
},
{
"code": null,
"e": 28045,
"s": 27841,
"text": "The runs finished pretty quickly and found different winning pipelines each time. Taking the square root of the scores gives us the Root Mean Squared Error (RMSE). The RMSE was around $30,000 on average."
},
{
"code": null,
"e": 28134,
"s": 28045,
"text": "Trying with 60 pipelines and a random_state = 20 for train_test_split and TPOTRegressor."
},
{
"code": null,
"e": 29575,
"s": 28134,
"text": "Times: [9.691357856966594, 1.8972856383004304, 2.5272325469001466]Scores: [-1061075530.3715296, -695536167.1288683, -783733389.9523941]Winning pipelines: [Pipeline(memory=None, steps=[('stackingestimator-1', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=12, min_sample...0.6000000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=7, min_child_weight=3, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1.0))]), Pipeline(memory=None, steps=[('stackingestimator', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=12, min_samples_...ators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False))])]"
},
{
"code": null,
"e": 29619,
"s": 29575,
"text": "Led to very different pipelines and scores."
},
{
"code": null,
"e": 29663,
"s": 29619,
"text": "Let’s try one longer run with 720 pipelines"
},
{
"code": null,
"e": 29928,
"s": 29663,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .25, random_state = 20)tpot = TPOTRegressor(verbosity=3, random_state=10, #scoring=rmsle, periodic_checkpoint_folder=”any_string”, n_jobs=-1, generations=8, population_size=80, early_stop=5)"
},
{
"code": null,
"e": 29937,
"s": 29928,
"text": "Results:"
},
{
"code": null,
"e": 30458,
"s": 29937,
"text": "Times: [43.206709423016584]Scores: [-644910660.5815958] Winning pipelines: [Pipeline(memory=None, steps=[('xgbregressor', XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=8, min_child_weight=3, missing=None, n_estimators=100, n_jobs=1, nthread=1, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=0.8500000000000001))])]"
},
{
"code": null,
"e": 30594,
"s": 30458,
"text": "RMSE is the best yet. It took the better part of an hour to converge, and we’re still running far smaller pipelines than recommended. 🤔"
},
{
"code": null,
"e": 30947,
"s": 30594,
"text": "Next let’s try using Root Mean Squared Logarithmic Error, a custom scoring parameter Kaggle uses for this competition. This was run in another very small iteration with 30 pipelines in three runs with random_state=20. We couldn’t use more than one CPU core because of a bug with custom scoring parameters in Jupyter in some algorithms included in TPOT."
},
{
"code": null,
"e": 32178,
"s": 30947,
"text": "Times: [1.6125734224997965, 1.2910610851162345, 0.9708147236000514]Scores: [-0.15007242511943228, -0.14164770517342357, -0.15506057088945932]Winning pipelines: [Pipeline(memory=None, steps=[('maxabsscaler', MaxAbsScaler(copy=True)), ('stackingestimator', StackingEstimator(estimator=RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None, max_features=0.7000000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, ...0.6000000000000001, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('extratreesregressor', ExtraTreesRegressor(bootstrap=False, criterion='mse', max_depth=None, max_features=0.6500000000000001, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=7, min_samples_split=10, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False))]), Pipeline(memory=None, steps=[('ridgecv', RidgeCV(alphas=array([ 0.1, 1. , 10. ]), cv=None, fit_intercept=True, gcv_mode=None, normalize=False, scoring=None, store_cv_values=False))])]"
},
{
"code": null,
"e": 32271,
"s": 32178,
"text": "Those scores aren’t terrible. The output file from tpot.export from this small run is below."
},
{
"code": null,
"e": 33177,
"s": 32271,
"text": "import numpy as np import pandas as pd from sklearn.linear_model import ElasticNetCV, LassoLarsCV from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline, make_union from tpot.builtins import StackingEstimator # NOTE: Make sure that the class is labeled 'target' in the data file tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64) features = tpot_data.drop('target', axis=1).values training_features, testing_features, training_target, testing_target = train_test_split(features, tpot_data['target'].values, random_state=42) # Score on the training set was:-0.169929041242275 exported_pipeline = make_pipeline( StackingEstimator(estimator=LassoLarsCV(normalize=False)), ElasticNetCV(l1_ratio=0.75, tol=0.01) exported_pipeline.fit(training_features, training_target) results = exported_pipeline.predict(testing_features)"
},
{
"code": null,
"e": 33398,
"s": 33177,
"text": "In the future I’d like to do some longer runs with TPOT on this data set to see how it performs. I’d also like to see how some manual feature engineering and various encoding strategies can improve our model performance."
},
{
"code": null,
"e": 33685,
"s": 33398,
"text": "I love Kaggle’s kernels, but if you want to run an algorithm such as TPOT for a few hours, it can be super frustrating. Kernels frequently crash when running, you sometimes can’t tell if your attempted commit is hanging, and you can’t control your environment as much as you might like."
},
{
"code": null,
"e": 33896,
"s": 33685,
"text": "There’s nothing like getting to 700 out of 720 pipeline iterations and having Kaggle disconnect. My Kaggle CPU utilization rate was often showed 400%+ and there were many restarts required during this exercise."
},
{
"code": null,
"e": 33931,
"s": 33896,
"text": "A few other things to be aware of:"
},
{
"code": null,
"e": 34093,
"s": 33931,
"text": "I found I needed to convert my Pandas DataFrame to a Numpy Array to avoid an XGBoost issue on the regression task. This is a known issue with Pandas and XGBoost."
},
{
"code": null,
"e": 34266,
"s": 34093,
"text": "A Kaggle kernel is running a Jupyter notebook under the hood. Custom scoring classifiers in TPOT don’t work when n_jobs is > 1 in a Jupyter notebook. This is a known issue."
},
{
"code": null,
"e": 34517,
"s": 34266,
"text": "Kaggle will only let your kernel code write to an output file when you commit your code. And you can’t see TPOT’s temporary output when committing. Make sure you just have the file name in quotes — no slashes. The file will show up on the Output tab."
},
{
"code": null,
"e": 34641,
"s": 34517,
"text": "Turning on the GPU setting on Kaggle didn’t speed things up for most of these analyses, but likely would for deep learning."
},
{
"code": null,
"e": 34817,
"s": 34641,
"text": "Kaggle’s 6 hours of possible run time and GPU setting make it possible to experiment with TPOT for free with no configuration on non-huge data sets. It’s hard to pass up free."
},
{
"code": null,
"e": 35145,
"s": 34817,
"text": "For more time and speed you can use something like Paperspace. I set TPOT up on Paperspace and it was pretty pain-free, although not money-free. If you need a cloud solution to run TPOT, I suggest playing around with it on Kaggle first and then moving off Kaggle if you need more than a few hours of running time or more power."
},
{
"code": null,
"e": 35673,
"s": 35145,
"text": "There are so many interesting directions to explore with TPOT and autoML. I’d like to compare TPOT with autoSKlearn, MLBox, Auto-Keras, and others. I’d also like to see how it performs with a greater variety of data, other imputation strategies, and other encoding strategies. A comparison with LightGBM, CatBoost , and deep learning algorithms would also be interesting. The exciting thing about this moment in machine learning is that there are so many areas to explore. Follow me to make sure you don’t miss future analysis."
},
{
"code": null,
"e": 36095,
"s": 35673,
"text": "For most data sets there’s still a lot of data cleaning, feature engineering, and final model selection to do — not to mention the most important step of asking the right questions up front. Then you might need to productionize your model. And TPOT isn’t doing exhaustive searches yet. So TPOT isn’t going to replace the data scientist role — but this tool might make your final machine learning algorithms better faster."
},
{
"code": null,
"e": 36183,
"s": 36095,
"text": "If you’ve used TPOT or other autoML tools please share your experience in the comments."
},
{
"code": null,
"e": 36334,
"s": 36183,
"text": "I hope you found this introduction to TPOT to be helpful. If you did, please share it on your favorite social media so other folks can find it, too. 😀"
},
{
"code": null,
"e": 36534,
"s": 36334,
"text": "I write about Python, SQL, and other tech topics. If any of that’s of interest to you, sign up for my mailing list of awesome data science resources and read more to help you grow your skills here. 👍"
}
] |
Single dimensional array in Java
|
Following is a simple example of a single dimensional array.
Live Demo
public class Tester {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.print(element + " ");
}
}
}
1.9 2.9 3.4 3.5
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "Following is a simple example of a single dimensional array."
},
{
"code": null,
"e": 1134,
"s": 1123,
"text": " Live Demo"
},
{
"code": null,
"e": 1378,
"s": 1134,
"text": "public class Tester {\n public static void main(String[] args) {\n double[] myList = {1.9, 2.9, 3.4, 3.5};\n // Print all the array elements\n for (double element: myList) {\n System.out.print(element + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 1394,
"s": 1378,
"text": "1.9 2.9 3.4 3.5"
}
] |
Negative of an image in MATLAB - GeeksforGeeks
|
28 Jul, 2020
The negative of an image is achieved by replacing the intensity ‘i’ in the original image by ‘i-1’, i.e. the darkest pixels will become the brightest and the brightest pixels will become the darkest. Image negative is produced by subtracting each pixel from the maximum intensity value.For example in an 8-bit grayscale image, the max intensity value is 255, thus each pixel is subtracted from 255 to produce the output image.The transformation function used in image negative is :
s = T(r) = (L – 1) – r
Where L - 1 is the max intensity value,
s is the output pixel value and
r is the input pixel value
Algorithm
Read RGB color image into the MATLAB environment using Matlab inbuilt function imread()Calculate the levels of the image, for example an 8-bit image has 256 levelsUse the formula stated above on every pixel of the image to get corresponding negative pixel value.Convert each RGB pixel value at location (i, j) to its negative image values and assign it to the corresponding location (i, j) of another matrixDisplay the negative image using Matlab in-built imshow() function.
Read RGB color image into the MATLAB environment using Matlab inbuilt function imread()
Calculate the levels of the image, for example an 8-bit image has 256 levels
Use the formula stated above on every pixel of the image to get corresponding negative pixel value.
Convert each RGB pixel value at location (i, j) to its negative image values and assign it to the corresponding location (i, j) of another matrix
Display the negative image using Matlab in-built imshow() function.
% reading the RGB file into the Matlab environmentskI = imread("sakura.jpg"); subplot(1, 2, 1), % displaying the RGB imageimshow(skI);title("Original image"); % levels of the 8-bit imageL = 2 ^ 8; % finding the negative neg = (L - 1) - skI;subplot(1, 2, 2), % displaying the negative imageimshow(neg);title("Negative Image")
Output :
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Decision Tree Introduction with example
Reinforcement learning
KDD Process in Data Mining
ML | Underfitting and Overfitting
Clustering in Machine Learning
|
[
{
"code": null,
"e": 24914,
"s": 24886,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 25396,
"s": 24914,
"text": "The negative of an image is achieved by replacing the intensity ‘i’ in the original image by ‘i-1’, i.e. the darkest pixels will become the brightest and the brightest pixels will become the darkest. Image negative is produced by subtracting each pixel from the maximum intensity value.For example in an 8-bit grayscale image, the max intensity value is 255, thus each pixel is subtracted from 255 to produce the output image.The transformation function used in image negative is :"
},
{
"code": null,
"e": 25520,
"s": 25396,
"text": "s = T(r) = (L – 1) – r\n\nWhere L - 1 is the max intensity value,\ns is the output pixel value and\nr is the input pixel value\n"
},
{
"code": null,
"e": 25530,
"s": 25520,
"text": "Algorithm"
},
{
"code": null,
"e": 26005,
"s": 25530,
"text": "Read RGB color image into the MATLAB environment using Matlab inbuilt function imread()Calculate the levels of the image, for example an 8-bit image has 256 levelsUse the formula stated above on every pixel of the image to get corresponding negative pixel value.Convert each RGB pixel value at location (i, j) to its negative image values and assign it to the corresponding location (i, j) of another matrixDisplay the negative image using Matlab in-built imshow() function."
},
{
"code": null,
"e": 26093,
"s": 26005,
"text": "Read RGB color image into the MATLAB environment using Matlab inbuilt function imread()"
},
{
"code": null,
"e": 26170,
"s": 26093,
"text": "Calculate the levels of the image, for example an 8-bit image has 256 levels"
},
{
"code": null,
"e": 26270,
"s": 26170,
"text": "Use the formula stated above on every pixel of the image to get corresponding negative pixel value."
},
{
"code": null,
"e": 26416,
"s": 26270,
"text": "Convert each RGB pixel value at location (i, j) to its negative image values and assign it to the corresponding location (i, j) of another matrix"
},
{
"code": null,
"e": 26484,
"s": 26416,
"text": "Display the negative image using Matlab in-built imshow() function."
},
{
"code": "% reading the RGB file into the Matlab environmentskI = imread(\"sakura.jpg\"); subplot(1, 2, 1), % displaying the RGB imageimshow(skI);title(\"Original image\"); % levels of the 8-bit imageL = 2 ^ 8; % finding the negative neg = (L - 1) - skI;subplot(1, 2, 2), % displaying the negative imageimshow(neg);title(\"Negative Image\")",
"e": 26837,
"s": 26484,
"text": null
},
{
"code": null,
"e": 26846,
"s": 26837,
"text": "Output :"
},
{
"code": null,
"e": 26863,
"s": 26846,
"text": "Image-Processing"
},
{
"code": null,
"e": 26870,
"s": 26863,
"text": "MATLAB"
},
{
"code": null,
"e": 26896,
"s": 26870,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 26994,
"s": 26896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27003,
"s": 26994,
"text": "Comments"
},
{
"code": null,
"e": 27016,
"s": 27003,
"text": "Old Comments"
},
{
"code": null,
"e": 27039,
"s": 27016,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27053,
"s": 27039,
"text": "Decision Tree"
},
{
"code": null,
"e": 27097,
"s": 27053,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27120,
"s": 27097,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 27158,
"s": 27120,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 27198,
"s": 27158,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 27221,
"s": 27198,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 27248,
"s": 27221,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 27282,
"s": 27248,
"text": "ML | Underfitting and Overfitting"
}
] |
Train your Machine Learning Model 150x Faster with cuML | by Khuyen Tran | Towards Data Science
|
Sklearn is a great library with a variety of machine learning models that you can use to train your data. But if your data is big, it might take you a long time to train your data, especially when you experiment with different hyperparameters to find the best model.
Is there a way that you can increase the speed of training your machine learning model by 150 times faster than using Sklearn with minimal change? Yes, you can do that with cuML.
Below is the chart that compares the time it takes to train the same model using Sklearn’s RandomForestClassifier and cuML’s RandomForestClassifier.
cuML is a suite of fast, GPU-accelerated machine learning algorithms designed for data science and analytical tasks. Its API is similar to Sklearn’s. This means you can use the same code you use to train Sklearn’s model to train cuML’s model.
In this article, I will compare the performance of these 2 libraries using different models. I will also show how increasing the memory of the graphic card can increase the speed by 10 times.
To install cuML, follow the instructions to install on Rapids’ page. Make sure to check the prerequisites before installing the library. You can either install all packages or just cuML. If you have limited space on your computer, I recommend installing cuDF and cuML.
Although in many cases, you don’t need to install cuDF to use cuML, cuDF is a nice complement for cuML since it is a GPU DataFrame.
Make sure to choose the options that fit your computer.
Since cuML often works better than Sklearn when there is a lot of data, we will create a dataset with 40000 rows of data using sklearn.datasets.
from sklearn import datasetsX, y = datasets.make_classification(n_samples=40000)
Convert the datatypes to np.float32 because some cuML models require the input to be np.float32.
X = X.astype(np.float32)y = y.astype(np.float32)
We will create the function to train the model. Using this function will make it easier for us to compare different models.
def train_data(model, X=X, y=y): clf = model clf.fit(X, y)
We use %timeit, an iPython’s magic command to run each function 7 times and take the average of all experiments.
Average time of sklearn's SVC 48.56009825014287 sAverage time of cuml's SVC 19.611496431714304 sRatio between sklearn and cuml is 2.476103668030909
cuML’s SVC is 2.5 times faster than sklearn’s SVC!
Let’s visualize it through the plot. We create a function to plot the speed of the models. I use cutecharts because it makes the bar charts cuter.
Since cuML’s models are faster than Sklearn’s when running on large data because they were trained using GPU, what will happen if we triple the memory of the GPU?
I use an Alienware M15 laptop with NVIDIA GeForce 2060 and a graphics card’s memory of 6.3 GB for the previous comparison.
Now I will use a Dell Precision 7740 with NVIDIA Quadro RTX 5000 and a graphics card’s memory of 17 GB to test the speed when the memory of the GPU increases.
Average time of sklearn's SVC 35.791008955999914 sAverage time of cuml's SVC 1.9953700327142931 sRatio between sklearn and cuml is 17.93702840535976
Wow! cuML’s SVM is 18 times faster than Sklearn’s SVM when it is trained on a machine with a graphics card’s memory of 17 GB! And it is 10 times faster than the speed of training on a laptop with a graphics card’s memory of 6.3 GB.
That is why it is better for us to have a good GPU in our machines if we are using GPU-accelerated libraries like cuML.
Average time of sklearn's RandomForestClassifier 29.824075075857113 sAverage time of cuml's RandomForestClassifier 0.49404465585715635 sRatio between sklearn and cuml is 60.3671646323408
cuML’s RandomForestClassifier is 60 times faster than Sklearn’s RandomForestClassifier! If it takes 30 seconds for you to train a Sklearn’s RandomForestClassifier, it takes less than half of a second to train a cuML’s RandomForestClassifier. How crazy is that?
Average time of Sklearn's RandomForestClassifier 24.006061030143037 sAverage time of cuML's RandomForestClassifier 0.15141178591425808 s.The ratio between Sklearn’s and cuML is 158.54816641379068
cuML’s RandomForestClassifier is 158 times faster than Sklearn’s RandomForestClassifier when trained on my Dell Precision 7740 laptop!
Average time of sklearn's KNeighborsClassifier 0.07836367340000508 sAverage time of cuml's KNeighborsClassifier 0.004251259535714585 sRatio between sklearn and cuml is 18.43304854518441
cuML’s KNeighborsClassifier is 18 times faster than Sklearn’s KNeighborsClassifier.
Average time of sklearn's KNeighborsClassifier 0.07511190322854547 sAverage time of cuml's KNeighborsClassifier 0.0015137992111426033 sRatio between sklearn and cuml is 49.618141346401956
cuML’s KNeighborsClassifier is 50 times faster than Sklearn’ KNeighborsClassifier when trained on my Dell Precision 7740 laptop.
You can find the code for the rest of the comparisons here.
Here are the two tables that summarize the speed of different models between 2 libraries on:
Alienware M15 — GeForce 2060 and a graphic card’s memory of 6.3 GB
Dell Precision 7740 — Quadro RTX 5000 and a graphic card’s memory of 17 GB
Pretty impressive, isn’t it?
Congratulations! You have just learned how fast training different models on cuML is compared to Sklearn. If it takes a long time to train your model using Sklearn, I highly recommend giving cuML a try, considering there is literally no change in code at all compared to Sklearn’s API.
And of course, with a library that uses GPU to execute the code like cuML, the better graphic card you have, the faster the training will be on average.
Check out the doc of cuML for details on other machine learning models.
The source code for this article could be found here.
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 438,
"s": 171,
"text": "Sklearn is a great library with a variety of machine learning models that you can use to train your data. But if your data is big, it might take you a long time to train your data, especially when you experiment with different hyperparameters to find the best model."
},
{
"code": null,
"e": 617,
"s": 438,
"text": "Is there a way that you can increase the speed of training your machine learning model by 150 times faster than using Sklearn with minimal change? Yes, you can do that with cuML."
},
{
"code": null,
"e": 766,
"s": 617,
"text": "Below is the chart that compares the time it takes to train the same model using Sklearn’s RandomForestClassifier and cuML’s RandomForestClassifier."
},
{
"code": null,
"e": 1009,
"s": 766,
"text": "cuML is a suite of fast, GPU-accelerated machine learning algorithms designed for data science and analytical tasks. Its API is similar to Sklearn’s. This means you can use the same code you use to train Sklearn’s model to train cuML’s model."
},
{
"code": null,
"e": 1201,
"s": 1009,
"text": "In this article, I will compare the performance of these 2 libraries using different models. I will also show how increasing the memory of the graphic card can increase the speed by 10 times."
},
{
"code": null,
"e": 1470,
"s": 1201,
"text": "To install cuML, follow the instructions to install on Rapids’ page. Make sure to check the prerequisites before installing the library. You can either install all packages or just cuML. If you have limited space on your computer, I recommend installing cuDF and cuML."
},
{
"code": null,
"e": 1602,
"s": 1470,
"text": "Although in many cases, you don’t need to install cuDF to use cuML, cuDF is a nice complement for cuML since it is a GPU DataFrame."
},
{
"code": null,
"e": 1658,
"s": 1602,
"text": "Make sure to choose the options that fit your computer."
},
{
"code": null,
"e": 1803,
"s": 1658,
"text": "Since cuML often works better than Sklearn when there is a lot of data, we will create a dataset with 40000 rows of data using sklearn.datasets."
},
{
"code": null,
"e": 1885,
"s": 1803,
"text": "from sklearn import datasetsX, y = datasets.make_classification(n_samples=40000)"
},
{
"code": null,
"e": 1982,
"s": 1885,
"text": "Convert the datatypes to np.float32 because some cuML models require the input to be np.float32."
},
{
"code": null,
"e": 2031,
"s": 1982,
"text": "X = X.astype(np.float32)y = y.astype(np.float32)"
},
{
"code": null,
"e": 2155,
"s": 2031,
"text": "We will create the function to train the model. Using this function will make it easier for us to compare different models."
},
{
"code": null,
"e": 2220,
"s": 2155,
"text": "def train_data(model, X=X, y=y): clf = model clf.fit(X, y)"
},
{
"code": null,
"e": 2333,
"s": 2220,
"text": "We use %timeit, an iPython’s magic command to run each function 7 times and take the average of all experiments."
},
{
"code": null,
"e": 2481,
"s": 2333,
"text": "Average time of sklearn's SVC 48.56009825014287 sAverage time of cuml's SVC 19.611496431714304 sRatio between sklearn and cuml is 2.476103668030909"
},
{
"code": null,
"e": 2532,
"s": 2481,
"text": "cuML’s SVC is 2.5 times faster than sklearn’s SVC!"
},
{
"code": null,
"e": 2679,
"s": 2532,
"text": "Let’s visualize it through the plot. We create a function to plot the speed of the models. I use cutecharts because it makes the bar charts cuter."
},
{
"code": null,
"e": 2842,
"s": 2679,
"text": "Since cuML’s models are faster than Sklearn’s when running on large data because they were trained using GPU, what will happen if we triple the memory of the GPU?"
},
{
"code": null,
"e": 2965,
"s": 2842,
"text": "I use an Alienware M15 laptop with NVIDIA GeForce 2060 and a graphics card’s memory of 6.3 GB for the previous comparison."
},
{
"code": null,
"e": 3124,
"s": 2965,
"text": "Now I will use a Dell Precision 7740 with NVIDIA Quadro RTX 5000 and a graphics card’s memory of 17 GB to test the speed when the memory of the GPU increases."
},
{
"code": null,
"e": 3273,
"s": 3124,
"text": "Average time of sklearn's SVC 35.791008955999914 sAverage time of cuml's SVC 1.9953700327142931 sRatio between sklearn and cuml is 17.93702840535976"
},
{
"code": null,
"e": 3505,
"s": 3273,
"text": "Wow! cuML’s SVM is 18 times faster than Sklearn’s SVM when it is trained on a machine with a graphics card’s memory of 17 GB! And it is 10 times faster than the speed of training on a laptop with a graphics card’s memory of 6.3 GB."
},
{
"code": null,
"e": 3625,
"s": 3505,
"text": "That is why it is better for us to have a good GPU in our machines if we are using GPU-accelerated libraries like cuML."
},
{
"code": null,
"e": 3812,
"s": 3625,
"text": "Average time of sklearn's RandomForestClassifier 29.824075075857113 sAverage time of cuml's RandomForestClassifier 0.49404465585715635 sRatio between sklearn and cuml is 60.3671646323408"
},
{
"code": null,
"e": 4073,
"s": 3812,
"text": "cuML’s RandomForestClassifier is 60 times faster than Sklearn’s RandomForestClassifier! If it takes 30 seconds for you to train a Sklearn’s RandomForestClassifier, it takes less than half of a second to train a cuML’s RandomForestClassifier. How crazy is that?"
},
{
"code": null,
"e": 4269,
"s": 4073,
"text": "Average time of Sklearn's RandomForestClassifier 24.006061030143037 sAverage time of cuML's RandomForestClassifier 0.15141178591425808 s.The ratio between Sklearn’s and cuML is 158.54816641379068"
},
{
"code": null,
"e": 4404,
"s": 4269,
"text": "cuML’s RandomForestClassifier is 158 times faster than Sklearn’s RandomForestClassifier when trained on my Dell Precision 7740 laptop!"
},
{
"code": null,
"e": 4590,
"s": 4404,
"text": "Average time of sklearn's KNeighborsClassifier 0.07836367340000508 sAverage time of cuml's KNeighborsClassifier 0.004251259535714585 sRatio between sklearn and cuml is 18.43304854518441"
},
{
"code": null,
"e": 4674,
"s": 4590,
"text": "cuML’s KNeighborsClassifier is 18 times faster than Sklearn’s KNeighborsClassifier."
},
{
"code": null,
"e": 4862,
"s": 4674,
"text": "Average time of sklearn's KNeighborsClassifier 0.07511190322854547 sAverage time of cuml's KNeighborsClassifier 0.0015137992111426033 sRatio between sklearn and cuml is 49.618141346401956"
},
{
"code": null,
"e": 4991,
"s": 4862,
"text": "cuML’s KNeighborsClassifier is 50 times faster than Sklearn’ KNeighborsClassifier when trained on my Dell Precision 7740 laptop."
},
{
"code": null,
"e": 5051,
"s": 4991,
"text": "You can find the code for the rest of the comparisons here."
},
{
"code": null,
"e": 5144,
"s": 5051,
"text": "Here are the two tables that summarize the speed of different models between 2 libraries on:"
},
{
"code": null,
"e": 5211,
"s": 5144,
"text": "Alienware M15 — GeForce 2060 and a graphic card’s memory of 6.3 GB"
},
{
"code": null,
"e": 5286,
"s": 5211,
"text": "Dell Precision 7740 — Quadro RTX 5000 and a graphic card’s memory of 17 GB"
},
{
"code": null,
"e": 5315,
"s": 5286,
"text": "Pretty impressive, isn’t it?"
},
{
"code": null,
"e": 5601,
"s": 5315,
"text": "Congratulations! You have just learned how fast training different models on cuML is compared to Sklearn. If it takes a long time to train your model using Sklearn, I highly recommend giving cuML a try, considering there is literally no change in code at all compared to Sklearn’s API."
},
{
"code": null,
"e": 5754,
"s": 5601,
"text": "And of course, with a library that uses GPU to execute the code like cuML, the better graphic card you have, the faster the training will be on average."
},
{
"code": null,
"e": 5826,
"s": 5754,
"text": "Check out the doc of cuML for details on other machine learning models."
},
{
"code": null,
"e": 5880,
"s": 5826,
"text": "The source code for this article could be found here."
},
{
"code": null,
"e": 5891,
"s": 5880,
"text": "github.com"
},
{
"code": null,
"e": 6051,
"s": 5891,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
How to open youtube app from webview in android?
|
This example demonstrate about How to open youtube app from webview in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show youtube app.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setLightTouchEnabled(true);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setGeolocationEnabled(true);
web_view.setSoundEffectsEnabled(true);
web_view.loadUrl("https://www.youtube.com/watch?v = atnyX5yjLj0");
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrate about How to open youtube app from webview in android."
},
{
"code": null,
"e": 1271,
"s": 1142,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1903,
"s": 1336,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1966,
"s": 1903,
"text": "In the above code, we have taken web view to show youtube app."
},
{
"code": null,
"e": 2023,
"s": 1966,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3531,
"s": 2023,
"text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setLightTouchEnabled(true);\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setGeolocationEnabled(true);\n web_view.setSoundEffectsEnabled(true);\n web_view.loadUrl(\"https://www.youtube.com/watch?v = atnyX5yjLj0\");\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3586,
"s": 3531,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4363,
"s": 3586,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4710,
"s": 4363,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4750,
"s": 4710,
"text": "Click here to download the project code"
}
] |
Exploring NLP concepts using Apache OpenNLP inside a Java-enabled Jupyter notebook | by Mani Sarkar | Towards Data Science
|
I have been exploring and playing around with the Apache OpenNLP library after a bit of convincing. For those who are not aware of it, it’s an Apache project, supporters of F/OSS Java projects for the last two decades or so (see Wikipedia). I found their command-line interface pretty simple to use and it is a great learning tool for learning and trying to understand Natural Language Processing (NLP). Independent of this post, you can find another perspective on exploring NLP concepts using Apache OpenNLP, all of this directly from the realms of your command-prompt.
I can say almost everyone in this space is also aware and familiar with Jupyter Notebooks (in case you are not, have a look at this video or [1] or [2]). Here onwards we will be doing the same things you have been doing with your own experiments from within the realms of the notebook.
I’ll refer you to the post where we cover the command-line experience with Apache OpenNLP, and it’s a great way to familiarise yourself with this NLP library.
Do the following before proceeding any further:
$ git clone git@github.com:neomatrix369/nlp-java-jvm-example.gitor$ git clone https://github.com/neomatrix369/nlp-java-jvm-example.git$ cd nlp-java-jvm-example
And then see Getting started section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further.
Also, we have chosen the JDK to be GraalVM by default, you can see this from these lines in the console messages:
<---snipped-->JDK_TO_USE=GRAALVMopenjdk version "11.0.5" 2019-10-15OpenJDK Runtime Environment (build 11.0.5+10-jvmci-19.3-b05-LTS)OpenJDK 64-Bit GraalVM CE 19.3.0 (build 11.0.5+10-jvmci-19.3-b05-LTS, mixed mode, sharing)<---snipped-->
Note: a docker image has been provided to be able to run a docker container that would contain all the tools you need. You can see the shared folder has been created which is linked to the volume mounted into your container, mapping your the folder from the local machine. So anything created or downloaded into the shared folder will be available even after you exit your container!
Have a quick read of the main README file to get an idea of how to go about using the docker-runner.sh shell script, and take a quick glance at the Usage section of the scripts as well.
See Running the Jupyter notebook container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further.
All you need to do is run this command after cloning the repo mentioned in the links above:
$ ./docker-runner.sh --notebookMode --runContainer
Once you have the above running, the action will automatically open load the Jupyter notebook interface for you into a browser window. You will have a couple of Java notebooks to choose from (placed in the shared/notebooks folder on your local machine):
When inside the container in the notebook mode, you have two approaches to install Apache OpenNLP:
From the command-line interface (optional)
See From the command-line interface sub-section under the Installing Apache OpenNLP in the container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further.
From inside the Jupyter notebook (recommended)
See From inside the Jupyter notebook sub-section under the Installing Apache OpenNLP in the container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further.
See Viewing and accessing the shared folder section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further.
This will also be covered in a small way via the Jupyter notebooks in the following section. You can see directory contents via the %system Java cell magic and then from the command prompt a similar files/folders layout.
While you have the notebook server running you will see this launcher window with a list of notebooks and other supporting files show up as soon as the notebook server launches:
Each of the notebooks above has a purpose, MyFirstJupyterNLPJavaNotebook.ipynb shows how to write Java in a IPython notebook and perform NLP actions using Java code snippets that invoke the Apache OpenNLP library functionalities (see docs for more details on the classes and methods and also the Java Docs for more details on the Java API usages).
The other notebook MyNextJupyterNLPJavaNotebook.ipynb runs the same Java code snippets on a remote cloud instance (with the help of the Valohai CLI client) and returns the results in the cells, with just single commands. It’s fast and free to create an account and use within the free-tier plan.
We are able to examine the below Java API bindings to the Apache OpenNLP library from inside both the Java-based notebooks:
Language Detector API
Sentence Detection API
Tokenizer API
Name Finder API (including other examples)
Parts of speech (POS) Tagger API
Chunking API
Parsing API
Exploring the above Apache OpenNLP Java APIs via the notebook directly
We are able to do this from inside a notebook, running the IJava Jupyter interpreter which allows writing Java in a typical notebook. We will be exploring the above named Java APIs using small snippets of Java code and see the results appear in the notebook:
So go back to your browser and look for the MyFirstJupyterNLPJavaNotebook.ipynb notebook and have a play with it, reading and executing each cell and observing the responses.
Exploring the above Apache OpenNLP Java APIs via the notebook with the help of remote cloud services
We are able to do this from inside a notebook, running the IJava Jupyter interpreter which allows writing Java in a typical notebook. But in this notebook, we have taken it further and used the %system Java cell magic and the Valohai CLI magic instead of running the Java code snippets in the various cells like the previous notebook.
So that way the downloading of the models and processing of the text using the model does not happen on your local machine but one a more sophisticated remote server in the cloud. And you are able to control this process from inside the notebook cells. This is more relevant when the models and the datasets to process are large and your local instance(s) do not have the necessary resources to support long-standing NLP processes. I have seen NLP training and evaluations to take long to finish and hence high-spec resources are a must.
And again go back to your browser and look for the MyNextJupyterNLPJavaNotebook.ipynb notebook and have a play with it, reading and executing each cell. All the necessary details are in there including links to the docs and supporting pages.
To get a deeper understanding of how these two notebooks were put together and how they work operationally, please have a look at all the source files.
Make sure you have saved your notebook before you do this. Switch to the console window from where you ran the docker-runner shell script. Pressing Ctrl-C in the console running the Docker container gives you this:
<---snipped--->[I 21:13:16.253 NotebookApp] Saving file at /MyFirstJupyterJavaNotebook.ipynb^C[I 21:13:22.953 NotebookApp] interruptedServing notebooks from local directory: /home/jovyan/work1 active kernelThe Jupyter Notebook is running at:http://1e2b8182be38:8888/Shutdown this notebook server (y/[n])? y[C 21:14:05.035 NotebookApp] Shutdown confirmed[I 21:14:05.036 NotebookApp] Shutting down 1 kernelNov 15, 2019 9:14:05 PM io.github.spencerpark.jupyter.channels.Loop shutdownINFO: Loop shutdown.<--snipped-->[I 21:14:05.441 NotebookApp] Kernel shutdown: 448d46f0-1bde-461b-be60-e248c6342f69
This shuts down the container and you are back to your local machine command-prompt. Your notebook stays preserved in the shares/notebooks folder on your local machine, provided you have been saving them as you kept changing them.
There are other Java/JVM based NLP libraries mentioned in the Resources section below, for brevity we won’t cover them. The links provided will lead to further information for your own pursuit.
Within the Apache OpenNLP tool itself, we have only covered the command-line access part of it and not the Java Bindings. In addition, we haven’t gone through all the NLP concepts or features of the tool again for brevity have only covered a handful of them. But the documentation and resources on the GitHub repo should help in further exploration.
You can also find out how to build the docker image for yourself, by examining the docker-runner script.
Although the Java cell magic does make a difference and helps run commands. Even though it’s a non-Python based notebook we could still run shell commands and execute Java code in our cells and do some decent NLP work in the Jupyter notebooks.
If you had a python-based notebook, then Valohai’s extension called Jupyhai specially made for such purposes would suffice. Have a look at the Jupyhai sub-section in the Resources section of this post (at the end of the post). In fact, we have been running all our actions in the Jupyhai notebook, although I have been calling it Jupyter Notebook, have a look at the icon on the toolbar in the middle part of the panel in the browser):
This has been a very different experience than most of the other ways of exploring and learning, and you can see why the whole industry specifically speaking areas that cover Academia, Research, Data Science and Machine Learning have taken this approach like a storm. We still have limitations but with time even they will be overcome making our experience a smooth one.
Seeing your results in the same page where your code sits is a lot assuring and gives us a short and quick feedback loop. Especially being able to see the visualisations and change them dynamically and get instant results can cut through the cruft for busy and eager students, scientists, mathematicians, engineers and analysts in every field not just Computing or Data Science or Machine Learning.
Github
Docs
%system Java cell magic implementation
Docker image with IJava + Jupyhai + other dependencies
Version Control for Jupyter Notebooks
Blogs on Jupyter Notebooks
Valohai’s Jupyter Notebook Extension
Asynchronous Workflows in Data Science
Automatic Version Control Meets Jupyter Notebooks
Level Up Your Machine Learning Code from Notebook to Production
Run Jupyter Notebook On Any Cloud Provider
Updates for Valohai Powered Notebooks
Version control for Jupyter Notebooks (video)
Docs
nlp-java-jvm-example GitHub project
Apache OpenNLP | GitHub | Mailing list | @apacheopennlp
Docs
Documentation resources
Manual
Apache OpenNLP Tools Javadoc
Download
Apache OpenNLP Jar/binary
Model Zoo
Models page
Language Detect model
Older models to support the examples in the docs
Legends to support the examples in the docs
List of languages
Penn Treebank tagset
Find more in the Resources section in the README
How to do Deep Learning for Java?
NLP with DL4J in Java, all from the command-line
Exploring NLP concepts using Apache OpenNLP
|
[
{
"code": null,
"e": 743,
"s": 171,
"text": "I have been exploring and playing around with the Apache OpenNLP library after a bit of convincing. For those who are not aware of it, it’s an Apache project, supporters of F/OSS Java projects for the last two decades or so (see Wikipedia). I found their command-line interface pretty simple to use and it is a great learning tool for learning and trying to understand Natural Language Processing (NLP). Independent of this post, you can find another perspective on exploring NLP concepts using Apache OpenNLP, all of this directly from the realms of your command-prompt."
},
{
"code": null,
"e": 1029,
"s": 743,
"text": "I can say almost everyone in this space is also aware and familiar with Jupyter Notebooks (in case you are not, have a look at this video or [1] or [2]). Here onwards we will be doing the same things you have been doing with your own experiments from within the realms of the notebook."
},
{
"code": null,
"e": 1188,
"s": 1029,
"text": "I’ll refer you to the post where we cover the command-line experience with Apache OpenNLP, and it’s a great way to familiarise yourself with this NLP library."
},
{
"code": null,
"e": 1236,
"s": 1188,
"text": "Do the following before proceeding any further:"
},
{
"code": null,
"e": 1396,
"s": 1236,
"text": "$ git clone git@github.com:neomatrix369/nlp-java-jvm-example.gitor$ git clone https://github.com/neomatrix369/nlp-java-jvm-example.git$ cd nlp-java-jvm-example"
},
{
"code": null,
"e": 1551,
"s": 1396,
"text": "And then see Getting started section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further."
},
{
"code": null,
"e": 1665,
"s": 1551,
"text": "Also, we have chosen the JDK to be GraalVM by default, you can see this from these lines in the console messages:"
},
{
"code": null,
"e": 1901,
"s": 1665,
"text": "<---snipped-->JDK_TO_USE=GRAALVMopenjdk version \"11.0.5\" 2019-10-15OpenJDK Runtime Environment (build 11.0.5+10-jvmci-19.3-b05-LTS)OpenJDK 64-Bit GraalVM CE 19.3.0 (build 11.0.5+10-jvmci-19.3-b05-LTS, mixed mode, sharing)<---snipped-->"
},
{
"code": null,
"e": 2285,
"s": 1901,
"text": "Note: a docker image has been provided to be able to run a docker container that would contain all the tools you need. You can see the shared folder has been created which is linked to the volume mounted into your container, mapping your the folder from the local machine. So anything created or downloaded into the shared folder will be available even after you exit your container!"
},
{
"code": null,
"e": 2471,
"s": 2285,
"text": "Have a quick read of the main README file to get an idea of how to go about using the docker-runner.sh shell script, and take a quick glance at the Usage section of the scripts as well."
},
{
"code": null,
"e": 2640,
"s": 2471,
"text": "See Running the Jupyter notebook container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further."
},
{
"code": null,
"e": 2732,
"s": 2640,
"text": "All you need to do is run this command after cloning the repo mentioned in the links above:"
},
{
"code": null,
"e": 2783,
"s": 2732,
"text": "$ ./docker-runner.sh --notebookMode --runContainer"
},
{
"code": null,
"e": 3037,
"s": 2783,
"text": "Once you have the above running, the action will automatically open load the Jupyter notebook interface for you into a browser window. You will have a couple of Java notebooks to choose from (placed in the shared/notebooks folder on your local machine):"
},
{
"code": null,
"e": 3136,
"s": 3037,
"text": "When inside the container in the notebook mode, you have two approaches to install Apache OpenNLP:"
},
{
"code": null,
"e": 3179,
"s": 3136,
"text": "From the command-line interface (optional)"
},
{
"code": null,
"e": 3406,
"s": 3179,
"text": "See From the command-line interface sub-section under the Installing Apache OpenNLP in the container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further."
},
{
"code": null,
"e": 3453,
"s": 3406,
"text": "From inside the Jupyter notebook (recommended)"
},
{
"code": null,
"e": 3681,
"s": 3453,
"text": "See From inside the Jupyter notebook sub-section under the Installing Apache OpenNLP in the container section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further."
},
{
"code": null,
"e": 3851,
"s": 3681,
"text": "See Viewing and accessing the shared folder section in the Exploring NLP concepts from inside a Java-based Jupyter notebook part of the README before proceeding further."
},
{
"code": null,
"e": 4072,
"s": 3851,
"text": "This will also be covered in a small way via the Jupyter notebooks in the following section. You can see directory contents via the %system Java cell magic and then from the command prompt a similar files/folders layout."
},
{
"code": null,
"e": 4250,
"s": 4072,
"text": "While you have the notebook server running you will see this launcher window with a list of notebooks and other supporting files show up as soon as the notebook server launches:"
},
{
"code": null,
"e": 4598,
"s": 4250,
"text": "Each of the notebooks above has a purpose, MyFirstJupyterNLPJavaNotebook.ipynb shows how to write Java in a IPython notebook and perform NLP actions using Java code snippets that invoke the Apache OpenNLP library functionalities (see docs for more details on the classes and methods and also the Java Docs for more details on the Java API usages)."
},
{
"code": null,
"e": 4894,
"s": 4598,
"text": "The other notebook MyNextJupyterNLPJavaNotebook.ipynb runs the same Java code snippets on a remote cloud instance (with the help of the Valohai CLI client) and returns the results in the cells, with just single commands. It’s fast and free to create an account and use within the free-tier plan."
},
{
"code": null,
"e": 5018,
"s": 4894,
"text": "We are able to examine the below Java API bindings to the Apache OpenNLP library from inside both the Java-based notebooks:"
},
{
"code": null,
"e": 5040,
"s": 5018,
"text": "Language Detector API"
},
{
"code": null,
"e": 5063,
"s": 5040,
"text": "Sentence Detection API"
},
{
"code": null,
"e": 5077,
"s": 5063,
"text": "Tokenizer API"
},
{
"code": null,
"e": 5120,
"s": 5077,
"text": "Name Finder API (including other examples)"
},
{
"code": null,
"e": 5153,
"s": 5120,
"text": "Parts of speech (POS) Tagger API"
},
{
"code": null,
"e": 5166,
"s": 5153,
"text": "Chunking API"
},
{
"code": null,
"e": 5178,
"s": 5166,
"text": "Parsing API"
},
{
"code": null,
"e": 5249,
"s": 5178,
"text": "Exploring the above Apache OpenNLP Java APIs via the notebook directly"
},
{
"code": null,
"e": 5508,
"s": 5249,
"text": "We are able to do this from inside a notebook, running the IJava Jupyter interpreter which allows writing Java in a typical notebook. We will be exploring the above named Java APIs using small snippets of Java code and see the results appear in the notebook:"
},
{
"code": null,
"e": 5683,
"s": 5508,
"text": "So go back to your browser and look for the MyFirstJupyterNLPJavaNotebook.ipynb notebook and have a play with it, reading and executing each cell and observing the responses."
},
{
"code": null,
"e": 5784,
"s": 5683,
"text": "Exploring the above Apache OpenNLP Java APIs via the notebook with the help of remote cloud services"
},
{
"code": null,
"e": 6119,
"s": 5784,
"text": "We are able to do this from inside a notebook, running the IJava Jupyter interpreter which allows writing Java in a typical notebook. But in this notebook, we have taken it further and used the %system Java cell magic and the Valohai CLI magic instead of running the Java code snippets in the various cells like the previous notebook."
},
{
"code": null,
"e": 6657,
"s": 6119,
"text": "So that way the downloading of the models and processing of the text using the model does not happen on your local machine but one a more sophisticated remote server in the cloud. And you are able to control this process from inside the notebook cells. This is more relevant when the models and the datasets to process are large and your local instance(s) do not have the necessary resources to support long-standing NLP processes. I have seen NLP training and evaluations to take long to finish and hence high-spec resources are a must."
},
{
"code": null,
"e": 6899,
"s": 6657,
"text": "And again go back to your browser and look for the MyNextJupyterNLPJavaNotebook.ipynb notebook and have a play with it, reading and executing each cell. All the necessary details are in there including links to the docs and supporting pages."
},
{
"code": null,
"e": 7051,
"s": 6899,
"text": "To get a deeper understanding of how these two notebooks were put together and how they work operationally, please have a look at all the source files."
},
{
"code": null,
"e": 7266,
"s": 7051,
"text": "Make sure you have saved your notebook before you do this. Switch to the console window from where you ran the docker-runner shell script. Pressing Ctrl-C in the console running the Docker container gives you this:"
},
{
"code": null,
"e": 7862,
"s": 7266,
"text": "<---snipped--->[I 21:13:16.253 NotebookApp] Saving file at /MyFirstJupyterJavaNotebook.ipynb^C[I 21:13:22.953 NotebookApp] interruptedServing notebooks from local directory: /home/jovyan/work1 active kernelThe Jupyter Notebook is running at:http://1e2b8182be38:8888/Shutdown this notebook server (y/[n])? y[C 21:14:05.035 NotebookApp] Shutdown confirmed[I 21:14:05.036 NotebookApp] Shutting down 1 kernelNov 15, 2019 9:14:05 PM io.github.spencerpark.jupyter.channels.Loop shutdownINFO: Loop shutdown.<--snipped-->[I 21:14:05.441 NotebookApp] Kernel shutdown: 448d46f0-1bde-461b-be60-e248c6342f69"
},
{
"code": null,
"e": 8093,
"s": 7862,
"text": "This shuts down the container and you are back to your local machine command-prompt. Your notebook stays preserved in the shares/notebooks folder on your local machine, provided you have been saving them as you kept changing them."
},
{
"code": null,
"e": 8287,
"s": 8093,
"text": "There are other Java/JVM based NLP libraries mentioned in the Resources section below, for brevity we won’t cover them. The links provided will lead to further information for your own pursuit."
},
{
"code": null,
"e": 8637,
"s": 8287,
"text": "Within the Apache OpenNLP tool itself, we have only covered the command-line access part of it and not the Java Bindings. In addition, we haven’t gone through all the NLP concepts or features of the tool again for brevity have only covered a handful of them. But the documentation and resources on the GitHub repo should help in further exploration."
},
{
"code": null,
"e": 8742,
"s": 8637,
"text": "You can also find out how to build the docker image for yourself, by examining the docker-runner script."
},
{
"code": null,
"e": 8986,
"s": 8742,
"text": "Although the Java cell magic does make a difference and helps run commands. Even though it’s a non-Python based notebook we could still run shell commands and execute Java code in our cells and do some decent NLP work in the Jupyter notebooks."
},
{
"code": null,
"e": 9422,
"s": 8986,
"text": "If you had a python-based notebook, then Valohai’s extension called Jupyhai specially made for such purposes would suffice. Have a look at the Jupyhai sub-section in the Resources section of this post (at the end of the post). In fact, we have been running all our actions in the Jupyhai notebook, although I have been calling it Jupyter Notebook, have a look at the icon on the toolbar in the middle part of the panel in the browser):"
},
{
"code": null,
"e": 9793,
"s": 9422,
"text": "This has been a very different experience than most of the other ways of exploring and learning, and you can see why the whole industry specifically speaking areas that cover Academia, Research, Data Science and Machine Learning have taken this approach like a storm. We still have limitations but with time even they will be overcome making our experience a smooth one."
},
{
"code": null,
"e": 10192,
"s": 9793,
"text": "Seeing your results in the same page where your code sits is a lot assuring and gives us a short and quick feedback loop. Especially being able to see the visualisations and change them dynamically and get instant results can cut through the cruft for busy and eager students, scientists, mathematicians, engineers and analysts in every field not just Computing or Data Science or Machine Learning."
},
{
"code": null,
"e": 10199,
"s": 10192,
"text": "Github"
},
{
"code": null,
"e": 10204,
"s": 10199,
"text": "Docs"
},
{
"code": null,
"e": 10243,
"s": 10204,
"text": "%system Java cell magic implementation"
},
{
"code": null,
"e": 10298,
"s": 10243,
"text": "Docker image with IJava + Jupyhai + other dependencies"
},
{
"code": null,
"e": 10336,
"s": 10298,
"text": "Version Control for Jupyter Notebooks"
},
{
"code": null,
"e": 10363,
"s": 10336,
"text": "Blogs on Jupyter Notebooks"
},
{
"code": null,
"e": 10400,
"s": 10363,
"text": "Valohai’s Jupyter Notebook Extension"
},
{
"code": null,
"e": 10439,
"s": 10400,
"text": "Asynchronous Workflows in Data Science"
},
{
"code": null,
"e": 10489,
"s": 10439,
"text": "Automatic Version Control Meets Jupyter Notebooks"
},
{
"code": null,
"e": 10553,
"s": 10489,
"text": "Level Up Your Machine Learning Code from Notebook to Production"
},
{
"code": null,
"e": 10596,
"s": 10553,
"text": "Run Jupyter Notebook On Any Cloud Provider"
},
{
"code": null,
"e": 10634,
"s": 10596,
"text": "Updates for Valohai Powered Notebooks"
},
{
"code": null,
"e": 10680,
"s": 10634,
"text": "Version control for Jupyter Notebooks (video)"
},
{
"code": null,
"e": 10685,
"s": 10680,
"text": "Docs"
},
{
"code": null,
"e": 10721,
"s": 10685,
"text": "nlp-java-jvm-example GitHub project"
},
{
"code": null,
"e": 10777,
"s": 10721,
"text": "Apache OpenNLP | GitHub | Mailing list | @apacheopennlp"
},
{
"code": null,
"e": 10782,
"s": 10777,
"text": "Docs"
},
{
"code": null,
"e": 10806,
"s": 10782,
"text": "Documentation resources"
},
{
"code": null,
"e": 10813,
"s": 10806,
"text": "Manual"
},
{
"code": null,
"e": 10842,
"s": 10813,
"text": "Apache OpenNLP Tools Javadoc"
},
{
"code": null,
"e": 10851,
"s": 10842,
"text": "Download"
},
{
"code": null,
"e": 10877,
"s": 10851,
"text": "Apache OpenNLP Jar/binary"
},
{
"code": null,
"e": 10887,
"s": 10877,
"text": "Model Zoo"
},
{
"code": null,
"e": 10899,
"s": 10887,
"text": "Models page"
},
{
"code": null,
"e": 10921,
"s": 10899,
"text": "Language Detect model"
},
{
"code": null,
"e": 10970,
"s": 10921,
"text": "Older models to support the examples in the docs"
},
{
"code": null,
"e": 11014,
"s": 10970,
"text": "Legends to support the examples in the docs"
},
{
"code": null,
"e": 11032,
"s": 11014,
"text": "List of languages"
},
{
"code": null,
"e": 11053,
"s": 11032,
"text": "Penn Treebank tagset"
},
{
"code": null,
"e": 11102,
"s": 11053,
"text": "Find more in the Resources section in the README"
},
{
"code": null,
"e": 11136,
"s": 11102,
"text": "How to do Deep Learning for Java?"
},
{
"code": null,
"e": 11185,
"s": 11136,
"text": "NLP with DL4J in Java, all from the command-line"
}
] |
Mahotas – Gaussian filtering
|
06 May, 2021
In this article we will see how we can do Gaussian filtering in mahotas. For this we are going to use the fluorescent microscopy image from a nuclear segmentation benchmark. We can get the image with the help of command given below
mhotas.demos.nuclear_image()
A Gaussian filter is a linear filter. It’s usually used to blur the image or to reduce noise. If you use two of them and subtract, you can use them for “unsharp masking” (edge detection). The Gaussian filter alone will blur edges and reduce contrast.Below is the nuclear_image
In order to do this we will use mahotas.gaussian_filter method
Syntax : mahotas.gaussian_filter(nuclear, 20)Argument : It takes numpy.ndarray object as argument and a integerReturn : It returns numpy.ndarray object
Note : The input of the gaussian filter should be the filtered image object In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
image = image[:, :, 0]
Example 1 :
Python3
# importing required librariesimport mahotasimport mahotas.demosimport numpy as npfrom pylab import imshow, show # getting nuclear imagenuclear = mh.demos.nuclear_image() # filtering the imagenuclear = nuclear[:, :, 0] print("Image with filter")# showing the imageimshow(nuclear)show() # setting gaussian filternuclear = mahotas.gaussian_filter(nuclear, 35) print("Image with gaussian filter")# showing the gaussian filterimshow(nuclear)show()
Output :
Example 2:
Python3
# importing required librariesimport numpy as npimport mahotasfrom pylab import imshow, show # loading imageimg = mahotas.imread('dog_image.png') # filtering the imageimg = img[:, :, 0] print("Image with filter")# showing the imageimshow(img)show() # setting gaussian filtergaussian = mahotas.gaussian_filter(img, 15) print("Image with gaussian filter")# showing the gaussian filterimshow(gaussian)show()
Output :
sweetyty
arorakashish0911
Image-Processing
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "In this article we will see how we can do Gaussian filtering in mahotas. For this we are going to use the fluorescent microscopy image from a nuclear segmentation benchmark. We can get the image with the help of command given below "
},
{
"code": null,
"e": 291,
"s": 262,
"text": "mhotas.demos.nuclear_image()"
},
{
"code": null,
"e": 570,
"s": 291,
"text": "A Gaussian filter is a linear filter. It’s usually used to blur the image or to reduce noise. If you use two of them and subtract, you can use them for “unsharp masking” (edge detection). The Gaussian filter alone will blur edges and reduce contrast.Below is the nuclear_image "
},
{
"code": null,
"e": 635,
"s": 570,
"text": "In order to do this we will use mahotas.gaussian_filter method "
},
{
"code": null,
"e": 789,
"s": 635,
"text": "Syntax : mahotas.gaussian_filter(nuclear, 20)Argument : It takes numpy.ndarray object as argument and a integerReturn : It returns numpy.ndarray object "
},
{
"code": null,
"e": 1022,
"s": 789,
"text": "Note : The input of the gaussian filter should be the filtered image object In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this "
},
{
"code": null,
"e": 1045,
"s": 1022,
"text": "image = image[:, :, 0]"
},
{
"code": null,
"e": 1059,
"s": 1045,
"text": "Example 1 : "
},
{
"code": null,
"e": 1067,
"s": 1059,
"text": "Python3"
},
{
"code": "# importing required librariesimport mahotasimport mahotas.demosimport numpy as npfrom pylab import imshow, show # getting nuclear imagenuclear = mh.demos.nuclear_image() # filtering the imagenuclear = nuclear[:, :, 0] print(\"Image with filter\")# showing the imageimshow(nuclear)show() # setting gaussian filternuclear = mahotas.gaussian_filter(nuclear, 35) print(\"Image with gaussian filter\")# showing the gaussian filterimshow(nuclear)show()",
"e": 1512,
"s": 1067,
"text": null
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": "Output : "
},
{
"code": null,
"e": 1536,
"s": 1523,
"text": "Example 2: "
},
{
"code": null,
"e": 1544,
"s": 1536,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy as npimport mahotasfrom pylab import imshow, show # loading imageimg = mahotas.imread('dog_image.png') # filtering the imageimg = img[:, :, 0] print(\"Image with filter\")# showing the imageimshow(img)show() # setting gaussian filtergaussian = mahotas.gaussian_filter(img, 15) print(\"Image with gaussian filter\")# showing the gaussian filterimshow(gaussian)show()",
"e": 1952,
"s": 1544,
"text": null
},
{
"code": null,
"e": 1963,
"s": 1952,
"text": "Output : "
},
{
"code": null,
"e": 1974,
"s": 1965,
"text": "sweetyty"
},
{
"code": null,
"e": 1991,
"s": 1974,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2008,
"s": 1991,
"text": "Image-Processing"
},
{
"code": null,
"e": 2023,
"s": 2008,
"text": "Python-Mahotas"
},
{
"code": null,
"e": 2030,
"s": 2023,
"text": "Python"
},
{
"code": null,
"e": 2128,
"s": 2030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2146,
"s": 2128,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2188,
"s": 2146,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2210,
"s": 2188,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2245,
"s": 2210,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2271,
"s": 2245,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2303,
"s": 2271,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2332,
"s": 2303,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2359,
"s": 2332,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2389,
"s": 2359,
"text": "Iterate over a list in Python"
}
] |
CSS | :disabled Selector
|
04 Dec, 2018
The :disabled selector is used to select the disabled element. This property is mostly used on the form elements.
Syntax:
:disabled {
// CSS property
}
You can also Set a background color for all disabled input elements of type=”text”:
input[type=text]:disabled {
background: #dddddd;
}
Example 1:
<!DOCTYPE html><html> <head> <title>disable property</title> <style> h1 { color:green; } input[type=text]:enabled { background: green; } input[type=text]:disabled { background: white; } input { width:150px; padding-left:10px; margin-top:10px; border:1px solid black; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:disabled Selector</h2> <form action=""> Author Name: <input type="text" value="Geeks"><br> College Name: <input type="text" value="GFG"><br> Country: <input type="text" disabled="disabled" value="India"> </form> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>disable selector</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h2>:disabled Selector</h2> <select> <option value="s1">Data Structure</option> <option value="s2" disabled>Algorithm</option> <option value="s3">Operating System</option> <option value="s4" disabled>HTML</option> <option value="s5">C programming</option> </select> </body></html>
Output
Supported Browsers: The browser supported by :disabled selector are listed below:
Apple Safari 3.2
Google Chrome 4.0
Firefox 3.5
Opera 9.6
Internet Explorer 9.0
More Selectors:
Advanced Selectors
Checked Selectors
Attribute Selector
CSS-Selectors
CSS
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": "\n04 Dec, 2018"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "The :disabled selector is used to select the disabled element. This property is mostly used on the form elements."
},
{
"code": null,
"e": 150,
"s": 142,
"text": "Syntax:"
},
{
"code": null,
"e": 185,
"s": 150,
"text": ":disabled {\n // CSS property\n} "
},
{
"code": null,
"e": 269,
"s": 185,
"text": "You can also Set a background color for all disabled input elements of type=”text”:"
},
{
"code": null,
"e": 324,
"s": 269,
"text": "input[type=text]:disabled {\n background: #dddddd;\n}"
},
{
"code": null,
"e": 335,
"s": 324,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>disable property</title> <style> h1 { color:green; } input[type=text]:enabled { background: green; } input[type=text]:disabled { background: white; } input { width:150px; padding-left:10px; margin-top:10px; border:1px solid black; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>:disabled Selector</h2> <form action=\"\"> Author Name: <input type=\"text\" value=\"Geeks\"><br> College Name: <input type=\"text\" value=\"GFG\"><br> Country: <input type=\"text\" disabled=\"disabled\" value=\"India\"> </form> </body></html> ",
"e": 1278,
"s": 335,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Output:"
},
{
"code": null,
"e": 1297,
"s": 1286,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>disable selector</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h2>:disabled Selector</h2> <select> <option value=\"s1\">Data Structure</option> <option value=\"s2\" disabled>Algorithm</option> <option value=\"s3\">Operating System</option> <option value=\"s4\" disabled>HTML</option> <option value=\"s5\">C programming</option> </select> </body></html> ",
"e": 1953,
"s": 1297,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1953,
"text": "Output"
},
{
"code": null,
"e": 2042,
"s": 1960,
"text": "Supported Browsers: The browser supported by :disabled selector are listed below:"
},
{
"code": null,
"e": 2059,
"s": 2042,
"text": "Apple Safari 3.2"
},
{
"code": null,
"e": 2077,
"s": 2059,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 2089,
"s": 2077,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 2099,
"s": 2089,
"text": "Opera 9.6"
},
{
"code": null,
"e": 2121,
"s": 2099,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 2137,
"s": 2121,
"text": "More Selectors:"
},
{
"code": null,
"e": 2156,
"s": 2137,
"text": "Advanced Selectors"
},
{
"code": null,
"e": 2174,
"s": 2156,
"text": "Checked Selectors"
},
{
"code": null,
"e": 2193,
"s": 2174,
"text": "Attribute Selector"
},
{
"code": null,
"e": 2207,
"s": 2193,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 2211,
"s": 2207,
"text": "CSS"
},
{
"code": null,
"e": 2216,
"s": 2211,
"text": "HTML"
},
{
"code": null,
"e": 2233,
"s": 2216,
"text": "Web Technologies"
},
{
"code": null,
"e": 2238,
"s": 2233,
"text": "HTML"
}
] |
What does the 'tearoff' attribute do in a Tkinter Menu?
|
Using Tkinter.Menu, we can create menus and submenus. Also, there are some other properties which are used with tkinter menus.
Tearoff property makes the menus in the window as tearable. tearoff attribute accepts a Boolean value to separate the menu from the main window or the parent window. With tearoff attribute, we have two options,
If tearoff=0, make the menu stick to the Window.
If tearoff=0, make the menu stick to the Window.
If tearoff=1, it display a “----” empty dotted lines on the menus through which we can separate our menu from the window.
If tearoff=1, it display a “----” empty dotted lines on the menus through which we can separate our menu from the window.
#Importing the tkinter library
from tkinter import *
win= Tk()
win.title("Tearoff Example")
win.geometry("600x500")
#Define a Function for Menu Selection Event
def mytext():
lab= Label(win,text= "You have made a selection", font=('Helvetica',20)).pack(pady=20)
#Create a Menubar
menu_bar = Menu(win)
#Make the menus non-tearable
file_menu = Menu(menu_bar, tearoff=0)
#Tearable Menu
#file_menu= Menu(menu_bar, tearoff=1)
file_menu.add_command(label="New",command=mytext)
# all file menu-items will be added here next
menu_bar.add_cascade(label='File', menu=file_menu)
win.config(menu=menu_bar)
mainloop()
Running the above snippet will generate the output and will show a window which
will have a menu.
Thus, for non-tearable and tearable menus (tearoff=0 and tearoff=1), the output
will be as follows −
|
[
{
"code": null,
"e": 1314,
"s": 1187,
"text": "Using Tkinter.Menu, we can create menus and submenus. Also, there are some other properties which are used with tkinter menus."
},
{
"code": null,
"e": 1525,
"s": 1314,
"text": "Tearoff property makes the menus in the window as tearable. tearoff attribute accepts a Boolean value to separate the menu from the main window or the parent window. With tearoff attribute, we have two options,"
},
{
"code": null,
"e": 1574,
"s": 1525,
"text": "If tearoff=0, make the menu stick to the Window."
},
{
"code": null,
"e": 1623,
"s": 1574,
"text": "If tearoff=0, make the menu stick to the Window."
},
{
"code": null,
"e": 1745,
"s": 1623,
"text": "If tearoff=1, it display a “----” empty dotted lines on the menus through which we can separate our menu from the window."
},
{
"code": null,
"e": 1867,
"s": 1745,
"text": "If tearoff=1, it display a “----” empty dotted lines on the menus through which we can separate our menu from the window."
},
{
"code": null,
"e": 2479,
"s": 1867,
"text": "#Importing the tkinter library\nfrom tkinter import *\nwin= Tk()\nwin.title(\"Tearoff Example\")\nwin.geometry(\"600x500\")\n\n#Define a Function for Menu Selection Event\ndef mytext():\n lab= Label(win,text= \"You have made a selection\", font=('Helvetica',20)).pack(pady=20)\n\n#Create a Menubar\nmenu_bar = Menu(win)\n\n#Make the menus non-tearable\nfile_menu = Menu(menu_bar, tearoff=0)\n\n#Tearable Menu\n#file_menu= Menu(menu_bar, tearoff=1)\nfile_menu.add_command(label=\"New\",command=mytext)\n# all file menu-items will be added here next\nmenu_bar.add_cascade(label='File', menu=file_menu)\nwin.config(menu=menu_bar)\n\nmainloop()"
},
{
"code": null,
"e": 2577,
"s": 2479,
"text": "Running the above snippet will generate the output and will show a window which\nwill have a menu."
},
{
"code": null,
"e": 2678,
"s": 2577,
"text": "Thus, for non-tearable and tearable menus (tearoff=0 and tearoff=1), the output\nwill be as follows −"
}
] |
Fix Drop table view #1051 unknown table error in MySQL
|
To correctly drop a view, use the below syntax −
drop view yourViewName;
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int
-> );
Query OK, 0 rows affected (1.01 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1001);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(1002);
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values(1003);
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+
| Id |
+------+
| 1001 |
| 1002 |
| 1003 |
+------+
3 rows in set (0.00 sec)
Let us first create a view −
mysql> create view view_DemoTable as select Id from DemoTable;
Query OK, 0 rows affected (0.23 sec)
We will now display the records of the view −
mysql> select *from view_DemoTable;
This will produce the following output −
+------+
| Id |
+------+
| 1001 |
| 1002 |
| 1003 |
+------+
3 rows in set (0.05 sec)
Following is the query to drop view −
mysql> drop view view_DemoTable;
Query OK, 0 rows affected (0.18 sec)
Now view is dropped successfully.
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "To correctly drop a view, use the below syntax −"
},
{
"code": null,
"e": 1135,
"s": 1111,
"text": "drop view yourViewName;"
},
{
"code": null,
"e": 1165,
"s": 1135,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1253,
"s": 1165,
"text": "mysql> create table DemoTable\n-> (\n-> Id int\n-> );\nQuery OK, 0 rows affected (1.01 sec)"
},
{
"code": null,
"e": 1309,
"s": 1253,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1548,
"s": 1309,
"text": "mysql> insert into DemoTable values(1001);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into DemoTable values(1002);\nQuery OK, 1 row affected (0.34 sec)\n\nmysql> insert into DemoTable values(1003);\nQuery OK, 1 row affected (0.26 sec)"
},
{
"code": null,
"e": 1608,
"s": 1548,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1639,
"s": 1608,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1680,
"s": 1639,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1768,
"s": 1680,
"text": "+------+\n| Id |\n+------+\n| 1001 |\n| 1002 |\n| 1003 |\n+------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1797,
"s": 1768,
"text": "Let us first create a view −"
},
{
"code": null,
"e": 1897,
"s": 1797,
"text": "mysql> create view view_DemoTable as select Id from DemoTable;\nQuery OK, 0 rows affected (0.23 sec)"
},
{
"code": null,
"e": 1943,
"s": 1897,
"text": "We will now display the records of the view −"
},
{
"code": null,
"e": 1979,
"s": 1943,
"text": "mysql> select *from view_DemoTable;"
},
{
"code": null,
"e": 2020,
"s": 1979,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2108,
"s": 2020,
"text": "+------+\n| Id |\n+------+\n| 1001 |\n| 1002 |\n| 1003 |\n+------+\n3 rows in set (0.05 sec)"
},
{
"code": null,
"e": 2146,
"s": 2108,
"text": "Following is the query to drop view −"
},
{
"code": null,
"e": 2216,
"s": 2146,
"text": "mysql> drop view view_DemoTable;\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 2250,
"s": 2216,
"text": "Now view is dropped successfully."
}
] |
Circular Crop an Image and Save it to the File in Android - GeeksforGeeks
|
05 Aug, 2021
There are multiple applications available in the market that help in dealing with image processing, while most of them fail to produce very basic operations. Cropping is a simple application when one could resize an image by cutting it down. This task becomes complex when it comes to free-hand or shape cropping, meaning cropping the image in the desired shape.
In this article, we will show you how you create an application to crop an image in a circular manner and store it in the local device. No external library or service is used to generate this application.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add an ImageView and two Buttons in the activity_main.xml or the layout file
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Image will be loaded here --> <ImageView android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="500dp" android:layout_centerInParent="true" /> <!-- Button to perform Cropping --> <Button android:id="@+id/btnCrop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="Crop" /> <!-- Button to save the image in ImageView --> <Button android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="Save" /> </RelativeLayout>
Step 3: Add the desired image in the res > drawable folder
While adding, give it the desired name. For our reference, this image is “image.png” which is downloaded from the Internet and copied directly into the drawable folder.
Step 4: Write the following code for MainActivity.kt
There are two functions inside this code:
getCircularBitmap(Bitmap) : To crop the imagesaveMediaToStorage(Bitmap) : To save the image. Refer How to Capture Screenshot of a View and Save it to Gallery in Android?
getCircularBitmap(Bitmap) : To crop the image
saveMediaToStorage(Bitmap) : To save the image. Refer How to Capture Screenshot of a View and Save it to Gallery in Android?
Refer to the comments for better understanding.
Kotlin
import android.content.ContentValuesimport android.graphics.*import android.net.Uriimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.Toastimport androidx.annotation.RequiresApiimport java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStreamimport java.lang.Integer.min class MainActivity : AppCompatActivity() { // Declaring the UI elements from the layout file private lateinit var buttonCrop: Button private lateinit var buttonSave: Button private lateinit var imageView: ImageView // Declaring the Bitmap private lateinit var bitmap: Bitmap @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the UI elements imageView = findViewById(R.id.iv) buttonCrop = findViewById(R.id.btnCrop) buttonSave = findViewById(R.id.btnSave) // Declaring resource address ( type integer) val bitmapResourceID: Int = R.drawable.image // Setting the ImageView with the Image imageView.setImageBitmap(BitmapFactory.decodeResource(resources, bitmapResourceID)) bitmap = BitmapFactory.decodeResource(resources, bitmapResourceID) // When Crop button is clicked buttonCrop.setOnClickListener { // runs a custom function on the original image bitmap = getCircularBitmap(bitmap) // Sets the ImageView with the editted/cropped Image imageView.setImageBitmap(bitmap) } // When Save button is clicked buttonSave.setOnClickListener { // Save whatever the bitmap is (edited/uneditted) into the device. saveMediaToStorage(bitmap) } } // Function to crop the image in a circle @RequiresApi(Build.VERSION_CODES.N) private fun getCircularBitmap(srcBitmap: Bitmap?): Bitmap { // Select whichever of width or height is minimum val squareBitmapWidth = min(srcBitmap!!.width, srcBitmap.height) // Generate a bitmap with the above value as dimensions val dstBitmap = Bitmap.createBitmap( squareBitmapWidth, squareBitmapWidth, Bitmap.Config.ARGB_8888 ) // Initializing a Canvas with the above generated bitmap val canvas = Canvas(dstBitmap) // initializing Paint val paint = Paint() paint.isAntiAlias = true // Generate a square (rectangle with all sides same) val rect = Rect(0, 0, squareBitmapWidth, squareBitmapWidth) val rectF = RectF(rect) // Operations to draw a circle canvas.drawOval(rectF, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) val left = ((squareBitmapWidth - srcBitmap.width) / 2).toFloat() val top = ((squareBitmapWidth - srcBitmap.height) / 2).toFloat() canvas.drawBitmap(srcBitmap, left, top, paint) srcBitmap.recycle() // Return the bitmap return dstBitmap } // Function to save an Image private fun saveMediaToStorage(bitmap: Bitmap) { val filename = "${System.currentTimeMillis()}.jpg" var fos: OutputStream? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { this.contentResolver?.also { resolver -> val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg") put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) } val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) fos = imageUri?.let { resolver.openOutputStream(it) } } } else { val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) val image = File(imagesDir, filename) fos = FileOutputStream(image) } fos?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it) Toast.makeText(this , "Captured View and saved to Gallery" , Toast.LENGTH_SHORT).show() } }}
Step 4: Add Storage permission in the AndroidManifest.xml file
This permission is needed to store the image in the device.
XML
<manifest...."> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application....> </application></manifest>
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
MVP (Model View Presenter) Architecture Pattern in Android with Example
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 25479,
"s": 25116,
"text": "There are multiple applications available in the market that help in dealing with image processing, while most of them fail to produce very basic operations. Cropping is a simple application when one could resize an image by cutting it down. This task becomes complex when it comes to free-hand or shape cropping, meaning cropping the image in the desired shape."
},
{
"code": null,
"e": 25684,
"s": 25479,
"text": "In this article, we will show you how you create an application to crop an image in a circular manner and store it in the local device. No external library or service is used to generate this application."
},
{
"code": null,
"e": 25731,
"s": 25684,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 25970,
"s": 25731,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 26055,
"s": 25970,
"text": "Step 2: Add an ImageView and two Buttons in the activity_main.xml or the layout file"
},
{
"code": null,
"e": 26059,
"s": 26055,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Image will be loaded here --> <ImageView android:id=\"@+id/iv\" android:layout_width=\"match_parent\" android:layout_height=\"500dp\" android:layout_centerInParent=\"true\" /> <!-- Button to perform Cropping --> <Button android:id=\"@+id/btnCrop\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:text=\"Crop\" /> <!-- Button to save the image in ImageView --> <Button android:id=\"@+id/btnSave\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_alignParentRight=\"true\" android:text=\"Save\" /> </RelativeLayout>",
"e": 27128,
"s": 26059,
"text": null
},
{
"code": null,
"e": 27187,
"s": 27128,
"text": "Step 3: Add the desired image in the res > drawable folder"
},
{
"code": null,
"e": 27356,
"s": 27187,
"text": "While adding, give it the desired name. For our reference, this image is “image.png” which is downloaded from the Internet and copied directly into the drawable folder."
},
{
"code": null,
"e": 27409,
"s": 27356,
"text": "Step 4: Write the following code for MainActivity.kt"
},
{
"code": null,
"e": 27451,
"s": 27409,
"text": "There are two functions inside this code:"
},
{
"code": null,
"e": 27621,
"s": 27451,
"text": "getCircularBitmap(Bitmap) : To crop the imagesaveMediaToStorage(Bitmap) : To save the image. Refer How to Capture Screenshot of a View and Save it to Gallery in Android?"
},
{
"code": null,
"e": 27667,
"s": 27621,
"text": "getCircularBitmap(Bitmap) : To crop the image"
},
{
"code": null,
"e": 27792,
"s": 27667,
"text": "saveMediaToStorage(Bitmap) : To save the image. Refer How to Capture Screenshot of a View and Save it to Gallery in Android?"
},
{
"code": null,
"e": 27840,
"s": 27792,
"text": "Refer to the comments for better understanding."
},
{
"code": null,
"e": 27847,
"s": 27840,
"text": "Kotlin"
},
{
"code": "import android.content.ContentValuesimport android.graphics.*import android.net.Uriimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.Toastimport androidx.annotation.RequiresApiimport java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStreamimport java.lang.Integer.min class MainActivity : AppCompatActivity() { // Declaring the UI elements from the layout file private lateinit var buttonCrop: Button private lateinit var buttonSave: Button private lateinit var imageView: ImageView // Declaring the Bitmap private lateinit var bitmap: Bitmap @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the UI elements imageView = findViewById(R.id.iv) buttonCrop = findViewById(R.id.btnCrop) buttonSave = findViewById(R.id.btnSave) // Declaring resource address ( type integer) val bitmapResourceID: Int = R.drawable.image // Setting the ImageView with the Image imageView.setImageBitmap(BitmapFactory.decodeResource(resources, bitmapResourceID)) bitmap = BitmapFactory.decodeResource(resources, bitmapResourceID) // When Crop button is clicked buttonCrop.setOnClickListener { // runs a custom function on the original image bitmap = getCircularBitmap(bitmap) // Sets the ImageView with the editted/cropped Image imageView.setImageBitmap(bitmap) } // When Save button is clicked buttonSave.setOnClickListener { // Save whatever the bitmap is (edited/uneditted) into the device. saveMediaToStorage(bitmap) } } // Function to crop the image in a circle @RequiresApi(Build.VERSION_CODES.N) private fun getCircularBitmap(srcBitmap: Bitmap?): Bitmap { // Select whichever of width or height is minimum val squareBitmapWidth = min(srcBitmap!!.width, srcBitmap.height) // Generate a bitmap with the above value as dimensions val dstBitmap = Bitmap.createBitmap( squareBitmapWidth, squareBitmapWidth, Bitmap.Config.ARGB_8888 ) // Initializing a Canvas with the above generated bitmap val canvas = Canvas(dstBitmap) // initializing Paint val paint = Paint() paint.isAntiAlias = true // Generate a square (rectangle with all sides same) val rect = Rect(0, 0, squareBitmapWidth, squareBitmapWidth) val rectF = RectF(rect) // Operations to draw a circle canvas.drawOval(rectF, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) val left = ((squareBitmapWidth - srcBitmap.width) / 2).toFloat() val top = ((squareBitmapWidth - srcBitmap.height) / 2).toFloat() canvas.drawBitmap(srcBitmap, left, top, paint) srcBitmap.recycle() // Return the bitmap return dstBitmap } // Function to save an Image private fun saveMediaToStorage(bitmap: Bitmap) { val filename = \"${System.currentTimeMillis()}.jpg\" var fos: OutputStream? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { this.contentResolver?.also { resolver -> val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, \"image/jpg\") put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) } val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) fos = imageUri?.let { resolver.openOutputStream(it) } } } else { val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) val image = File(imagesDir, filename) fos = FileOutputStream(image) } fos?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it) Toast.makeText(this , \"Captured View and saved to Gallery\" , Toast.LENGTH_SHORT).show() } }}",
"e": 32382,
"s": 27847,
"text": null
},
{
"code": null,
"e": 32445,
"s": 32382,
"text": "Step 4: Add Storage permission in the AndroidManifest.xml file"
},
{
"code": null,
"e": 32505,
"s": 32445,
"text": "This permission is needed to store the image in the device."
},
{
"code": null,
"e": 32509,
"s": 32505,
"text": "XML"
},
{
"code": "<manifest....\"> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <application....> </application></manifest>",
"e": 32658,
"s": 32509,
"text": null
},
{
"code": null,
"e": 32666,
"s": 32658,
"text": "Output:"
},
{
"code": null,
"e": 32674,
"s": 32666,
"text": "Android"
},
{
"code": null,
"e": 32681,
"s": 32674,
"text": "Kotlin"
},
{
"code": null,
"e": 32689,
"s": 32681,
"text": "Android"
},
{
"code": null,
"e": 32787,
"s": 32689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32826,
"s": 32787,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32876,
"s": 32826,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32918,
"s": 32876,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32956,
"s": 32918,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 33029,
"s": 32956,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 33048,
"s": 33029,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 33061,
"s": 33048,
"text": "Kotlin Array"
},
{
"code": null,
"e": 33103,
"s": 33061,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33130,
"s": 33103,
"text": "Kotlin Setters and Getters"
}
] |
Logistic Regression using Python (scikit-learn) | by Michael Galarnyk | Towards Data Science
|
One of the most amazing things about Python’s scikit-learn library is that is has a 4-step modeling pattern that makes it easy to code a machine learning classifier. While this tutorial uses a classifier called Logistic Regression, the coding process in this tutorial applies to other classifiers in sklearn (Decision Tree, K-Nearest Neighbors etc). In this tutorial, we use Logistic Regression to predict digit labels based on images. The image above shows a bunch of training digits (observations) from the MNIST dataset whose category membership is known (labels 0–9). After training a model with logistic regression, it can be used to predict an image label (labels 0–9) given an image.
The first part of this tutorial post goes over a toy dataset (digits dataset) to show quickly illustrate scikit-learn’s 4 step modeling pattern and show the behavior of the logistic regression algorthm. The second part of the tutorial goes over a more realistic dataset (MNIST dataset) to briefly show how changing a model’s default parameters can effect performance (both in timing and accuracy of the model).With that, lets get started. If you get lost, I recommend opening the video above in a separate tab. The code used in this tutorial is available below
Digits Logistic Regression (first part of tutorial code)
MNIST Logistic Regression (second part of tutorial code)
If you already have anaconda installed, skip to the next section. I recommend having anaconda installed (either Python 2 or 3 works well for this tutorial) so you won’t have any issue importing libraries.
You can either download anaconda from the official site and install on your own or you can follow these anaconda installation tutorials below to set up anaconda on your operating system.
Install Anaconda on Windows: Link
Install Anaconda on Mac: Link
Install Anaconda on Ubuntu (Linux): Link
The digits dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the digits dataset.
from sklearn.datasets import load_digitsdigits = load_digits()
Now that you have the dataset loaded you can use the commands below
# Print to show there are 1797 images (8 by 8 images for a dimensionality of 64)print(“Image Data Shape” , digits.data.shape)# Print to show there are 1797 labels (integers from 0–9)print("Label Data Shape", digits.target.shape)
to see that there are 1797 images and 1797 labels in the dataset
This section is really just to show what the images and labels look like. It usually helps to visualize your data to see what you are working with.
import numpy as np import matplotlib.pyplot as pltplt.figure(figsize=(20,4))for index, (image, label) in enumerate(zip(digits.data[0:5], digits.target[0:5])): plt.subplot(1, 5, index + 1) plt.imshow(np.reshape(image, (8,8)), cmap=plt.cm.gray) plt.title('Training: %i\n' % label, fontsize = 20)
The code below performs a train test split which puts 75% of the data into a training set and 25% of the data into a test set. This is to make sure that our classification algorithm is able to generalize well to new data.
from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=0)
Step 1. Import the model you want to use
In sklearn, all machine learning models are implemented as Python classes
from sklearn.linear_model import LogisticRegression
Step 2. Make an instance of the Model
# all parameters not specified are set to their defaultslogisticRegr = LogisticRegression()
Step 3. Training the model on the data, storing the information learned from the data
Model is learning the relationship between digits (x_train) and labels (y_train)
logisticRegr.fit(x_train, y_train)
Step 4. Predict labels for new data (new images)
Uses the information the model learned during the model training process
# Returns a NumPy Array# Predict for One Observation (image)logisticRegr.predict(x_test[0].reshape(1,-1))
Predict for Multiple Observations (images) at Once
logisticRegr.predict(x_test[0:10])
Make predictions on entire test data
predictions = logisticRegr.predict(x_test)
While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric. To do this are going to see how the model performs on the new data (test set)
accuracy is defined as:
(fraction of correct predictions): correct predictions / total number of data points
# Use score method to get accuracy of modelscore = logisticRegr.score(x_test, y_test)print(score)
Our accuracy was 95.3%.
A confusion matrix is a table that is often used to describe the performance of a classification model (or “classifier”) on a set of test data for which the true values are known. In this section, I am just showing two python packages (Seaborn and Matplotlib) for making confusion matrices more understandable and visually appealing.
import matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import metrics
The confusion matrix below is not visually super informative or visually appealing.
cm = metrics.confusion_matrix(y_test, predictions)print(cm)
Method 1 (Seaborn)
As you can see below, this method produces a more understandable and visually readable confusion matrix using seaborn.
plt.figure(figsize=(9,9))sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r');plt.ylabel('Actual label');plt.xlabel('Predicted label');all_sample_title = 'Accuracy Score: {0}'.format(score)plt.title(all_sample_title, size = 15);
Method 2 (Matplotlib)This method is clearly a lot more code. I just wanted to show people how to do it in matplotlib as well.
plt.figure(figsize=(9,9))plt.imshow(cm, interpolation='nearest', cmap='Pastel1')plt.title('Confusion matrix', size = 15)plt.colorbar()tick_marks = np.arange(10)plt.xticks(tick_marks, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], rotation=45, size = 10)plt.yticks(tick_marks, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], size = 10)plt.tight_layout()plt.ylabel('Actual label', size = 15)plt.xlabel('Predicted label', size = 15)width, height = cm.shapefor x in xrange(width): for y in xrange(height): plt.annotate(str(cm[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center')
One important point to emphasize that the digit dataset contained in sklearn is too small to be representative of a real world machine learning task.We are going to use the MNIST dataset because it is for people who want to try learning techniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessing and formatting. One of the things we will notice is that parameter tuning can greatly speed up a machine learning algorithm’s training time.
The MNIST dataset doesn’t come from within scikit-learn
from sklearn.datasets import fetch_mldatamnist = fetch_mldata('MNIST original')
Now that you have the dataset loaded you can use the commands below
# These are the images# There are 70,000 images (28 by 28 images for a dimensionality of 784)print(mnist.data.shape)# These are the labelsprint(mnist.target.shape)
to see that there are 70000 images and 70000 labels in the dataset
The code below performs a train test split. test_size=1/7.0 makes the training set size 60,000 images and the test set size 10,000 images.
from sklearn.model_selection import train_test_splittrain_img, test_img, train_lbl, test_lbl = train_test_split( mnist.data, mnist.target, test_size=1/7.0, random_state=0)
import numpy as npimport matplotlib.pyplot as pltplt.figure(figsize=(20,4))for index, (image, label) in enumerate(zip(train_img[0:5], train_lbl[0:5])): plt.subplot(1, 5, index + 1) plt.imshow(np.reshape(image, (28,28)), cmap=plt.cm.gray) plt.title('Training: %i\n' % label, fontsize = 20)
One thing I like to mention is the importance of parameter tuning. While it may not have mattered much for the smaller digits dataset, it makes a bigger difference on larger and more complex datasets. While usually one adjusts parameters for the sake of accuracy, in the case below, we are adjusting the parameter solver to speed up the fitting of the model.
Step 1. Import the model you want to use
In sklearn, all machine learning models are implemented as Python classes
from sklearn.linear_model import LogisticRegression
Step 2. Make an instance of the Model
Please see this tutorial if you are curious what changing solver does. Essentially, we are changing the optimization algorithm.
# all parameters not specified are set to their defaults# default solver is incredibly slow thats why we change itlogisticRegr = LogisticRegression(solver = 'lbfgs')
Step 3. Training the model on the data, storing the information learned from the data
Model is learning the relationship between x (digits) and y (labels)
logisticRegr.fit(train_img, train_lbl)
Step 4. Predict the labels of new data (new images)Uses the information the model learned during the model training process
# Returns a NumPy Array# Predict for One Observation (image)logisticRegr.predict(test_img[0].reshape(1,-1))
Predict for Multiple Observations (images) at Once
logisticRegr.predict(test_img[0:10])
Make predictions on entire test data
predictions = logisticRegr.predict(test_img)
While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric. To do this are going to see how the model performs on the new data (test set)
accuracy is defined as:
(fraction of correct predictions): correct predictions / total number of data points
score = logisticRegr.score(test_img, test_lbl)print(score)
One thing I briefly want to mention is that is the default optimization algorithm parameter was solver = liblinear and it took 2893.1 seconds to run with a accuracy of 91.45%. When I set solver = lbfgs , it took 52.86 seconds to run with an accuracy of 91.3%. Changing the solver had a minor effect on accuracy, but at least it was a lot faster.
While I could show another confusion matrix, I figured people would rather see misclassified images on the off chance someone finds it interesting.
Getting the misclassified images’ index
import numpy as np import matplotlib.pyplot as pltindex = 0misclassifiedIndexes = []for label, predict in zip(test_lbl, predictions): if label != predict: misclassifiedIndexes.append(index) index +=1
Showing the misclassified images and image labels using matplotlib
plt.figure(figsize=(20,4))for plotIndex, badIndex in enumerate(misclassifiedIndexes[0:5]): plt.subplot(1, 5, plotIndex + 1) plt.imshow(np.reshape(test_img[badIndex], (28,28)), cmap=plt.cm.gray) plt.title(‘Predicted: {}, Actual: {}’.format(predictions[badIndex], test_lbl[badIndex]), fontsize = 15)
The important thing to note here is that making a machine learning model in scikit-learn is not a lot of work. I hope this post helps you with whatever you are working on. My next machine learning tutorial goes over PCA using Python. If you have any questions or thoughts on the tutorial, feel free to reach out in the comments below, through YouTube video page, or through Twitter! If you want to learn about other machine learning algorithms, please consider taking my Machine Learning with Scikit-Learn LinkedIn Learning course.
|
[
{
"code": null,
"e": 863,
"s": 172,
"text": "One of the most amazing things about Python’s scikit-learn library is that is has a 4-step modeling pattern that makes it easy to code a machine learning classifier. While this tutorial uses a classifier called Logistic Regression, the coding process in this tutorial applies to other classifiers in sklearn (Decision Tree, K-Nearest Neighbors etc). In this tutorial, we use Logistic Regression to predict digit labels based on images. The image above shows a bunch of training digits (observations) from the MNIST dataset whose category membership is known (labels 0–9). After training a model with logistic regression, it can be used to predict an image label (labels 0–9) given an image."
},
{
"code": null,
"e": 1424,
"s": 863,
"text": "The first part of this tutorial post goes over a toy dataset (digits dataset) to show quickly illustrate scikit-learn’s 4 step modeling pattern and show the behavior of the logistic regression algorthm. The second part of the tutorial goes over a more realistic dataset (MNIST dataset) to briefly show how changing a model’s default parameters can effect performance (both in timing and accuracy of the model).With that, lets get started. If you get lost, I recommend opening the video above in a separate tab. The code used in this tutorial is available below"
},
{
"code": null,
"e": 1481,
"s": 1424,
"text": "Digits Logistic Regression (first part of tutorial code)"
},
{
"code": null,
"e": 1538,
"s": 1481,
"text": "MNIST Logistic Regression (second part of tutorial code)"
},
{
"code": null,
"e": 1743,
"s": 1538,
"text": "If you already have anaconda installed, skip to the next section. I recommend having anaconda installed (either Python 2 or 3 works well for this tutorial) so you won’t have any issue importing libraries."
},
{
"code": null,
"e": 1930,
"s": 1743,
"text": "You can either download anaconda from the official site and install on your own or you can follow these anaconda installation tutorials below to set up anaconda on your operating system."
},
{
"code": null,
"e": 1964,
"s": 1930,
"text": "Install Anaconda on Windows: Link"
},
{
"code": null,
"e": 1994,
"s": 1964,
"text": "Install Anaconda on Mac: Link"
},
{
"code": null,
"e": 2035,
"s": 1994,
"text": "Install Anaconda on Ubuntu (Linux): Link"
},
{
"code": null,
"e": 2218,
"s": 2035,
"text": "The digits dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the digits dataset."
},
{
"code": null,
"e": 2281,
"s": 2218,
"text": "from sklearn.datasets import load_digitsdigits = load_digits()"
},
{
"code": null,
"e": 2349,
"s": 2281,
"text": "Now that you have the dataset loaded you can use the commands below"
},
{
"code": null,
"e": 2578,
"s": 2349,
"text": "# Print to show there are 1797 images (8 by 8 images for a dimensionality of 64)print(“Image Data Shape” , digits.data.shape)# Print to show there are 1797 labels (integers from 0–9)print(\"Label Data Shape\", digits.target.shape)"
},
{
"code": null,
"e": 2643,
"s": 2578,
"text": "to see that there are 1797 images and 1797 labels in the dataset"
},
{
"code": null,
"e": 2791,
"s": 2643,
"text": "This section is really just to show what the images and labels look like. It usually helps to visualize your data to see what you are working with."
},
{
"code": null,
"e": 3085,
"s": 2791,
"text": "import numpy as np import matplotlib.pyplot as pltplt.figure(figsize=(20,4))for index, (image, label) in enumerate(zip(digits.data[0:5], digits.target[0:5])): plt.subplot(1, 5, index + 1) plt.imshow(np.reshape(image, (8,8)), cmap=plt.cm.gray) plt.title('Training: %i\\n' % label, fontsize = 20)"
},
{
"code": null,
"e": 3307,
"s": 3085,
"text": "The code below performs a train test split which puts 75% of the data into a training set and 25% of the data into a test set. This is to make sure that our classification algorithm is able to generalize well to new data."
},
{
"code": null,
"e": 3471,
"s": 3307,
"text": "from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=0)"
},
{
"code": null,
"e": 3512,
"s": 3471,
"text": "Step 1. Import the model you want to use"
},
{
"code": null,
"e": 3586,
"s": 3512,
"text": "In sklearn, all machine learning models are implemented as Python classes"
},
{
"code": null,
"e": 3638,
"s": 3586,
"text": "from sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 3676,
"s": 3638,
"text": "Step 2. Make an instance of the Model"
},
{
"code": null,
"e": 3768,
"s": 3676,
"text": "# all parameters not specified are set to their defaultslogisticRegr = LogisticRegression()"
},
{
"code": null,
"e": 3854,
"s": 3768,
"text": "Step 3. Training the model on the data, storing the information learned from the data"
},
{
"code": null,
"e": 3935,
"s": 3854,
"text": "Model is learning the relationship between digits (x_train) and labels (y_train)"
},
{
"code": null,
"e": 3970,
"s": 3935,
"text": "logisticRegr.fit(x_train, y_train)"
},
{
"code": null,
"e": 4019,
"s": 3970,
"text": "Step 4. Predict labels for new data (new images)"
},
{
"code": null,
"e": 4092,
"s": 4019,
"text": "Uses the information the model learned during the model training process"
},
{
"code": null,
"e": 4198,
"s": 4092,
"text": "# Returns a NumPy Array# Predict for One Observation (image)logisticRegr.predict(x_test[0].reshape(1,-1))"
},
{
"code": null,
"e": 4249,
"s": 4198,
"text": "Predict for Multiple Observations (images) at Once"
},
{
"code": null,
"e": 4284,
"s": 4249,
"text": "logisticRegr.predict(x_test[0:10])"
},
{
"code": null,
"e": 4321,
"s": 4284,
"text": "Make predictions on entire test data"
},
{
"code": null,
"e": 4364,
"s": 4321,
"text": "predictions = logisticRegr.predict(x_test)"
},
{
"code": null,
"e": 4612,
"s": 4364,
"text": "While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric. To do this are going to see how the model performs on the new data (test set)"
},
{
"code": null,
"e": 4636,
"s": 4612,
"text": "accuracy is defined as:"
},
{
"code": null,
"e": 4721,
"s": 4636,
"text": "(fraction of correct predictions): correct predictions / total number of data points"
},
{
"code": null,
"e": 4819,
"s": 4721,
"text": "# Use score method to get accuracy of modelscore = logisticRegr.score(x_test, y_test)print(score)"
},
{
"code": null,
"e": 4843,
"s": 4819,
"text": "Our accuracy was 95.3%."
},
{
"code": null,
"e": 5177,
"s": 4843,
"text": "A confusion matrix is a table that is often used to describe the performance of a classification model (or “classifier”) on a set of test data for which the true values are known. In this section, I am just showing two python packages (Seaborn and Matplotlib) for making confusion matrices more understandable and visually appealing."
},
{
"code": null,
"e": 5257,
"s": 5177,
"text": "import matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import metrics"
},
{
"code": null,
"e": 5341,
"s": 5257,
"text": "The confusion matrix below is not visually super informative or visually appealing."
},
{
"code": null,
"e": 5401,
"s": 5341,
"text": "cm = metrics.confusion_matrix(y_test, predictions)print(cm)"
},
{
"code": null,
"e": 5420,
"s": 5401,
"text": "Method 1 (Seaborn)"
},
{
"code": null,
"e": 5539,
"s": 5420,
"text": "As you can see below, this method produces a more understandable and visually readable confusion matrix using seaborn."
},
{
"code": null,
"e": 5802,
"s": 5539,
"text": "plt.figure(figsize=(9,9))sns.heatmap(cm, annot=True, fmt=\".3f\", linewidths=.5, square = True, cmap = 'Blues_r');plt.ylabel('Actual label');plt.xlabel('Predicted label');all_sample_title = 'Accuracy Score: {0}'.format(score)plt.title(all_sample_title, size = 15);"
},
{
"code": null,
"e": 5928,
"s": 5802,
"text": "Method 2 (Matplotlib)This method is clearly a lot more code. I just wanted to show people how to do it in matplotlib as well."
},
{
"code": null,
"e": 6540,
"s": 5928,
"text": "plt.figure(figsize=(9,9))plt.imshow(cm, interpolation='nearest', cmap='Pastel1')plt.title('Confusion matrix', size = 15)plt.colorbar()tick_marks = np.arange(10)plt.xticks(tick_marks, [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"], rotation=45, size = 10)plt.yticks(tick_marks, [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"], size = 10)plt.tight_layout()plt.ylabel('Actual label', size = 15)plt.xlabel('Predicted label', size = 15)width, height = cm.shapefor x in xrange(width): for y in xrange(height): plt.annotate(str(cm[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center')"
},
{
"code": null,
"e": 7028,
"s": 6540,
"text": "One important point to emphasize that the digit dataset contained in sklearn is too small to be representative of a real world machine learning task.We are going to use the MNIST dataset because it is for people who want to try learning techniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessing and formatting. One of the things we will notice is that parameter tuning can greatly speed up a machine learning algorithm’s training time."
},
{
"code": null,
"e": 7084,
"s": 7028,
"text": "The MNIST dataset doesn’t come from within scikit-learn"
},
{
"code": null,
"e": 7164,
"s": 7084,
"text": "from sklearn.datasets import fetch_mldatamnist = fetch_mldata('MNIST original')"
},
{
"code": null,
"e": 7232,
"s": 7164,
"text": "Now that you have the dataset loaded you can use the commands below"
},
{
"code": null,
"e": 7396,
"s": 7232,
"text": "# These are the images# There are 70,000 images (28 by 28 images for a dimensionality of 784)print(mnist.data.shape)# These are the labelsprint(mnist.target.shape)"
},
{
"code": null,
"e": 7463,
"s": 7396,
"text": "to see that there are 70000 images and 70000 labels in the dataset"
},
{
"code": null,
"e": 7602,
"s": 7463,
"text": "The code below performs a train test split. test_size=1/7.0 makes the training set size 60,000 images and the test set size 10,000 images."
},
{
"code": null,
"e": 7774,
"s": 7602,
"text": "from sklearn.model_selection import train_test_splittrain_img, test_img, train_lbl, test_lbl = train_test_split( mnist.data, mnist.target, test_size=1/7.0, random_state=0)"
},
{
"code": null,
"e": 8063,
"s": 7774,
"text": "import numpy as npimport matplotlib.pyplot as pltplt.figure(figsize=(20,4))for index, (image, label) in enumerate(zip(train_img[0:5], train_lbl[0:5])): plt.subplot(1, 5, index + 1) plt.imshow(np.reshape(image, (28,28)), cmap=plt.cm.gray) plt.title('Training: %i\\n' % label, fontsize = 20)"
},
{
"code": null,
"e": 8422,
"s": 8063,
"text": "One thing I like to mention is the importance of parameter tuning. While it may not have mattered much for the smaller digits dataset, it makes a bigger difference on larger and more complex datasets. While usually one adjusts parameters for the sake of accuracy, in the case below, we are adjusting the parameter solver to speed up the fitting of the model."
},
{
"code": null,
"e": 8463,
"s": 8422,
"text": "Step 1. Import the model you want to use"
},
{
"code": null,
"e": 8537,
"s": 8463,
"text": "In sklearn, all machine learning models are implemented as Python classes"
},
{
"code": null,
"e": 8589,
"s": 8537,
"text": "from sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 8627,
"s": 8589,
"text": "Step 2. Make an instance of the Model"
},
{
"code": null,
"e": 8755,
"s": 8627,
"text": "Please see this tutorial if you are curious what changing solver does. Essentially, we are changing the optimization algorithm."
},
{
"code": null,
"e": 8921,
"s": 8755,
"text": "# all parameters not specified are set to their defaults# default solver is incredibly slow thats why we change itlogisticRegr = LogisticRegression(solver = 'lbfgs')"
},
{
"code": null,
"e": 9007,
"s": 8921,
"text": "Step 3. Training the model on the data, storing the information learned from the data"
},
{
"code": null,
"e": 9076,
"s": 9007,
"text": "Model is learning the relationship between x (digits) and y (labels)"
},
{
"code": null,
"e": 9115,
"s": 9076,
"text": "logisticRegr.fit(train_img, train_lbl)"
},
{
"code": null,
"e": 9239,
"s": 9115,
"text": "Step 4. Predict the labels of new data (new images)Uses the information the model learned during the model training process"
},
{
"code": null,
"e": 9347,
"s": 9239,
"text": "# Returns a NumPy Array# Predict for One Observation (image)logisticRegr.predict(test_img[0].reshape(1,-1))"
},
{
"code": null,
"e": 9398,
"s": 9347,
"text": "Predict for Multiple Observations (images) at Once"
},
{
"code": null,
"e": 9435,
"s": 9398,
"text": "logisticRegr.predict(test_img[0:10])"
},
{
"code": null,
"e": 9472,
"s": 9435,
"text": "Make predictions on entire test data"
},
{
"code": null,
"e": 9517,
"s": 9472,
"text": "predictions = logisticRegr.predict(test_img)"
},
{
"code": null,
"e": 9765,
"s": 9517,
"text": "While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric. To do this are going to see how the model performs on the new data (test set)"
},
{
"code": null,
"e": 9789,
"s": 9765,
"text": "accuracy is defined as:"
},
{
"code": null,
"e": 9874,
"s": 9789,
"text": "(fraction of correct predictions): correct predictions / total number of data points"
},
{
"code": null,
"e": 9933,
"s": 9874,
"text": "score = logisticRegr.score(test_img, test_lbl)print(score)"
},
{
"code": null,
"e": 10279,
"s": 9933,
"text": "One thing I briefly want to mention is that is the default optimization algorithm parameter was solver = liblinear and it took 2893.1 seconds to run with a accuracy of 91.45%. When I set solver = lbfgs , it took 52.86 seconds to run with an accuracy of 91.3%. Changing the solver had a minor effect on accuracy, but at least it was a lot faster."
},
{
"code": null,
"e": 10427,
"s": 10279,
"text": "While I could show another confusion matrix, I figured people would rather see misclassified images on the off chance someone finds it interesting."
},
{
"code": null,
"e": 10467,
"s": 10427,
"text": "Getting the misclassified images’ index"
},
{
"code": null,
"e": 10670,
"s": 10467,
"text": "import numpy as np import matplotlib.pyplot as pltindex = 0misclassifiedIndexes = []for label, predict in zip(test_lbl, predictions): if label != predict: misclassifiedIndexes.append(index) index +=1"
},
{
"code": null,
"e": 10737,
"s": 10670,
"text": "Showing the misclassified images and image labels using matplotlib"
},
{
"code": null,
"e": 11035,
"s": 10737,
"text": "plt.figure(figsize=(20,4))for plotIndex, badIndex in enumerate(misclassifiedIndexes[0:5]): plt.subplot(1, 5, plotIndex + 1) plt.imshow(np.reshape(test_img[badIndex], (28,28)), cmap=plt.cm.gray) plt.title(‘Predicted: {}, Actual: {}’.format(predictions[badIndex], test_lbl[badIndex]), fontsize = 15)"
}
] |
Automating Portfolio Optimization and Allocation using Python | by Sanket Karve | Towards Data Science
|
Modern Portfolio Theory (MPT) or mean-variance analysis is a mathematical model/study for developing and creating a portfolio which aims to maximize the return for a given amount of risk. The math is largely based on the assumption and experience that an average human prefers a less risky portfolio. The risk mitigation can be done by either investing in traditional safe havens or by diversification — a cause championed by the MPT.
The theory was introduced by Henry Markowitz in the 1950s, for which he was awarded the Nobel prize. While the MPT has had its fair share of criticisms, partly due to its backward looking tendencies and inabilities to factor in force majeures/trends in business and economy, I find the tool valuable to gauge the risk of one’s portfolio holdings by measuring the volatility as a proxy.
I will be using Python to automate the optimization of the portfolio. The concepts of the theory are mentioned below in brief:-
Portfolio Expected Return -
Portfolio Expected Return -
The expected return of a portfolio is calculated by multiplying the weight of the asset by its return and summing the values of all the assets together. To introduce a forward looking estimate, probability may be introduced to generate and incorporate features in business and economy.
2. Portfolio Variance -
Portfolio variance is used as the measure of risk in this model. A higher variance will indicate a higher risk for the asset class and the portfolio. The formula is expressed as
3. Sharpe Ratio
The Sharpe ratio measures the return of an investment in relation to the risk-free rate (Treasury rate) and its risk profile. In general, a higher value for the Sharpe ratio indicates a better and more lucrative investment. Thus if comparing two portfolio’s with similar risk profiles, given all else equal it would be better to invest in the portfolio with a higher Sharpe Ratio.
4. The Efficient Frontier -
This plot measure risk vs returns and is used to select the most optimum portfolio to invest into after considering the risk profile and the characteristics of the investor. The efficient frontier is essential the part of the curve in the first and second quadrants depending on the objective and investor ability/characteristics.
The Capital Allocation Line (CAL) is essentially a tangent to the efficient frontier. The point of intersection between the tangent and the frontier is considered to be the optimal investment which has maximum returns for a given risk profile, under normal conditions
Importing Libraries
Importing Libraries
We will first import all the relevant libraries to help make our life easier as we progress.
#Importing all required libraries#Created by Sanket Karveimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pandas_datareader as webfrom matplotlib.ticker import FuncFormatter
Additionally, a critical library is the PyPortfolioOpt which contains functions to help us with the optimization of the portfolio. We will install the library with the following commands
!pip install PyPortfolioOpt#Installing the Portfolio Optimzation Library
Import the functions which will be required further on -
from pypfopt.efficient_frontier import EfficientFrontierfrom pypfopt import risk_modelsfrom pypfopt import expected_returnsfrom pypfopt.cla import CLAfrom pypfopt.plotting import Plottingfrom matplotlib.ticker import FuncFormatter
2. Scrapping Stock and Financial Data from the Web
We will pull data from Yahoo! Finance for various stock tickers. The tickers I have used are Boston Scientific, Berkshire Hathway, Invesco Trust, S&P Index Fund, AES Corp., and Sealed Air Corp. The tickers have been chosen to spread the investment across various industries.
After inputting the tickers, we need to create a blank dataframe which will be used to capture all the prices of the stocks via a loop. For the purpose of this exercise, I have filtered down to capture the Adjusted Close value of the stocks that we are studying.
tickers = ['BSX','AES','BRK-B','SEE','QQQ','SPY']thelen = len(tickers)price_data = []for ticker in range(thelen):prices = web.DataReader(tickers[ticker], start='2015-01-01', end = '2020-06-06', data_source='yahoo')price_data.append(prices.assign(ticker=ticker)[['Adj Close']])df_stocks = pd.concat(price_data, axis=1)df_stocks.columns=tickersdf_stocks.head()
Check if any values captured are ‘NaN’. Of less importance will be zero values. In case, there are NaN values — good practice will be to either consider a different time series or fill in the data with the average price of D-1, D+1. In case of a large void I would prefer not considering and deleting the time series data rather than inserting a zero value.
#Checking if any NaN values in the datanullin_df = pd.DataFrame(df_stocks,columns=tickers)print(nullin_df.isnull().sum())
3. Calculations
We will move ahead with the calculations for the optimization of the portfolio. Start with capturing the expected return and the variance of the portfolio chosen.
#Annualized Returnmu = expected_returns.mean_historical_return(df_stocks)#Sample Variance of PortfolioSigma = risk_models.sample_cov(df_stocks)
Proceed by computing and storing the values for a portfolio weight with maximum Sharpe ratio and minimum volatility respectively.
#Max Sharpe Ratio - Tangent to the EFef = EfficientFrontier(mu, Sigma, weight_bounds=(-1,1)) #weight bounds in negative allows shorting of stockssharpe_pfolio=ef.max_sharpe() #May use add objective to ensure minimum zero weighting to individual stockssharpe_pwt=ef.clean_weights()print(sharpe_pwt)
This will provide you the weight of different holdings. In case you want to minimize ‘zero’ holding or weight feel free to use L2 regression. Additionally, the weight_bounds have been set from -1 to 1 for allowing computation of ‘shorting’ stocks. The same exercise will be undertaken for the minimum variance portfolio.
4. Plotting the Efficient Frontier and Optimizing Portfolio Allocation
The final step is the plot the efficient frontier for visual purposes, and calculate the asset allocation (i.e. no of shares to purchase or short) for a given dollar amount of a portfolio. For the purpose of this exercise, I have considered $10,000 — the default starting value on investopedia.
latest_prices = discrete_allocation.get_latest_prices(df_stocks)# Allocate Portfolio Value in $ as required to show number of shares/stocks to buy, also bounds for shorting will affect allocation#Min Volatility Portfolio Allocation $10000allocation_minv, rem_minv = discrete_allocation.DiscreteAllocation(minvol_pwt, latest_prices, total_portfolio_value=10000).lp_portfolio()print(allocation_minv)print("Leftover Fund value in$ after building minimum volatility portfolio is ${:.2f}".format(rem_minv))
This will provide you with the optimized portfolio as seen below
The same can be done for calculating the portfolio with the maximum Sharpe ratio.
Investing is said to be part art part science. Python and its libraries allow us to automate optimization and save valuable time in the process of doing so. However, it must be noted that these techniques in isolation are unlikely to be the best way to approach investing.
Moving ahead, I will post about how we can choose stocks to replicate an index fund via machine learning to build our portfolio and many other functions which Python can assist us with. Finally, I have also created a program to calculate potential losses or variations in share prices using monte carlo simulations. This tool may be used in tandem with this portfolio optimizer.
towardsdatascience.com
The information above is in no means expert investment advise or practices and is merely an effort by the me discuss how Python can be used to automate portfolio optimization via the Modern Portfolio Theory (MPT). For the complete source code or for any discussion, feel free to reach out
|
[
{
"code": null,
"e": 606,
"s": 171,
"text": "Modern Portfolio Theory (MPT) or mean-variance analysis is a mathematical model/study for developing and creating a portfolio which aims to maximize the return for a given amount of risk. The math is largely based on the assumption and experience that an average human prefers a less risky portfolio. The risk mitigation can be done by either investing in traditional safe havens or by diversification — a cause championed by the MPT."
},
{
"code": null,
"e": 992,
"s": 606,
"text": "The theory was introduced by Henry Markowitz in the 1950s, for which he was awarded the Nobel prize. While the MPT has had its fair share of criticisms, partly due to its backward looking tendencies and inabilities to factor in force majeures/trends in business and economy, I find the tool valuable to gauge the risk of one’s portfolio holdings by measuring the volatility as a proxy."
},
{
"code": null,
"e": 1120,
"s": 992,
"text": "I will be using Python to automate the optimization of the portfolio. The concepts of the theory are mentioned below in brief:-"
},
{
"code": null,
"e": 1148,
"s": 1120,
"text": "Portfolio Expected Return -"
},
{
"code": null,
"e": 1176,
"s": 1148,
"text": "Portfolio Expected Return -"
},
{
"code": null,
"e": 1462,
"s": 1176,
"text": "The expected return of a portfolio is calculated by multiplying the weight of the asset by its return and summing the values of all the assets together. To introduce a forward looking estimate, probability may be introduced to generate and incorporate features in business and economy."
},
{
"code": null,
"e": 1486,
"s": 1462,
"text": "2. Portfolio Variance -"
},
{
"code": null,
"e": 1664,
"s": 1486,
"text": "Portfolio variance is used as the measure of risk in this model. A higher variance will indicate a higher risk for the asset class and the portfolio. The formula is expressed as"
},
{
"code": null,
"e": 1680,
"s": 1664,
"text": "3. Sharpe Ratio"
},
{
"code": null,
"e": 2061,
"s": 1680,
"text": "The Sharpe ratio measures the return of an investment in relation to the risk-free rate (Treasury rate) and its risk profile. In general, a higher value for the Sharpe ratio indicates a better and more lucrative investment. Thus if comparing two portfolio’s with similar risk profiles, given all else equal it would be better to invest in the portfolio with a higher Sharpe Ratio."
},
{
"code": null,
"e": 2089,
"s": 2061,
"text": "4. The Efficient Frontier -"
},
{
"code": null,
"e": 2420,
"s": 2089,
"text": "This plot measure risk vs returns and is used to select the most optimum portfolio to invest into after considering the risk profile and the characteristics of the investor. The efficient frontier is essential the part of the curve in the first and second quadrants depending on the objective and investor ability/characteristics."
},
{
"code": null,
"e": 2688,
"s": 2420,
"text": "The Capital Allocation Line (CAL) is essentially a tangent to the efficient frontier. The point of intersection between the tangent and the frontier is considered to be the optimal investment which has maximum returns for a given risk profile, under normal conditions"
},
{
"code": null,
"e": 2708,
"s": 2688,
"text": "Importing Libraries"
},
{
"code": null,
"e": 2728,
"s": 2708,
"text": "Importing Libraries"
},
{
"code": null,
"e": 2821,
"s": 2728,
"text": "We will first import all the relevant libraries to help make our life easier as we progress."
},
{
"code": null,
"e": 3021,
"s": 2821,
"text": "#Importing all required libraries#Created by Sanket Karveimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pandas_datareader as webfrom matplotlib.ticker import FuncFormatter"
},
{
"code": null,
"e": 3208,
"s": 3021,
"text": "Additionally, a critical library is the PyPortfolioOpt which contains functions to help us with the optimization of the portfolio. We will install the library with the following commands"
},
{
"code": null,
"e": 3281,
"s": 3208,
"text": "!pip install PyPortfolioOpt#Installing the Portfolio Optimzation Library"
},
{
"code": null,
"e": 3338,
"s": 3281,
"text": "Import the functions which will be required further on -"
},
{
"code": null,
"e": 3569,
"s": 3338,
"text": "from pypfopt.efficient_frontier import EfficientFrontierfrom pypfopt import risk_modelsfrom pypfopt import expected_returnsfrom pypfopt.cla import CLAfrom pypfopt.plotting import Plottingfrom matplotlib.ticker import FuncFormatter"
},
{
"code": null,
"e": 3620,
"s": 3569,
"text": "2. Scrapping Stock and Financial Data from the Web"
},
{
"code": null,
"e": 3895,
"s": 3620,
"text": "We will pull data from Yahoo! Finance for various stock tickers. The tickers I have used are Boston Scientific, Berkshire Hathway, Invesco Trust, S&P Index Fund, AES Corp., and Sealed Air Corp. The tickers have been chosen to spread the investment across various industries."
},
{
"code": null,
"e": 4158,
"s": 3895,
"text": "After inputting the tickers, we need to create a blank dataframe which will be used to capture all the prices of the stocks via a loop. For the purpose of this exercise, I have filtered down to capture the Adjusted Close value of the stocks that we are studying."
},
{
"code": null,
"e": 4517,
"s": 4158,
"text": "tickers = ['BSX','AES','BRK-B','SEE','QQQ','SPY']thelen = len(tickers)price_data = []for ticker in range(thelen):prices = web.DataReader(tickers[ticker], start='2015-01-01', end = '2020-06-06', data_source='yahoo')price_data.append(prices.assign(ticker=ticker)[['Adj Close']])df_stocks = pd.concat(price_data, axis=1)df_stocks.columns=tickersdf_stocks.head()"
},
{
"code": null,
"e": 4875,
"s": 4517,
"text": "Check if any values captured are ‘NaN’. Of less importance will be zero values. In case, there are NaN values — good practice will be to either consider a different time series or fill in the data with the average price of D-1, D+1. In case of a large void I would prefer not considering and deleting the time series data rather than inserting a zero value."
},
{
"code": null,
"e": 4997,
"s": 4875,
"text": "#Checking if any NaN values in the datanullin_df = pd.DataFrame(df_stocks,columns=tickers)print(nullin_df.isnull().sum())"
},
{
"code": null,
"e": 5013,
"s": 4997,
"text": "3. Calculations"
},
{
"code": null,
"e": 5176,
"s": 5013,
"text": "We will move ahead with the calculations for the optimization of the portfolio. Start with capturing the expected return and the variance of the portfolio chosen."
},
{
"code": null,
"e": 5320,
"s": 5176,
"text": "#Annualized Returnmu = expected_returns.mean_historical_return(df_stocks)#Sample Variance of PortfolioSigma = risk_models.sample_cov(df_stocks)"
},
{
"code": null,
"e": 5450,
"s": 5320,
"text": "Proceed by computing and storing the values for a portfolio weight with maximum Sharpe ratio and minimum volatility respectively."
},
{
"code": null,
"e": 5748,
"s": 5450,
"text": "#Max Sharpe Ratio - Tangent to the EFef = EfficientFrontier(mu, Sigma, weight_bounds=(-1,1)) #weight bounds in negative allows shorting of stockssharpe_pfolio=ef.max_sharpe() #May use add objective to ensure minimum zero weighting to individual stockssharpe_pwt=ef.clean_weights()print(sharpe_pwt)"
},
{
"code": null,
"e": 6069,
"s": 5748,
"text": "This will provide you the weight of different holdings. In case you want to minimize ‘zero’ holding or weight feel free to use L2 regression. Additionally, the weight_bounds have been set from -1 to 1 for allowing computation of ‘shorting’ stocks. The same exercise will be undertaken for the minimum variance portfolio."
},
{
"code": null,
"e": 6140,
"s": 6069,
"text": "4. Plotting the Efficient Frontier and Optimizing Portfolio Allocation"
},
{
"code": null,
"e": 6435,
"s": 6140,
"text": "The final step is the plot the efficient frontier for visual purposes, and calculate the asset allocation (i.e. no of shares to purchase or short) for a given dollar amount of a portfolio. For the purpose of this exercise, I have considered $10,000 — the default starting value on investopedia."
},
{
"code": null,
"e": 6937,
"s": 6435,
"text": "latest_prices = discrete_allocation.get_latest_prices(df_stocks)# Allocate Portfolio Value in $ as required to show number of shares/stocks to buy, also bounds for shorting will affect allocation#Min Volatility Portfolio Allocation $10000allocation_minv, rem_minv = discrete_allocation.DiscreteAllocation(minvol_pwt, latest_prices, total_portfolio_value=10000).lp_portfolio()print(allocation_minv)print(\"Leftover Fund value in$ after building minimum volatility portfolio is ${:.2f}\".format(rem_minv))"
},
{
"code": null,
"e": 7002,
"s": 6937,
"text": "This will provide you with the optimized portfolio as seen below"
},
{
"code": null,
"e": 7084,
"s": 7002,
"text": "The same can be done for calculating the portfolio with the maximum Sharpe ratio."
},
{
"code": null,
"e": 7357,
"s": 7084,
"text": "Investing is said to be part art part science. Python and its libraries allow us to automate optimization and save valuable time in the process of doing so. However, it must be noted that these techniques in isolation are unlikely to be the best way to approach investing."
},
{
"code": null,
"e": 7736,
"s": 7357,
"text": "Moving ahead, I will post about how we can choose stocks to replicate an index fund via machine learning to build our portfolio and many other functions which Python can assist us with. Finally, I have also created a program to calculate potential losses or variations in share prices using monte carlo simulations. This tool may be used in tandem with this portfolio optimizer."
},
{
"code": null,
"e": 7759,
"s": 7736,
"text": "towardsdatascience.com"
}
] |
Google Guice - Overview
|
Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google.
Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −
public class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
}
Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation.
Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below:
public class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
/*
* Bind SpellChecker binding to WinWordSpellChecker implementation
* whenever spellChecker dependency is used.
*/
bind(SpellChecker.class).to(WinWordSpellChecker.class);
}
}
The Module is the core building block for an Injector which is Guice's object-graph builder. First step is to create an injector and then we can use the injector to get the objects.
public static void main(String[] args) {
/*
* Guice.createInjector() takes Modules, and returns a new Injector
* instance. This method is to be called once during application startup.
*/
Injector injector = Guice.createInjector(new TextEditorModule());
/*
* Build object using injector
*/
TextEditor textEditor = injector.getInstance(TextEditor.class);
}
In above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object.
27 Lectures
1.5 hours
Lemuel Ogbunude
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2239,
"s": 2102,
"text": "Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google."
},
{
"code": null,
"e": 2739,
"s": 2239,
"text": "Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent."
},
{
"code": null,
"e": 2897,
"s": 2739,
"text": "Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −"
},
{
"code": null,
"e": 3038,
"s": 2897,
"text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n public TextEditor() {\n spellChecker = new SpellChecker();\n }\n}"
},
{
"code": null,
"e": 3207,
"s": 3038,
"text": "What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −"
},
{
"code": null,
"e": 3383,
"s": 3207,
"text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n}"
},
{
"code": null,
"e": 3588,
"s": 3383,
"text": "Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation.\n"
},
{
"code": null,
"e": 3810,
"s": 3588,
"text": "Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below:"
},
{
"code": null,
"e": 4121,
"s": 3810,
"text": "public class TextEditorModule extends AbstractModule {\n @Override \n protected void configure() {\n /*\n * Bind SpellChecker binding to WinWordSpellChecker implementation \n * whenever spellChecker dependency is used.\n */\n bind(SpellChecker.class).to(WinWordSpellChecker.class);\n }\n}"
},
{
"code": null,
"e": 4303,
"s": 4121,
"text": "The Module is the core building block for an Injector which is Guice's object-graph builder. First step is to create an injector and then we can use the injector to get the objects."
},
{
"code": null,
"e": 4688,
"s": 4303,
"text": "public static void main(String[] args) {\n /*\n * Guice.createInjector() takes Modules, and returns a new Injector\n * instance. This method is to be called once during application startup.\n */\n Injector injector = Guice.createInjector(new TextEditorModule());\n /*\n * Build object using injector\n */\n TextEditor textEditor = injector.getInstance(TextEditor.class); \n}"
},
{
"code": null,
"e": 4852,
"s": 4688,
"text": "In above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object."
},
{
"code": null,
"e": 4887,
"s": 4852,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4904,
"s": 4887,
"text": " Lemuel Ogbunude"
},
{
"code": null,
"e": 4911,
"s": 4904,
"text": " Print"
},
{
"code": null,
"e": 4922,
"s": 4911,
"text": " Add Notes"
}
] |
sciPy stats.binned_statistic() function | Python - GeeksforGeeks
|
18 Feb, 2019
stats.binned_statistic(x, values, statistic='mean', bins=10, range=None) function computes the binned statistics value for the given data (array elements).It works similar to histogram function. As histogram function makes bins and counts the no. of points in each bin; this function computes the sum, mean, median, count or other statistics of the values for each bin.
Parameters :arr : [array_like]input array to be binned.values : [array_like]on which stats to be calculated.statistics : Statistics to compute {mean, count, median, sum, function}. Default is mean.bin : [int or scalars]If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges.range : (float, float) Lower and upper range of the bins and if not provided, range is from x.max() to x.min().
Results : Statistics value for each bin; bin edges; bin number.
Code #1 :
# stats.binned_statistic() method import numpy as npfrom scipy import stats # 1D arrayarr = [20, 2, 7, 1, 34]print("\narr : \n", arr) # median print("\nbinned_statistic for median : \n", stats.binned_statistic( arr, np.arange(5), statistic ='median', bins = 4))
Output :
arr :
[20, 2, 7, 1, 34]
binned_statistic for median :
BinnedStatisticResult(statistic=array([ 2., nan, 0., 4.]),
bin_edges=array([ 1., 9.25, 17.5, 25.75, 34. ]),
binnumber=array([3, 1, 1, 1, 4], dtype=int64))
Code #2 :
# stats.binned_statistic() method import numpy as npfrom scipy import stats # mean arr = [20, 2, 7, 1, 34]print("\nbinned_statistic for mean : \n", stats.binned_statistic( arr, np.arange(5), statistic ='mean', bins = 2))
Output :
binned_statistic for mean :
BinnedStatisticResult(statistic=array([2., 2.]),
bin_edges=array([ 1., 17.5, 34. ]),
binnumber=array([2, 1, 1, 1, 2], dtype=int64))
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24298,
"s": 24270,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 24668,
"s": 24298,
"text": "stats.binned_statistic(x, values, statistic='mean', bins=10, range=None) function computes the binned statistics value for the given data (array elements).It works similar to histogram function. As histogram function makes bins and counts the no. of points in each bin; this function computes the sum, mean, median, count or other statistics of the values for each bin."
},
{
"code": null,
"e": 25145,
"s": 24668,
"text": "Parameters :arr : [array_like]input array to be binned.values : [array_like]on which stats to be calculated.statistics : Statistics to compute {mean, count, median, sum, function}. Default is mean.bin : [int or scalars]If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges.range : (float, float) Lower and upper range of the bins and if not provided, range is from x.max() to x.min()."
},
{
"code": null,
"e": 25209,
"s": 25145,
"text": "Results : Statistics value for each bin; bin edges; bin number."
},
{
"code": null,
"e": 25219,
"s": 25209,
"text": "Code #1 :"
},
{
"code": "# stats.binned_statistic() method import numpy as npfrom scipy import stats # 1D arrayarr = [20, 2, 7, 1, 34]print(\"\\narr : \\n\", arr) # median print(\"\\nbinned_statistic for median : \\n\", stats.binned_statistic( arr, np.arange(5), statistic ='median', bins = 4)) ",
"e": 25496,
"s": 25219,
"text": null
},
{
"code": null,
"e": 25505,
"s": 25496,
"text": "Output :"
},
{
"code": null,
"e": 25726,
"s": 25505,
"text": "arr : \n [20, 2, 7, 1, 34]\n\nbinned_statistic for median : \n BinnedStatisticResult(statistic=array([ 2., nan, 0., 4.]), \nbin_edges=array([ 1., 9.25, 17.5, 25.75, 34. ]), \nbinnumber=array([3, 1, 1, 1, 4], dtype=int64))\n"
},
{
"code": null,
"e": 25737,
"s": 25726,
"text": " Code #2 :"
},
{
"code": "# stats.binned_statistic() method import numpy as npfrom scipy import stats # mean arr = [20, 2, 7, 1, 34]print(\"\\nbinned_statistic for mean : \\n\", stats.binned_statistic( arr, np.arange(5), statistic ='mean', bins = 2)) ",
"e": 25968,
"s": 25737,
"text": null
},
{
"code": null,
"e": 25977,
"s": 25968,
"text": "Output :"
},
{
"code": null,
"e": 26141,
"s": 25977,
"text": "binned_statistic for mean : \n BinnedStatisticResult(statistic=array([2., 2.]), \nbin_edges=array([ 1., 17.5, 34. ]), \nbinnumber=array([2, 1, 1, 1, 2], dtype=int64))"
},
{
"code": null,
"e": 26170,
"s": 26141,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26183,
"s": 26170,
"text": "Python-scipy"
},
{
"code": null,
"e": 26190,
"s": 26183,
"text": "Python"
},
{
"code": null,
"e": 26288,
"s": 26190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26297,
"s": 26288,
"text": "Comments"
},
{
"code": null,
"e": 26310,
"s": 26297,
"text": "Old Comments"
},
{
"code": null,
"e": 26328,
"s": 26310,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26363,
"s": 26328,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26385,
"s": 26363,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26417,
"s": 26385,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26447,
"s": 26417,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26489,
"s": 26447,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26515,
"s": 26489,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26552,
"s": 26515,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26595,
"s": 26552,
"text": "Python program to convert a list to string"
}
] |
Implement Stack using Linked List | Practice | GeeksforGeeks
|
Let's give it a try! You have a linked list and you have to implement the functionalities push and pop of stack using this given linked list. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack.
Example 1:
Input:
push(2)
push(3)
pop()
push(4)
pop()
Output: 3 4
Explanation:
push(2) the stack will be {2}
push(3) the stack will be {2 3}
pop() poped element will be 3,
the stack will be {2}
push(4) the stack will be {2 4}
pop() poped element will be 4
Example 2:
Input:
pop()
push(4)
push(5)
pop()
Output: -1 5
Your Task: You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.
Expected Time Complexity: O(1) for both push() and pop().
Expected Auxiliary Space: O(1) for both push() and pop().
Constraints:
1 <= Q <= 100
1 <= x <= 100
0
nityabhanu5 hours ago
EASY CPP SOLUTIONNote(Hint): The top node of stack is acting like the header node of a linked list
CODE:
void MyStack ::push(int x) { StackNode *s=new StackNode(x); s->next=top; top=s;}
//Function to remove an item from top of the stack.int MyStack ::pop() { if(!top) { return -1; } int data=top->data; top=top->next; return data;}
0
madhukartemba2 weeks ago
JAVA SOLUTION:
class MyStack
{
StackNode top = null;
//Function to push an integer into the stack.
void push(int a)
{
StackNode node = new StackNode(a);
node.next = top;
top = node;
}
//Function to remove an item from top of the stack.
int pop()
{
if(top==null) return -1;
StackNode new_top = top.next;
int data = top.data;
//Garbage collector in Java will take care of it.
top.next = null;
top = null;
top = new_top;
return data;
}
}
+1
nevilvas3 weeks ago
class Node:
def __init__(self,data):
self.data = data
self.next = None
class MyStack:
def __init__(self):
self.top = None
#Function to push an integer into the stack.
def push(self, data):
temp = Node(data)
temp.next = self.top
self.top = temp
#Function to remove an item from top of the stack.
def pop(self):
# Add code here
if self.top == None:
return -1
ans = self.top.data
self.top = self.top.next
return ans
0
sangrambachu4 weeks ago
class MyStack
{
StackNode top;
//Function to push an integer into the stack.
void push(int a)
{
// Add your code here
StackNode temp = new StackNode(a);
temp.next = top;
top = temp;
}
//Function to remove an item from top of the stack.
int pop()
{
// Add your code here
if(top == null) {
return -1;
}
int a = top.data;
top = top.next;
return a;
}
}
0
tarunkanade1 month ago
0.5/1.6
//Function to push an integer into the stack.
void push(int a)
{
// Add your code here
StackNode temp = new StackNode(a);
temp.next = top;
top = temp;
}
//Function to remove an item from top of the stack.
int pop()
{
// Add your code here
if(top == null){
return -1;
}
int res = top.data;
top = top.next;
return res;
}
0
swastikp17111 month ago
Simple Stack Implementation Using LinkedList in Java
class MyStack
{
StackNode top;
MyStack(){
top=null;
}
//Function to push an integer into the stack.
void push(int a)
{
StackNode newNode=new StackNode(a);
newNode.next=top;
top=newNode;
}
//Function to remove an item from top of the stack.
int pop()
{
// condition for Empty Stack
if(top==null) return -1;
// When Stack is not Empty
int ans=top.data;
top=top.next;
return ans;
}
}
0
atif836141 month ago
main opreation in stack :
// this is push opreation:
void push(int a){
StackNode newnode=new StackNode(a);
newnode.next=top;
top = newnode;
}
// pop opreation :
int pop(){
int tempdata;
if(top==null){
return -1;
}
else
tempdata=top.data;
top = top.next;
return tempdata;
}
0
akasharma9121 month ago
void MyStack ::push(int x) { StackNode * t = new StackNode(x); t->next=top; top=t;}
//Function to remove an item from top of the stack.int MyStack ::pop() { if (top==NULL) { return -1; } else{ int element =top->data; top=top->next; return element; }}
0
yashkotalwar101 month ago
// Java
void push(int a) { StackNode stackNode = new StackNode(a); stackNode.next = top; top = stackNode; } int pop() { if (top == null){ return -1; } int temp = top.data; top = top.next; return temp; }
0
sayantankuila1 month ago
C solution
void push(struct Stack* stack, int item){ stack->top++; stack->array[stack->top] = item; }
// Function to remove an item from stack. It decreases top by 1int pop(struct Stack* stack){ if(stack->top == -1){ return -1; } else{ int v= stack->array[stack->top]; stack->top--; return v; } }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 521,
"s": 238,
"text": "Let's give it a try! You have a linked list and you have to implement the functionalities push and pop of stack using this given linked list. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. "
},
{
"code": null,
"e": 532,
"s": 521,
"text": "Example 1:"
},
{
"code": null,
"e": 810,
"s": 532,
"text": "Input: \npush(2)\npush(3)\npop()\npush(4) \npop()\nOutput: 3 4\nExplanation: \npush(2) the stack will be {2}\npush(3) the stack will be {2 3}\npop() poped element will be 3,\n the stack will be {2}\npush(4) the stack will be {2 4}\npop() poped element will be 4"
},
{
"code": null,
"e": 821,
"s": 810,
"text": "Example 2:"
},
{
"code": null,
"e": 870,
"s": 821,
"text": "Input: \npop()\npush(4)\npush(5)\npop()\nOutput: -1 5"
},
{
"code": null,
"e": 1325,
"s": 870,
"text": "Your Task: You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.\n\nExpected Time Complexity: O(1) for both push() and pop().\nExpected Auxiliary Space: O(1) for both push() and pop().\n\nConstraints:\n1 <= Q <= 100\n1 <= x <= 100"
},
{
"code": null,
"e": 1327,
"s": 1325,
"text": "0"
},
{
"code": null,
"e": 1349,
"s": 1327,
"text": "nityabhanu5 hours ago"
},
{
"code": null,
"e": 1449,
"s": 1349,
"text": "EASY CPP SOLUTIONNote(Hint): The top node of stack is acting like the header node of a linked list "
},
{
"code": null,
"e": 1455,
"s": 1449,
"text": "CODE:"
},
{
"code": null,
"e": 1539,
"s": 1455,
"text": "void MyStack ::push(int x) { StackNode *s=new StackNode(x); s->next=top; top=s;}"
},
{
"code": null,
"e": 1696,
"s": 1539,
"text": "//Function to remove an item from top of the stack.int MyStack ::pop() { if(!top) { return -1; } int data=top->data; top=top->next; return data;}"
},
{
"code": null,
"e": 1698,
"s": 1696,
"text": "0"
},
{
"code": null,
"e": 1723,
"s": 1698,
"text": "madhukartemba2 weeks ago"
},
{
"code": null,
"e": 1738,
"s": 1723,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 2349,
"s": 1738,
"text": "class MyStack \n{\n StackNode top = null;\n \n //Function to push an integer into the stack.\n void push(int a) \n {\n StackNode node = new StackNode(a);\n node.next = top;\n top = node;\n }\n \n //Function to remove an item from top of the stack.\n int pop() \n {\n if(top==null) return -1;\n \n StackNode new_top = top.next;\n \n int data = top.data;\n \n //Garbage collector in Java will take care of it.\n top.next = null;\n top = null;\n \n top = new_top;\n \n return data;\n \n }\n}"
},
{
"code": null,
"e": 2352,
"s": 2349,
"text": "+1"
},
{
"code": null,
"e": 2372,
"s": 2352,
"text": "nevilvas3 weeks ago"
},
{
"code": null,
"e": 2938,
"s": 2372,
"text": "class Node: \n def __init__(self,data):\n self.data = data\n self.next = None\n \n\n\n\nclass MyStack:\n def __init__(self):\n self.top = None\n #Function to push an integer into the stack.\n def push(self, data):\n temp = Node(data)\n temp.next = self.top\n self.top = temp\n\n \n\n\n #Function to remove an item from top of the stack.\n def pop(self):\n\n # Add code here\n if self.top == None:\n return -1\n ans = self.top.data\n self.top = self.top.next\n return ans"
},
{
"code": null,
"e": 2940,
"s": 2938,
"text": "0"
},
{
"code": null,
"e": 2964,
"s": 2940,
"text": "sangrambachu4 weeks ago"
},
{
"code": null,
"e": 3463,
"s": 2964,
"text": "class MyStack \n{\n StackNode top;\n \n //Function to push an integer into the stack.\n void push(int a) \n {\n // Add your code here\n StackNode temp = new StackNode(a);\n temp.next = top;\n top = temp;\n }\n \n //Function to remove an item from top of the stack.\n int pop() \n {\n // Add your code here\n if(top == null) {\n return -1;\n }\n \n int a = top.data;\n top = top.next;\n return a;\n }\n}"
},
{
"code": null,
"e": 3465,
"s": 3463,
"text": "0"
},
{
"code": null,
"e": 3488,
"s": 3465,
"text": "tarunkanade1 month ago"
},
{
"code": null,
"e": 3496,
"s": 3488,
"text": "0.5/1.6"
},
{
"code": null,
"e": 3969,
"s": 3496,
"text": "//Function to push an integer into the stack.\n void push(int a) \n {\n // Add your code here\n StackNode temp = new StackNode(a);\n temp.next = top;\n top = temp;\n }\n \n //Function to remove an item from top of the stack.\n int pop() \n {\n // Add your code here\n if(top == null){\n return -1;\n }\n \n int res = top.data;\n \n top = top.next;\n \n return res;\n }"
},
{
"code": null,
"e": 3971,
"s": 3969,
"text": "0"
},
{
"code": null,
"e": 3995,
"s": 3971,
"text": "swastikp17111 month ago"
},
{
"code": null,
"e": 4049,
"s": 3995,
"text": "Simple Stack Implementation Using LinkedList in Java "
},
{
"code": null,
"e": 4582,
"s": 4049,
"text": "class MyStack \n{\n StackNode top;\n \n MyStack(){\n top=null;\n }\n //Function to push an integer into the stack.\n void push(int a) \n {\n StackNode newNode=new StackNode(a);\n newNode.next=top;\n top=newNode;\n }\n \n //Function to remove an item from top of the stack.\n int pop() \n {\n \t// condition for Empty Stack\n if(top==null) return -1;\n \n // When Stack is not Empty\n int ans=top.data;\n top=top.next;\n \n return ans;\n }\n}"
},
{
"code": null,
"e": 4586,
"s": 4584,
"text": "0"
},
{
"code": null,
"e": 4607,
"s": 4586,
"text": "atif836141 month ago"
},
{
"code": null,
"e": 4633,
"s": 4607,
"text": "main opreation in stack :"
},
{
"code": null,
"e": 4660,
"s": 4633,
"text": "// this is push opreation:"
},
{
"code": null,
"e": 4678,
"s": 4660,
"text": "void push(int a){"
},
{
"code": null,
"e": 4714,
"s": 4678,
"text": "StackNode newnode=new StackNode(a);"
},
{
"code": null,
"e": 4732,
"s": 4714,
"text": "newnode.next=top;"
},
{
"code": null,
"e": 4747,
"s": 4732,
"text": "top = newnode;"
},
{
"code": null,
"e": 4749,
"s": 4747,
"text": "}"
},
{
"code": null,
"e": 4771,
"s": 4749,
"text": "// pop opreation :"
},
{
"code": null,
"e": 4782,
"s": 4771,
"text": "int pop(){"
},
{
"code": null,
"e": 4796,
"s": 4782,
"text": "int tempdata;"
},
{
"code": null,
"e": 4811,
"s": 4796,
"text": "if(top==null){"
},
{
"code": null,
"e": 4822,
"s": 4811,
"text": "return -1;"
},
{
"code": null,
"e": 4824,
"s": 4822,
"text": "}"
},
{
"code": null,
"e": 4829,
"s": 4824,
"text": "else"
},
{
"code": null,
"e": 4848,
"s": 4829,
"text": "tempdata=top.data;"
},
{
"code": null,
"e": 4864,
"s": 4848,
"text": "top = top.next;"
},
{
"code": null,
"e": 4881,
"s": 4864,
"text": "return tempdata;"
},
{
"code": null,
"e": 4883,
"s": 4881,
"text": "}"
},
{
"code": null,
"e": 4887,
"s": 4885,
"text": "0"
},
{
"code": null,
"e": 4911,
"s": 4887,
"text": "akasharma9121 month ago"
},
{
"code": null,
"e": 5001,
"s": 4911,
"text": "void MyStack ::push(int x) { StackNode * t = new StackNode(x); t->next=top; top=t;}"
},
{
"code": null,
"e": 5203,
"s": 5001,
"text": "//Function to remove an item from top of the stack.int MyStack ::pop() { if (top==NULL) { return -1; } else{ int element =top->data; top=top->next; return element; }} "
},
{
"code": null,
"e": 5205,
"s": 5203,
"text": "0"
},
{
"code": null,
"e": 5231,
"s": 5205,
"text": "yashkotalwar101 month ago"
},
{
"code": null,
"e": 5239,
"s": 5231,
"text": "// Java"
},
{
"code": null,
"e": 5504,
"s": 5239,
"text": "void push(int a) { StackNode stackNode = new StackNode(a); stackNode.next = top; top = stackNode; } int pop() { if (top == null){ return -1; } int temp = top.data; top = top.next; return temp; }"
},
{
"code": null,
"e": 5506,
"s": 5504,
"text": "0"
},
{
"code": null,
"e": 5531,
"s": 5506,
"text": "sayantankuila1 month ago"
},
{
"code": null,
"e": 5542,
"s": 5531,
"text": "C solution"
},
{
"code": null,
"e": 5639,
"s": 5542,
"text": "void push(struct Stack* stack, int item){ stack->top++; stack->array[stack->top] = item; }"
},
{
"code": null,
"e": 5876,
"s": 5639,
"text": "// Function to remove an item from stack. It decreases top by 1int pop(struct Stack* stack){ if(stack->top == -1){ return -1; } else{ int v= stack->array[stack->top]; stack->top--; return v; } }"
},
{
"code": null,
"e": 6022,
"s": 5876,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6058,
"s": 6022,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6068,
"s": 6058,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6078,
"s": 6068,
"text": "\nContest\n"
},
{
"code": null,
"e": 6141,
"s": 6078,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6289,
"s": 6141,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6497,
"s": 6289,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6603,
"s": 6497,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Reverse Geocoding in R. Free Without the Google or Bing API | by Aisha Sikder, PhD | Towards Data Science
|
As I continue to work on my dissertation, I have come across a few glitches in executing what should be easy scripts from various packages in R and Python. This weekend, I gave myself the task to reverse geocode ~1 million latitude and longitude coordinates. I found a great package in R called revgeo and thought this would be pretty easy to implement. I would just have to specify the provider and the API key. Google and Bing limit the number of free queries per day so it was not a viable option, but Photon does not! The only caveat is that detailed locations like address names are not always available. Below is a sample of how to utilize the revgeo package:
library(revgeo)revgeo(longitude=-77.0229529, latitude=38.89283435, provider = 'photon', output=’frame’)
So where is the problem? Well, as stated on Photons webpage:
You can use the API for your project, but please be fair — extensive usage will be throttled. We do not guarantee for the availability and usage might be subject of change in the future.
I am not certain how many queries it takes before the Photon API slows down but it is important to be mindful in how many requests we send to their server. I decided to start with 500,000 coordinates to reverse geocode but this didn’t work well. I ran the code and walked away for some time and when I came back I saw the throttling had begun so I needed to tweak the code. In addition, R was throwing an error cannot allocate vector of size x.x Gb, which means that my available RAM has been exhausted.
At this point I had two issues: 1) Throttling and 2) Memory Allocation. For issue 1, I needed to incorporate sleep times in the code and work with smaller subsets of my already subsetted dataframe. For issue 2, I found a thread on stackoverflow that had useful advice:
stackoverflow.com
A solution that helped me was running memory.limit(size = _ _ _ _ _ _). In addition I used the rm() command to remove any dataframes I no longer needed within my code and the gc() command for garbage collection. Shown below, I loaded in the dataframe with ~1 million coordinates called main. I subsetted the data to only 100,000 rows. As you will see later, I subset the data even further in a while loop to avoid memory allocation issues.
library(revgeo)# the dataframe called 'main' is where the 1 million coordinate points reside.main <- readRDS("main.rds"))main_sub <- main[0:100000,] # Working with a smaller initial subsetrm(main)gc()
Below is the full code. The script incorporates other actions not relating to this posts subject matter but I wanted to publish it here so that you may see the whole picture and hopefully take away some helpful tips in reverse geocoding.
# Step 1: Create a blank dataframe to store results.data_all = data.frame()start <- Sys.time()# Step 2: Create a while loop to have the function running until the # dataframe with 100,000 rows is empty.while (nrow(main_sub)>0) {# Step 3: Subset the data even further so that you are sending only # a small portion of requests to the Photon server. main_sub_t <- main_sub[1:200,]# Step 4: Extracting the lat/longs from the subsetted data from# the previous step (Step 3). latlong <- main_sub_t %>% select(latitude, longitude) %>% unique() %>% mutate(index=row_number()) # Step 5: Incorporate the revgeo package here. I left_joined the # output with the latlong dataframe from the previous step to add # the latitude/longitude information with the reverse geocoded data.cities <- revgeo(latlong$longitude, latlong$latitude, provider = 'photon', output = 'frame')) %>% mutate(index = row_number(),country = as.character(country)) %>% filter(country == 'United States of America') %>% mutate(location = paste(city, state, sep = ", ")) %>% select(index, location) %>% left_join(latlong, by="index") %>% select(-index) # Removing the latlong dataframe because I no longer need it. This # helps with reducing memory in my global environment.rm(latlong) # Step 6: Adding the information from the cities dataframe to # main_sub_t dataframe (from Step 3). data_new <- main_sub_t %>% left_join(cities, by=c("latitude","longitude")) %>% select(X, text, location, latitude, longitude) # Step 7: Adding data_new into the empty data_all dataframe where # all subsetted reverse geocoded data will be combined. data_all <- rbind(data_all,data_new) %>% na.omit() # Step 8: Remove the rows that were used in the first loop from the # main_sub frame so the next 200 rows can be read into the while # loop. main_sub <- anti_join(main_sub, main_sub_t, by=c("X")) print(nrow(main_sub)) # Remove dataframes that are not needed before the while loop closes # to free up space. rm(data_sub_t) rm(data_new) rm(latlong_1) rm(cities) print('Sleeping for 10 seconds') Sys.sleep(10) }end <- Sys.time()
After implementing this code, it took about 4 hours to reverse geocode 100,000 coordinates. In my opinion, that’s not a viable option if I have 1 million coordinates to convert. I may have to find another method to achieve my goal but I figured this would be helpful to some of you who have smaller datasets.
Thanks for reading and happy coding!
|
[
{
"code": null,
"e": 837,
"s": 171,
"text": "As I continue to work on my dissertation, I have come across a few glitches in executing what should be easy scripts from various packages in R and Python. This weekend, I gave myself the task to reverse geocode ~1 million latitude and longitude coordinates. I found a great package in R called revgeo and thought this would be pretty easy to implement. I would just have to specify the provider and the API key. Google and Bing limit the number of free queries per day so it was not a viable option, but Photon does not! The only caveat is that detailed locations like address names are not always available. Below is a sample of how to utilize the revgeo package:"
},
{
"code": null,
"e": 941,
"s": 837,
"text": "library(revgeo)revgeo(longitude=-77.0229529, latitude=38.89283435, provider = 'photon', output=’frame’)"
},
{
"code": null,
"e": 1002,
"s": 941,
"text": "So where is the problem? Well, as stated on Photons webpage:"
},
{
"code": null,
"e": 1189,
"s": 1002,
"text": "You can use the API for your project, but please be fair — extensive usage will be throttled. We do not guarantee for the availability and usage might be subject of change in the future."
},
{
"code": null,
"e": 1693,
"s": 1189,
"text": "I am not certain how many queries it takes before the Photon API slows down but it is important to be mindful in how many requests we send to their server. I decided to start with 500,000 coordinates to reverse geocode but this didn’t work well. I ran the code and walked away for some time and when I came back I saw the throttling had begun so I needed to tweak the code. In addition, R was throwing an error cannot allocate vector of size x.x Gb, which means that my available RAM has been exhausted."
},
{
"code": null,
"e": 1962,
"s": 1693,
"text": "At this point I had two issues: 1) Throttling and 2) Memory Allocation. For issue 1, I needed to incorporate sleep times in the code and work with smaller subsets of my already subsetted dataframe. For issue 2, I found a thread on stackoverflow that had useful advice:"
},
{
"code": null,
"e": 1980,
"s": 1962,
"text": "stackoverflow.com"
},
{
"code": null,
"e": 2420,
"s": 1980,
"text": "A solution that helped me was running memory.limit(size = _ _ _ _ _ _). In addition I used the rm() command to remove any dataframes I no longer needed within my code and the gc() command for garbage collection. Shown below, I loaded in the dataframe with ~1 million coordinates called main. I subsetted the data to only 100,000 rows. As you will see later, I subset the data even further in a while loop to avoid memory allocation issues."
},
{
"code": null,
"e": 2621,
"s": 2420,
"text": "library(revgeo)# the dataframe called 'main' is where the 1 million coordinate points reside.main <- readRDS(\"main.rds\"))main_sub <- main[0:100000,] # Working with a smaller initial subsetrm(main)gc()"
},
{
"code": null,
"e": 2859,
"s": 2621,
"text": "Below is the full code. The script incorporates other actions not relating to this posts subject matter but I wanted to publish it here so that you may see the whole picture and hopefully take away some helpful tips in reverse geocoding."
},
{
"code": null,
"e": 5006,
"s": 2859,
"text": "# Step 1: Create a blank dataframe to store results.data_all = data.frame()start <- Sys.time()# Step 2: Create a while loop to have the function running until the # dataframe with 100,000 rows is empty.while (nrow(main_sub)>0) {# Step 3: Subset the data even further so that you are sending only # a small portion of requests to the Photon server. main_sub_t <- main_sub[1:200,]# Step 4: Extracting the lat/longs from the subsetted data from# the previous step (Step 3). latlong <- main_sub_t %>% select(latitude, longitude) %>% unique() %>% mutate(index=row_number()) # Step 5: Incorporate the revgeo package here. I left_joined the # output with the latlong dataframe from the previous step to add # the latitude/longitude information with the reverse geocoded data.cities <- revgeo(latlong$longitude, latlong$latitude, provider = 'photon', output = 'frame')) %>% mutate(index = row_number(),country = as.character(country)) %>% filter(country == 'United States of America') %>% mutate(location = paste(city, state, sep = \", \")) %>% select(index, location) %>% left_join(latlong, by=\"index\") %>% select(-index) # Removing the latlong dataframe because I no longer need it. This # helps with reducing memory in my global environment.rm(latlong) # Step 6: Adding the information from the cities dataframe to # main_sub_t dataframe (from Step 3). data_new <- main_sub_t %>% left_join(cities, by=c(\"latitude\",\"longitude\")) %>% select(X, text, location, latitude, longitude) # Step 7: Adding data_new into the empty data_all dataframe where # all subsetted reverse geocoded data will be combined. data_all <- rbind(data_all,data_new) %>% na.omit() # Step 8: Remove the rows that were used in the first loop from the # main_sub frame so the next 200 rows can be read into the while # loop. main_sub <- anti_join(main_sub, main_sub_t, by=c(\"X\")) print(nrow(main_sub)) # Remove dataframes that are not needed before the while loop closes # to free up space. rm(data_sub_t) rm(data_new) rm(latlong_1) rm(cities) print('Sleeping for 10 seconds') Sys.sleep(10) }end <- Sys.time()"
},
{
"code": null,
"e": 5315,
"s": 5006,
"text": "After implementing this code, it took about 4 hours to reverse geocode 100,000 coordinates. In my opinion, that’s not a viable option if I have 1 million coordinates to convert. I may have to find another method to achieve my goal but I figured this would be helpful to some of you who have smaller datasets."
}
] |
Your first user defined function in R | by Shruthi Geetha | Towards Data Science
|
You might be using R frequently for data processing and modelling, but do you want to try efficient user defined functions to make your work easy? Then this post is for you.
User defined functions need not be complex or difficult to build, but can make you very efficient if you are smart about where you use it. It can be small or big based on your needs. A user defined function can be used for any action to be performed in R.
Read on to know more about user defined functions — step by step. Once you have a basic algorithm & a cup of tea ready, let’s get started.
Identify different sections in your algorithm that needs to be repeated again. If there is a continuous chunk that is being repeated, you would need a single function, else you can use two functions separately. There is also a chance that you can use a user defined function within another user defined function. Sounds cool right!
Look for possibilities, identify the part that you would want to convert into a function. Now, let’s concentrate on just that section.
There will be an input and output for this section. Input will be a variable or multiple variables/datasets that you have. It could be read directly into R or could be a result of the code that you plan to write.
Identify and visualize how the input looks like. You can either code it out or use pen and paper.
Think about what you would want as an output of this function. Output of this function should be such that it can be easily plugged into the rest of the code or saved without further complex transformations.
You don’t have to worry much about the exact format of the output. You can figure that out on the way.
Figure out a rough algorithm as to how would you reach from the decided input to the desired output. If you are a beginner, don’t be lazy to draw a flow chart before you code (thank me later!). List down detailed steps, transformations and if you are comfortable with R, write down the in-build functions directly.
Now we can start coding. Yay! The basic syntax for user defined function is given below:
Function_name <- function(a,b,...){ ---- Function Body ---- }
where ‘a’ and ‘b’ are arguments.
And once you define a function, you can call it later as
Result <- Function_name(a,b)
Let me show you a small example. As discussed above, I am identifying that I need to convert addition of two numbers into a user defined function. I want my input to be the 2 numbers and output should be a sentence containing the 2 numbers and its summation. Flow chart will be as given below
Now we have to code it:
MyAddFunction <- function(a,b){ output = a + b result = paste0("Addition of ", a, " and ", b, " gives ", output) return(result)}
Try calling this function using different values for a and b as given below:
For a = 3 and b = 5,
MyAddFunction(3,5) gives result as “Addition of 3 and 5 gives 8”
Congratulations! You have written your first function.
Ready to take it further? It is always better to build a skeleton of the function as we did above and then build on it for further modifications or customization. This way, you can clearly check where you are going wrong.
Let’s say instead of 2 numbers, a user tries to insert a = “one”. Do you want to add error messages telling the user to use a numeric variable rather than a character?
To do this, we can further modify the same function.
Let’s see how my function will look like now:
MyAddFunction <- function(a,b){ if(all(is.numeric(a), is.numeric(b))){ output = a + b result = paste0("Addition of ", a, " and ", b, " gives ", output) }else{ result = "Please make sure that inputs are numeric" } return(result)}
Try calling this function using different values for a and b as given below:
Now for a = 3 and b = 5, the results will remain the same;
MyAddFunction(3,5) gives result as “Addition of 3 and 5 gives 8”
But for a = 4 and b = “two”,
MyAddFunction(4,”two”) gives result as “Please make sure that inputs are numeric”
Now that you have learnt how to build a basic user defined function in R, I hope you will be able to use it to make your code better. User defined functions can help achieve a lot of coding milestones like below:
Your code is now easy to understand by you and othersIt is now better structured and client readyUDF can help pin point algorithmic errorsIt leads to easy modification and code alterations in future
Your code is now easy to understand by you and others
It is now better structured and client ready
UDF can help pin point algorithmic errors
It leads to easy modification and code alterations in future
From now on with use of UDFs, hope you never feel lost while approaching yours or your peers code after a while!
Do you want to know how to make advanced user defined functions using loops or to call a user defined function inside another function? Check out my next post for more such interesting functions.
|
[
{
"code": null,
"e": 346,
"s": 172,
"text": "You might be using R frequently for data processing and modelling, but do you want to try efficient user defined functions to make your work easy? Then this post is for you."
},
{
"code": null,
"e": 602,
"s": 346,
"text": "User defined functions need not be complex or difficult to build, but can make you very efficient if you are smart about where you use it. It can be small or big based on your needs. A user defined function can be used for any action to be performed in R."
},
{
"code": null,
"e": 741,
"s": 602,
"text": "Read on to know more about user defined functions — step by step. Once you have a basic algorithm & a cup of tea ready, let’s get started."
},
{
"code": null,
"e": 1073,
"s": 741,
"text": "Identify different sections in your algorithm that needs to be repeated again. If there is a continuous chunk that is being repeated, you would need a single function, else you can use two functions separately. There is also a chance that you can use a user defined function within another user defined function. Sounds cool right!"
},
{
"code": null,
"e": 1208,
"s": 1073,
"text": "Look for possibilities, identify the part that you would want to convert into a function. Now, let’s concentrate on just that section."
},
{
"code": null,
"e": 1421,
"s": 1208,
"text": "There will be an input and output for this section. Input will be a variable or multiple variables/datasets that you have. It could be read directly into R or could be a result of the code that you plan to write."
},
{
"code": null,
"e": 1519,
"s": 1421,
"text": "Identify and visualize how the input looks like. You can either code it out or use pen and paper."
},
{
"code": null,
"e": 1727,
"s": 1519,
"text": "Think about what you would want as an output of this function. Output of this function should be such that it can be easily plugged into the rest of the code or saved without further complex transformations."
},
{
"code": null,
"e": 1830,
"s": 1727,
"text": "You don’t have to worry much about the exact format of the output. You can figure that out on the way."
},
{
"code": null,
"e": 2145,
"s": 1830,
"text": "Figure out a rough algorithm as to how would you reach from the decided input to the desired output. If you are a beginner, don’t be lazy to draw a flow chart before you code (thank me later!). List down detailed steps, transformations and if you are comfortable with R, write down the in-build functions directly."
},
{
"code": null,
"e": 2234,
"s": 2145,
"text": "Now we can start coding. Yay! The basic syntax for user defined function is given below:"
},
{
"code": null,
"e": 2300,
"s": 2234,
"text": "Function_name <- function(a,b,...){ ---- Function Body ---- }"
},
{
"code": null,
"e": 2333,
"s": 2300,
"text": "where ‘a’ and ‘b’ are arguments."
},
{
"code": null,
"e": 2390,
"s": 2333,
"text": "And once you define a function, you can call it later as"
},
{
"code": null,
"e": 2419,
"s": 2390,
"text": "Result <- Function_name(a,b)"
},
{
"code": null,
"e": 2712,
"s": 2419,
"text": "Let me show you a small example. As discussed above, I am identifying that I need to convert addition of two numbers into a user defined function. I want my input to be the 2 numbers and output should be a sentence containing the 2 numbers and its summation. Flow chart will be as given below"
},
{
"code": null,
"e": 2736,
"s": 2712,
"text": "Now we have to code it:"
},
{
"code": null,
"e": 2868,
"s": 2736,
"text": "MyAddFunction <- function(a,b){ output = a + b result = paste0(\"Addition of \", a, \" and \", b, \" gives \", output) return(result)}"
},
{
"code": null,
"e": 2945,
"s": 2868,
"text": "Try calling this function using different values for a and b as given below:"
},
{
"code": null,
"e": 2966,
"s": 2945,
"text": "For a = 3 and b = 5,"
},
{
"code": null,
"e": 3031,
"s": 2966,
"text": "MyAddFunction(3,5) gives result as “Addition of 3 and 5 gives 8”"
},
{
"code": null,
"e": 3086,
"s": 3031,
"text": "Congratulations! You have written your first function."
},
{
"code": null,
"e": 3308,
"s": 3086,
"text": "Ready to take it further? It is always better to build a skeleton of the function as we did above and then build on it for further modifications or customization. This way, you can clearly check where you are going wrong."
},
{
"code": null,
"e": 3476,
"s": 3308,
"text": "Let’s say instead of 2 numbers, a user tries to insert a = “one”. Do you want to add error messages telling the user to use a numeric variable rather than a character?"
},
{
"code": null,
"e": 3529,
"s": 3476,
"text": "To do this, we can further modify the same function."
},
{
"code": null,
"e": 3575,
"s": 3529,
"text": "Let’s see how my function will look like now:"
},
{
"code": null,
"e": 3817,
"s": 3575,
"text": "MyAddFunction <- function(a,b){ if(all(is.numeric(a), is.numeric(b))){ output = a + b result = paste0(\"Addition of \", a, \" and \", b, \" gives \", output) }else{ result = \"Please make sure that inputs are numeric\" } return(result)}"
},
{
"code": null,
"e": 3894,
"s": 3817,
"text": "Try calling this function using different values for a and b as given below:"
},
{
"code": null,
"e": 3953,
"s": 3894,
"text": "Now for a = 3 and b = 5, the results will remain the same;"
},
{
"code": null,
"e": 4018,
"s": 3953,
"text": "MyAddFunction(3,5) gives result as “Addition of 3 and 5 gives 8”"
},
{
"code": null,
"e": 4047,
"s": 4018,
"text": "But for a = 4 and b = “two”,"
},
{
"code": null,
"e": 4129,
"s": 4047,
"text": "MyAddFunction(4,”two”) gives result as “Please make sure that inputs are numeric”"
},
{
"code": null,
"e": 4342,
"s": 4129,
"text": "Now that you have learnt how to build a basic user defined function in R, I hope you will be able to use it to make your code better. User defined functions can help achieve a lot of coding milestones like below:"
},
{
"code": null,
"e": 4541,
"s": 4342,
"text": "Your code is now easy to understand by you and othersIt is now better structured and client readyUDF can help pin point algorithmic errorsIt leads to easy modification and code alterations in future"
},
{
"code": null,
"e": 4595,
"s": 4541,
"text": "Your code is now easy to understand by you and others"
},
{
"code": null,
"e": 4640,
"s": 4595,
"text": "It is now better structured and client ready"
},
{
"code": null,
"e": 4682,
"s": 4640,
"text": "UDF can help pin point algorithmic errors"
},
{
"code": null,
"e": 4743,
"s": 4682,
"text": "It leads to easy modification and code alterations in future"
},
{
"code": null,
"e": 4856,
"s": 4743,
"text": "From now on with use of UDFs, hope you never feel lost while approaching yours or your peers code after a while!"
}
] |
Python None Keyword - GeeksforGeeks
|
12 Nov, 2020
None is used to define a null value. It is not the same as an empty string, False, or a zero. It is a data type of the class NoneType object.
Assigning a value of None to a variable is one way to reset it to its original, empty state.
Example 1:
Python3
# we will check the type of Noneprint(type(None))
<class 'NoneType'>
Example 2:
Python3
# declaring a variable as Nonevar = None # checking it's valueif var is None: print("var has a value of None")else: print("var has a value")
var has a value of None
Note: If a function does not return anything, it returns None in python.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25671,
"s": 25643,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 25814,
"s": 25671,
"text": "None is used to define a null value. It is not the same as an empty string, False, or a zero. It is a data type of the class NoneType object. "
},
{
"code": null,
"e": 25907,
"s": 25814,
"text": "Assigning a value of None to a variable is one way to reset it to its original, empty state."
},
{
"code": null,
"e": 25918,
"s": 25907,
"text": "Example 1:"
},
{
"code": null,
"e": 25926,
"s": 25918,
"text": "Python3"
},
{
"code": "# we will check the type of Noneprint(type(None))",
"e": 25976,
"s": 25926,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25976,
"text": "<class 'NoneType'>\n"
},
{
"code": null,
"e": 26007,
"s": 25996,
"text": "Example 2:"
},
{
"code": null,
"e": 26015,
"s": 26007,
"text": "Python3"
},
{
"code": "# declaring a variable as Nonevar = None # checking it's valueif var is None: print(\"var has a value of None\")else: print(\"var has a value\")",
"e": 26163,
"s": 26015,
"text": null
},
{
"code": null,
"e": 26188,
"s": 26163,
"text": "var has a value of None\n"
},
{
"code": null,
"e": 26261,
"s": 26188,
"text": "Note: If a function does not return anything, it returns None in python."
},
{
"code": null,
"e": 26275,
"s": 26261,
"text": "python-basics"
},
{
"code": null,
"e": 26282,
"s": 26275,
"text": "Python"
},
{
"code": null,
"e": 26380,
"s": 26282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26412,
"s": 26380,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26454,
"s": 26412,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26496,
"s": 26454,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26552,
"s": 26496,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26579,
"s": 26552,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26610,
"s": 26579,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26639,
"s": 26610,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26661,
"s": 26639,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26697,
"s": 26661,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Implementation of Tic-Tac-Toe for 2 person game (User vs. User) - GeeksforGeeks
|
24 Sep, 2021
For 1-Person game (User vs. CPU), please refer Implementation of Tic-Tac-Toe game
Rules of the Game
The game is to be played between two people (in this program between HUMAN to HUMAN).
First the game will take the names of the two players as input.
One of the player chooses ‘O’ and the other ‘X’ to mark their respective cells.
There would be a game toss, which will decide which player will move first.
The game starts with one of the players and the game ends when one of the players has one whole row/ column/ diagonal filled with his/her respective character (‘O’ or ‘X’).
If the game is Tie then, A message is displayed “Game is Tie”.
Winning Strategy – An Interesting FactIf both the players play optimally then it is destined that you will never lose (“although the match can still be drawn”). It doesn’t matter whether you play first or second. In another way – “ Two expert players will always draw ”.Isn’t this interesting?
Below is the code for the Game:
C++
// C++ program to play Tic-Tac-Toe#include <bits/stdc++.h>using namespace std; // Length of the board#define SIDE 3 // Name fo the playersstring PLAYER1, PLAYER2; // Function to show the current// board statusvoid showBoard(char board[][SIDE]){ printf("\n\n"); printf("\t\t\t %c | %c | %c \n", board[0][0], board[0][1], board[0][2]); printf("\t\t\t------------\n"); printf("\t\t\t %c | %c | %c \n", board[1][0], board[1][1], board[1][2]); printf("\t\t\t------------\n"); printf("\t\t\t %c | %c | %c \n\n", board[2][0], board[2][1], board[2][2]); return;} // Function to show the instructionsvoid showInstructions(){ printf("\t\t\t Tic-Tac-Toe\n\n"); printf("Choose a cell numbered " "from 1 to 9 as below" " and play\n\n"); printf("\t\t\t 1 | 2 | 3 \n"); printf("\t\t\t------------\n"); printf("\t\t\t 4 | 5 | 6 \n"); printf("\t\t\t------------\n"); printf("\t\t\t 7 | 8 | 9 \n\n"); printf("-\t-\t-\t-\t-\t" "-\t-\t-\t-\t-\n\n"); return;} // Function to initialise the gamevoid initialise(char board[][SIDE], int moves[]){ // Initiate the random number // generator so that the same // configuration doesn't arises srand(time(NULL)); // Initially the board is empty for (int i = 0; i < SIDE; i++) { for (int j = 0; j < SIDE; j++) board[i][j] = ' '; } // Fill the moves with numbers for (int i = 0; i < SIDE * SIDE; i++) moves[i] = i; // randomise the moves random_shuffle(moves, moves + SIDE * SIDE); return;} // Function to declare winner of the gamevoid declareWinner(string whoseTurn){ if (whoseTurn == PLAYER1) cout << PLAYER1 << " has won\n"; else cout << PLAYER1 << " has won\n"; return;} // Function that returns true if// any of the row is crossed with// the same player's movebool rowCrossed(char board[][SIDE]){ for (int i = 0; i < SIDE; i++) { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') return (true); } return (false);} // Function that returns true if any// of the column is crossed with the// same player's movebool columnCrossed(char board[][SIDE]){ for (int i = 0; i < SIDE; i++) { if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') return (true); } return (false);} // Function that returns true if any// of the diagonal is crossed with// the same player's movebool diagonalCrossed(char board[][SIDE]){ if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') return (true); if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') return (true); return (false);} // Function that returns true if the// game is over else it returns a falsebool gameOver(char board[][SIDE]){ return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board));} // Function to play Tic-Tac-Toevoid playTicTacToe(string whoseTurn){ // A 3*3 Tic-Tac-Toe board for playing char board[SIDE][SIDE]; int moves[SIDE * SIDE]; // Initialise the game initialise(board, moves); // Show instructions before playing showInstructions(); int moveIndex = 0, x, y; int r, c; // Keep playing till the game is // over or it is a draw while (gameOver(board) == false && moveIndex != SIDE * SIDE) { if (whoseTurn == PLAYER1) { // Label for player1 wrong choice // of row and column player1: // Input the desired row and // column by player 1 to // insert X cout << PLAYER1 << " Enter the respective" << " row and column to " "insert X :\n"; cin >> r >> c; if (r <= 3 && c <= 3) { // To check desired row and // column should be empty if (board[r - 1] == ' ') board[r - 1] = 'X'; // If input is on already // filled position else { cout << "You cannot Overlap" << " on Already " "filled position:\n"; goto player1; } } // Input is not valid else { cout << "\nInput is not " << "valid please enter " << "right one\n"; goto player1; } showBoard(board); moveIndex++; whoseTurn = PLAYER2; } else if (whoseTurn == PLAYER2) { // Label for player2 wrong choice // of row and column player2: // Input the desired row and // column by player 1 to // insert X cout << PLAYER2 << " Enter the respective" << " row and column to " "insert O :"; cin >> r >> c; if (r <= 3 && c <= 3) { // Input the desired row and // column by player 1 to // insert X if (board[r - 1] == ' ') board[r - 1] = 'O'; // If input is on already // filled position else { cout << "You cannot Overlap" << " on Already " << "filled position:\n"; goto player2; } } // Input is not valid else { cout << "\nInput is not " << "valid please enter " << "right one :\n"; goto player2; } showBoard(board); moveIndex++; whoseTurn = PLAYER1; } } // If the game has drawn if (gameOver(board) == false && moveIndex == SIDE * SIDE) printf("It's a draw\n"); else { // Toggling the user to declare // the actual winner if (whoseTurn == PLAYER1) whoseTurn = PLAYER2; else if (whoseTurn == PLAYER2) whoseTurn = PLAYER1; // Declare the winner declareWinner(whoseTurn); } return;} // Driver Codeint main(){ // Take the name of players cout << "Enter name of first Player: "; cin >> PLAYER1; cout << "Enter name of Second Player: "; cin >> PLAYER2; // Use current time as seed for // random generator srand(time(0)); // Lets do toss int toss = rand() % 2; // Let us play the game if (toss == 1) { cout << "Player " << PLAYER1 << " win the toss" << endl; playTicTacToe(PLAYER1); } else { cout << "Player " << PLAYER2 << " win the toss" << endl; playTicTacToe(PLAYER2); } return (0);}
Output: Below is the output of the above code:
abhishek0719kadiyan
anikakapoor
Algorithms
Project
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Quadratic Probing in Hashing
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter
Implementing Web Scraping in Python with BeautifulSoup
Working with Images in Python
|
[
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 26136,
"s": 26053,
"text": "For 1-Person game (User vs. CPU), please refer Implementation of Tic-Tac-Toe game "
},
{
"code": null,
"e": 26154,
"s": 26136,
"text": "Rules of the Game"
},
{
"code": null,
"e": 26240,
"s": 26154,
"text": "The game is to be played between two people (in this program between HUMAN to HUMAN)."
},
{
"code": null,
"e": 26304,
"s": 26240,
"text": "First the game will take the names of the two players as input."
},
{
"code": null,
"e": 26384,
"s": 26304,
"text": "One of the player chooses ‘O’ and the other ‘X’ to mark their respective cells."
},
{
"code": null,
"e": 26460,
"s": 26384,
"text": "There would be a game toss, which will decide which player will move first."
},
{
"code": null,
"e": 26633,
"s": 26460,
"text": "The game starts with one of the players and the game ends when one of the players has one whole row/ column/ diagonal filled with his/her respective character (‘O’ or ‘X’)."
},
{
"code": null,
"e": 26696,
"s": 26633,
"text": "If the game is Tie then, A message is displayed “Game is Tie”."
},
{
"code": null,
"e": 26990,
"s": 26696,
"text": "Winning Strategy – An Interesting FactIf both the players play optimally then it is destined that you will never lose (“although the match can still be drawn”). It doesn’t matter whether you play first or second. In another way – “ Two expert players will always draw ”.Isn’t this interesting?"
},
{
"code": null,
"e": 27023,
"s": 26990,
"text": "Below is the code for the Game: "
},
{
"code": null,
"e": 27027,
"s": 27023,
"text": "C++"
},
{
"code": "// C++ program to play Tic-Tac-Toe#include <bits/stdc++.h>using namespace std; // Length of the board#define SIDE 3 // Name fo the playersstring PLAYER1, PLAYER2; // Function to show the current// board statusvoid showBoard(char board[][SIDE]){ printf(\"\\n\\n\"); printf(\"\\t\\t\\t %c | %c | %c \\n\", board[0][0], board[0][1], board[0][2]); printf(\"\\t\\t\\t------------\\n\"); printf(\"\\t\\t\\t %c | %c | %c \\n\", board[1][0], board[1][1], board[1][2]); printf(\"\\t\\t\\t------------\\n\"); printf(\"\\t\\t\\t %c | %c | %c \\n\\n\", board[2][0], board[2][1], board[2][2]); return;} // Function to show the instructionsvoid showInstructions(){ printf(\"\\t\\t\\t Tic-Tac-Toe\\n\\n\"); printf(\"Choose a cell numbered \" \"from 1 to 9 as below\" \" and play\\n\\n\"); printf(\"\\t\\t\\t 1 | 2 | 3 \\n\"); printf(\"\\t\\t\\t------------\\n\"); printf(\"\\t\\t\\t 4 | 5 | 6 \\n\"); printf(\"\\t\\t\\t------------\\n\"); printf(\"\\t\\t\\t 7 | 8 | 9 \\n\\n\"); printf(\"-\\t-\\t-\\t-\\t-\\t\" \"-\\t-\\t-\\t-\\t-\\n\\n\"); return;} // Function to initialise the gamevoid initialise(char board[][SIDE], int moves[]){ // Initiate the random number // generator so that the same // configuration doesn't arises srand(time(NULL)); // Initially the board is empty for (int i = 0; i < SIDE; i++) { for (int j = 0; j < SIDE; j++) board[i][j] = ' '; } // Fill the moves with numbers for (int i = 0; i < SIDE * SIDE; i++) moves[i] = i; // randomise the moves random_shuffle(moves, moves + SIDE * SIDE); return;} // Function to declare winner of the gamevoid declareWinner(string whoseTurn){ if (whoseTurn == PLAYER1) cout << PLAYER1 << \" has won\\n\"; else cout << PLAYER1 << \" has won\\n\"; return;} // Function that returns true if// any of the row is crossed with// the same player's movebool rowCrossed(char board[][SIDE]){ for (int i = 0; i < SIDE; i++) { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') return (true); } return (false);} // Function that returns true if any// of the column is crossed with the// same player's movebool columnCrossed(char board[][SIDE]){ for (int i = 0; i < SIDE; i++) { if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') return (true); } return (false);} // Function that returns true if any// of the diagonal is crossed with// the same player's movebool diagonalCrossed(char board[][SIDE]){ if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') return (true); if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') return (true); return (false);} // Function that returns true if the// game is over else it returns a falsebool gameOver(char board[][SIDE]){ return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board));} // Function to play Tic-Tac-Toevoid playTicTacToe(string whoseTurn){ // A 3*3 Tic-Tac-Toe board for playing char board[SIDE][SIDE]; int moves[SIDE * SIDE]; // Initialise the game initialise(board, moves); // Show instructions before playing showInstructions(); int moveIndex = 0, x, y; int r, c; // Keep playing till the game is // over or it is a draw while (gameOver(board) == false && moveIndex != SIDE * SIDE) { if (whoseTurn == PLAYER1) { // Label for player1 wrong choice // of row and column player1: // Input the desired row and // column by player 1 to // insert X cout << PLAYER1 << \" Enter the respective\" << \" row and column to \" \"insert X :\\n\"; cin >> r >> c; if (r <= 3 && c <= 3) { // To check desired row and // column should be empty if (board[r - 1] == ' ') board[r - 1] = 'X'; // If input is on already // filled position else { cout << \"You cannot Overlap\" << \" on Already \" \"filled position:\\n\"; goto player1; } } // Input is not valid else { cout << \"\\nInput is not \" << \"valid please enter \" << \"right one\\n\"; goto player1; } showBoard(board); moveIndex++; whoseTurn = PLAYER2; } else if (whoseTurn == PLAYER2) { // Label for player2 wrong choice // of row and column player2: // Input the desired row and // column by player 1 to // insert X cout << PLAYER2 << \" Enter the respective\" << \" row and column to \" \"insert O :\"; cin >> r >> c; if (r <= 3 && c <= 3) { // Input the desired row and // column by player 1 to // insert X if (board[r - 1] == ' ') board[r - 1] = 'O'; // If input is on already // filled position else { cout << \"You cannot Overlap\" << \" on Already \" << \"filled position:\\n\"; goto player2; } } // Input is not valid else { cout << \"\\nInput is not \" << \"valid please enter \" << \"right one :\\n\"; goto player2; } showBoard(board); moveIndex++; whoseTurn = PLAYER1; } } // If the game has drawn if (gameOver(board) == false && moveIndex == SIDE * SIDE) printf(\"It's a draw\\n\"); else { // Toggling the user to declare // the actual winner if (whoseTurn == PLAYER1) whoseTurn = PLAYER2; else if (whoseTurn == PLAYER2) whoseTurn = PLAYER1; // Declare the winner declareWinner(whoseTurn); } return;} // Driver Codeint main(){ // Take the name of players cout << \"Enter name of first Player: \"; cin >> PLAYER1; cout << \"Enter name of Second Player: \"; cin >> PLAYER2; // Use current time as seed for // random generator srand(time(0)); // Lets do toss int toss = rand() % 2; // Let us play the game if (toss == 1) { cout << \"Player \" << PLAYER1 << \" win the toss\" << endl; playTicTacToe(PLAYER1); } else { cout << \"Player \" << PLAYER2 << \" win the toss\" << endl; playTicTacToe(PLAYER2); } return (0);}",
"e": 34193,
"s": 27027,
"text": null
},
{
"code": null,
"e": 34241,
"s": 34193,
"text": "Output: Below is the output of the above code: "
},
{
"code": null,
"e": 34263,
"s": 34243,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 34275,
"s": 34263,
"text": "anikakapoor"
},
{
"code": null,
"e": 34286,
"s": 34275,
"text": "Algorithms"
},
{
"code": null,
"e": 34294,
"s": 34286,
"text": "Project"
},
{
"code": null,
"e": 34305,
"s": 34294,
"text": "Algorithms"
},
{
"code": null,
"e": 34403,
"s": 34305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34428,
"s": 34403,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34455,
"s": 34428,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 34489,
"s": 34455,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 34518,
"s": 34489,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 34585,
"s": 34518,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 34618,
"s": 34585,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 34640,
"s": 34618,
"text": "XML parsing in Python"
},
{
"code": null,
"e": 34685,
"s": 34640,
"text": "Python | Simple GUI calculator using Tkinter"
},
{
"code": null,
"e": 34740,
"s": 34685,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
}
] |
HTML | DOM Input URL pattern Property - GeeksforGeeks
|
17 Oct, 2019
The DOM Input URL pattern Property in HTML DOM is used to set or return the pattern attribute of a URL field. It is used to specify the regular expression on which the input elements value is checked. Use the global title attribute to describe the pattern for helping the user.
Syntax:
It returns the Input url pattern property.urlObject.pattern
urlObject.pattern
It is used to set Input url pattern property.urlObject.pattern = regexpProperty Values: It contains single value regexp which is used to specify the regular expression that a URL field value is checked against.Return Value: It returns a string value which represents the regular expression that a URL field value is checked against.Example-1: This example illustrates how to return the Input url pattern property.<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for="uname" style="color:green"> <b>Enter URL</b> </label> <input type="url" id="gfg" placeholder="Enter URL" size="20" pattern="https?://.+" title="Include http://"> <br> <br> <button type="button" onclick="geeks()"> Click </button> <p id="GFG" style="color:green; font-size:25px;"> </p> <script> function geeks() { var link = document.getElementById( "gfg").pattern; document.getElementById( "GFG").innerHTML = link; } </script> </center></body> </html>Output:Before Clicking On Button:After Clicking On Button:Example-2: This Example illustrates how to set the Property.<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for="uname" style="color:green"> <b>Enter URL</b> </label> <input type="url" id="gfg" placeholder="Enter URL" size="20" pattern="https?://.+" title="Include http://"> <br> <br> <button type="button" onclick="geeks()"> Click </button> <p id="GFG" style="color:green; font-size:25px;"> </p> <script> function geeks() { var link = document.getElementById( "gfg").pattern = "URL must start with " + "http://www.facebook.com/"; document.getElementById( "GFG").innerHTML = link; } </script> </center></body> </html>Output :Before Clicking On Button: :After Clicking On Button:Supported Browsers: The browser supported by DOM input URL pattern property are listed below:Google ChromeInternet Explorer 10.0 +FirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
urlObject.pattern = regexp
Property Values: It contains single value regexp which is used to specify the regular expression that a URL field value is checked against.
Return Value: It returns a string value which represents the regular expression that a URL field value is checked against.
Example-1: This example illustrates how to return the Input url pattern property.
<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for="uname" style="color:green"> <b>Enter URL</b> </label> <input type="url" id="gfg" placeholder="Enter URL" size="20" pattern="https?://.+" title="Include http://"> <br> <br> <button type="button" onclick="geeks()"> Click </button> <p id="GFG" style="color:green; font-size:25px;"> </p> <script> function geeks() { var link = document.getElementById( "gfg").pattern; document.getElementById( "GFG").innerHTML = link; } </script> </center></body> </html>
Output:Before Clicking On Button:
After Clicking On Button:
Example-2: This Example illustrates how to set the Property.
<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for="uname" style="color:green"> <b>Enter URL</b> </label> <input type="url" id="gfg" placeholder="Enter URL" size="20" pattern="https?://.+" title="Include http://"> <br> <br> <button type="button" onclick="geeks()"> Click </button> <p id="GFG" style="color:green; font-size:25px;"> </p> <script> function geeks() { var link = document.getElementById( "gfg").pattern = "URL must start with " + "http://www.facebook.com/"; document.getElementById( "GFG").innerHTML = link; } </script> </center></body> </html>
Output :Before Clicking On Button: :
After Clicking On Button:
Supported Browsers: The browser supported by DOM input URL pattern property are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubham_singh
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
HTML Cheat Sheet - A Basic Guide to HTML
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
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": 25494,
"s": 25466,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 25772,
"s": 25494,
"text": "The DOM Input URL pattern Property in HTML DOM is used to set or return the pattern attribute of a URL field. It is used to specify the regular expression on which the input elements value is checked. Use the global title attribute to describe the pattern for helping the user."
},
{
"code": null,
"e": 25780,
"s": 25772,
"text": "Syntax:"
},
{
"code": null,
"e": 25840,
"s": 25780,
"text": "It returns the Input url pattern property.urlObject.pattern"
},
{
"code": null,
"e": 25858,
"s": 25840,
"text": "urlObject.pattern"
},
{
"code": null,
"e": 29065,
"s": 25858,
"text": "It is used to set Input url pattern property.urlObject.pattern = regexpProperty Values: It contains single value regexp which is used to specify the regular expression that a URL field value is checked against.Return Value: It returns a string value which represents the regular expression that a URL field value is checked against.Example-1: This example illustrates how to return the Input url pattern property.<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for=\"uname\" style=\"color:green\"> <b>Enter URL</b> </label> <input type=\"url\" id=\"gfg\" placeholder=\"Enter URL\" size=\"20\" pattern=\"https?://.+\" title=\"Include http://\"> <br> <br> <button type=\"button\" onclick=\"geeks()\"> Click </button> <p id=\"GFG\" style=\"color:green; font-size:25px;\"> </p> <script> function geeks() { var link = document.getElementById( \"gfg\").pattern; document.getElementById( \"GFG\").innerHTML = link; } </script> </center></body> </html>Output:Before Clicking On Button:After Clicking On Button:Example-2: This Example illustrates how to set the Property.<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for=\"uname\" style=\"color:green\"> <b>Enter URL</b> </label> <input type=\"url\" id=\"gfg\" placeholder=\"Enter URL\" size=\"20\" pattern=\"https?://.+\" title=\"Include http://\"> <br> <br> <button type=\"button\" onclick=\"geeks()\"> Click </button> <p id=\"GFG\" style=\"color:green; font-size:25px;\"> </p> <script> function geeks() { var link = document.getElementById( \"gfg\").pattern = \"URL must start with \" + \"http://www.facebook.com/\"; document.getElementById( \"GFG\").innerHTML = link; } </script> </center></body> </html>Output :Before Clicking On Button: :After Clicking On Button:Supported Browsers: The browser supported by DOM input URL pattern property are listed below:Google ChromeInternet Explorer 10.0 +FirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29092,
"s": 29065,
"text": "urlObject.pattern = regexp"
},
{
"code": null,
"e": 29232,
"s": 29092,
"text": "Property Values: It contains single value regexp which is used to specify the regular expression that a URL field value is checked against."
},
{
"code": null,
"e": 29355,
"s": 29232,
"text": "Return Value: It returns a string value which represents the regular expression that a URL field value is checked against."
},
{
"code": null,
"e": 29437,
"s": 29355,
"text": "Example-1: This example illustrates how to return the Input url pattern property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for=\"uname\" style=\"color:green\"> <b>Enter URL</b> </label> <input type=\"url\" id=\"gfg\" placeholder=\"Enter URL\" size=\"20\" pattern=\"https?://.+\" title=\"Include http://\"> <br> <br> <button type=\"button\" onclick=\"geeks()\"> Click </button> <p id=\"GFG\" style=\"color:green; font-size:25px;\"> </p> <script> function geeks() { var link = document.getElementById( \"gfg\").pattern; document.getElementById( \"GFG\").innerHTML = link; } </script> </center></body> </html>",
"e": 30550,
"s": 29437,
"text": null
},
{
"code": null,
"e": 30584,
"s": 30550,
"text": "Output:Before Clicking On Button:"
},
{
"code": null,
"e": 30610,
"s": 30584,
"text": "After Clicking On Button:"
},
{
"code": null,
"e": 30671,
"s": 30610,
"text": "Example-2: This Example illustrates how to set the Property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM Input URL pattern Property </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input URL pattern Property </h2> <label for=\"uname\" style=\"color:green\"> <b>Enter URL</b> </label> <input type=\"url\" id=\"gfg\" placeholder=\"Enter URL\" size=\"20\" pattern=\"https?://.+\" title=\"Include http://\"> <br> <br> <button type=\"button\" onclick=\"geeks()\"> Click </button> <p id=\"GFG\" style=\"color:green; font-size:25px;\"> </p> <script> function geeks() { var link = document.getElementById( \"gfg\").pattern = \"URL must start with \" + \"http://www.facebook.com/\"; document.getElementById( \"GFG\").innerHTML = link; } </script> </center></body> </html>",
"e": 31855,
"s": 30671,
"text": null
},
{
"code": null,
"e": 31892,
"s": 31855,
"text": "Output :Before Clicking On Button: :"
},
{
"code": null,
"e": 31918,
"s": 31892,
"text": "After Clicking On Button:"
},
{
"code": null,
"e": 32012,
"s": 31918,
"text": "Supported Browsers: The browser supported by DOM input URL pattern property are listed below:"
},
{
"code": null,
"e": 32026,
"s": 32012,
"text": "Google Chrome"
},
{
"code": null,
"e": 32051,
"s": 32026,
"text": "Internet Explorer 10.0 +"
},
{
"code": null,
"e": 32059,
"s": 32051,
"text": "Firefox"
},
{
"code": null,
"e": 32065,
"s": 32059,
"text": "Opera"
},
{
"code": null,
"e": 32072,
"s": 32065,
"text": "Safari"
},
{
"code": null,
"e": 32209,
"s": 32072,
"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": 32223,
"s": 32209,
"text": "shubham_singh"
},
{
"code": null,
"e": 32232,
"s": 32223,
"text": "HTML-DOM"
},
{
"code": null,
"e": 32237,
"s": 32232,
"text": "HTML"
},
{
"code": null,
"e": 32254,
"s": 32237,
"text": "Web Technologies"
},
{
"code": null,
"e": 32259,
"s": 32254,
"text": "HTML"
},
{
"code": null,
"e": 32357,
"s": 32259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32381,
"s": 32357,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 32431,
"s": 32381,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 32472,
"s": 32431,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 32509,
"s": 32472,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 32573,
"s": 32509,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 32613,
"s": 32573,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32646,
"s": 32613,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32691,
"s": 32646,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32734,
"s": 32691,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
What is the yield keyword in JavaScript?
|
The yield keyword is used in JavaScript to pause and resume a generator function. The value of the expression is returned to the generator's caller.
Here are the Examples −
function* displayRank () {
var selPlayers= [1, 2, 3, 4];
for (var a = 0; a < selPlayers.length; a++) {
yield selPlayers[i];
}
}
After defining a generator function, use it like the following. HHere displayRank() is the generator function −
var rank = displayRank(); //
// value: 1
alert(rank.next());
// value: 2
alert(rank.next());
// value: 3
alert(rank.next());
// value: 4
alert(rank.next());
// value: undefined
alert(rank.next());
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "The yield keyword is used in JavaScript to pause and resume a generator function. The value of the expression is returned to the generator's caller."
},
{
"code": null,
"e": 1235,
"s": 1211,
"text": "Here are the Examples −"
},
{
"code": null,
"e": 1378,
"s": 1235,
"text": "function* displayRank () {\n var selPlayers= [1, 2, 3, 4];\n for (var a = 0; a < selPlayers.length; a++) {\n yield selPlayers[i];\n }\n}"
},
{
"code": null,
"e": 1490,
"s": 1378,
"text": "After defining a generator function, use it like the following. HHere displayRank() is the generator function −"
},
{
"code": null,
"e": 1687,
"s": 1490,
"text": "var rank = displayRank(); //\n// value: 1\nalert(rank.next());\n// value: 2\nalert(rank.next());\n// value: 3\nalert(rank.next());\n// value: 4\nalert(rank.next());\n// value: undefined\nalert(rank.next());"
}
] |
How To Select Rows From PySpark DataFrames Based on Column Values | Towards Data Science
|
Filtering rows of DataFrames is among the most commonly performed operations in PySpark. In today’s short guide we will discuss how to select a range of rows based on certain conditions in a few different ways.
Specifically, we will explore how to perform row selection using
the filter() function
the where() function
Spark SQL
First, let’s create an example DataFrame that we will reference throughout this article in order to demonstrate a couple of concepts.
from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \ .master('local[1]') \ .appName('Example') \ .getOrCreate()df = spark_session.createDataFrame( [ (1, True, 1.0, 100), (2, False, 2.0, 200), (3, False, 3.0, 300), (4, True, 4.0, 400), (5, True, 5.0, 500), ], ['colA', 'colB', 'colC', 'colD'])df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 1| true| 1.0| 100|| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+
The first option you have when it comes to filtering DataFrame rows is pyspark.sql.DataFrame.filter() function that performs filtering based on the specified conditions.
For example, say we want to keep only the rows whose values in colC are greater or equal to 3.0. The following expression will do the trick:
df = df.filter(df.colC >= 3.0)df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+
You can even specify Column functions such as pyspark.sql.Column.between in order to keep only rows between the specified lower and upper bounds, as shown below.
df = df.filter(df.colD.between(200, 400))df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|+----+-----+----+----+
pyspark.sql.DataFrame.where() is an alias to filter() we discussed in the previous section. It can be used in the same way in order to filter the rows of the DataFrame based on the conditions provided.
df = df.where(~df.colB)df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|+----+-----+----+----+
Alternatively, you can even use Spark SQL in order to query the DataFrame using an SQL expression. For example,
# Create a view for the dataframedf.createOrReplaceTempView("df_view")df = spark_session.sql( """ SELECT * FROM df_view WHERE colC >= 2.0 """)df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+
In today’s short guide we discussed how to perform row selection from PySpark DataFrames based on specific conditions. Specifically, we showcased how to do so using filter() and where() methods as well as Spark SQL.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
You may also like
|
[
{
"code": null,
"e": 383,
"s": 172,
"text": "Filtering rows of DataFrames is among the most commonly performed operations in PySpark. In today’s short guide we will discuss how to select a range of rows based on certain conditions in a few different ways."
},
{
"code": null,
"e": 448,
"s": 383,
"text": "Specifically, we will explore how to perform row selection using"
},
{
"code": null,
"e": 470,
"s": 448,
"text": "the filter() function"
},
{
"code": null,
"e": 491,
"s": 470,
"text": "the where() function"
},
{
"code": null,
"e": 501,
"s": 491,
"text": "Spark SQL"
},
{
"code": null,
"e": 635,
"s": 501,
"text": "First, let’s create an example DataFrame that we will reference throughout this article in order to demonstrate a couple of concepts."
},
{
"code": null,
"e": 1247,
"s": 635,
"text": "from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \\ .master('local[1]') \\ .appName('Example') \\ .getOrCreate()df = spark_session.createDataFrame( [ (1, True, 1.0, 100), (2, False, 2.0, 200), (3, False, 3.0, 300), (4, True, 4.0, 400), (5, True, 5.0, 500), ], ['colA', 'colB', 'colC', 'colD'])df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 1| true| 1.0| 100|| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+"
},
{
"code": null,
"e": 1417,
"s": 1247,
"text": "The first option you have when it comes to filtering DataFrame rows is pyspark.sql.DataFrame.filter() function that performs filtering based on the specified conditions."
},
{
"code": null,
"e": 1558,
"s": 1417,
"text": "For example, say we want to keep only the rows whose values in colC are greater or equal to 3.0. The following expression will do the trick:"
},
{
"code": null,
"e": 1752,
"s": 1558,
"text": "df = df.filter(df.colC >= 3.0)df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+"
},
{
"code": null,
"e": 1914,
"s": 1752,
"text": "You can even specify Column functions such as pyspark.sql.Column.between in order to keep only rows between the specified lower and upper bounds, as shown below."
},
{
"code": null,
"e": 2119,
"s": 1914,
"text": "df = df.filter(df.colD.between(200, 400))df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|+----+-----+----+----+"
},
{
"code": null,
"e": 2321,
"s": 2119,
"text": "pyspark.sql.DataFrame.where() is an alias to filter() we discussed in the previous section. It can be used in the same way in order to filter the rows of the DataFrame based on the conditions provided."
},
{
"code": null,
"e": 2486,
"s": 2321,
"text": "df = df.where(~df.colB)df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|+----+-----+----+----+"
},
{
"code": null,
"e": 2598,
"s": 2486,
"text": "Alternatively, you can even use Spark SQL in order to query the DataFrame using an SQL expression. For example,"
},
{
"code": null,
"e": 2942,
"s": 2598,
"text": "# Create a view for the dataframedf.createOrReplaceTempView(\"df_view\")df = spark_session.sql( \"\"\" SELECT * FROM df_view WHERE colC >= 2.0 \"\"\")df.show()+----+-----+----+----+|colA| colB|colC|colD|+----+-----+----+----+| 2|false| 2.0| 200|| 3|false| 3.0| 300|| 4| true| 4.0| 400|| 5| true| 5.0| 500|+----+-----+----+----+"
},
{
"code": null,
"e": 3158,
"s": 2942,
"text": "In today’s short guide we discussed how to perform row selection from PySpark DataFrames based on specific conditions. Specifically, we showcased how to do so using filter() and where() methods as well as Spark SQL."
},
{
"code": null,
"e": 3329,
"s": 3158,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium."
}
] |
PyQt5 QToolButton - GeeksforGeeks
|
17 Sep, 2019
Tool button is a PyQt5 widget which looks like the buttons used in Toolbar. This button contains icon which gives an idea about its utility. For adding this button in application QToolButton class is used.
Example:
A window having a Tool button with an exit icon. When the user clicks this button the application gets closed.
import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(506, 312) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.toolButton = QtWidgets.QToolButton(self.centralwidget) self.toolButton.setGeometry(QtCore.QRect(220, 120, 41, 41)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("exiticon.png [exact location of image]"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # adding icon to the toolbutton self.toolButton.setIcon(icon) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) # adding signal and slot self.toolButton.clicked.connect(self.exitapp) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) # For closing the application def exitapp(self): sys.exit() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
Output:
When user clicks this button, application get closed.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 25028,
"s": 24822,
"text": "Tool button is a PyQt5 widget which looks like the buttons used in Toolbar. This button contains icon which gives an idea about its utility. For adding this button in application QToolButton class is used."
},
{
"code": null,
"e": 25037,
"s": 25028,
"text": "Example:"
},
{
"code": null,
"e": 25148,
"s": 25037,
"text": "A window having a Tool button with an exit icon. When the user clicks this button the application gets closed."
},
{
"code": "import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(506, 312) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName(\"centralwidget\") self.toolButton = QtWidgets.QToolButton(self.centralwidget) self.toolButton.setGeometry(QtCore.QRect(220, 120, 41, 41)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\"exiticon.png [exact location of image]\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # adding icon to the toolbutton self.toolButton.setIcon(icon) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) # adding signal and slot self.toolButton.clicked.connect(self.exitapp) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\")) # For closing the application def exitapp(self): sys.exit() if __name__ == \"__main__\": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) ",
"e": 26546,
"s": 25148,
"text": null
},
{
"code": null,
"e": 26554,
"s": 26546,
"text": "Output:"
},
{
"code": null,
"e": 26608,
"s": 26554,
"text": "When user clicks this button, application get closed."
},
{
"code": null,
"e": 26619,
"s": 26608,
"text": "Python-gui"
},
{
"code": null,
"e": 26631,
"s": 26619,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26638,
"s": 26631,
"text": "Python"
},
{
"code": null,
"e": 26736,
"s": 26638,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26745,
"s": 26736,
"text": "Comments"
},
{
"code": null,
"e": 26758,
"s": 26745,
"text": "Old Comments"
},
{
"code": null,
"e": 26776,
"s": 26758,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26808,
"s": 26776,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26830,
"s": 26808,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26865,
"s": 26830,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26907,
"s": 26865,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26951,
"s": 26907,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26972,
"s": 26951,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27009,
"s": 26972,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27038,
"s": 27009,
"text": "*args and **kwargs in Python"
}
] |
Bootstrap - Alerts
|
This chapter will discuss about alerts and the classes Bootstrap provides for alerts. Alerts provide a way to style messages to the user. They provide contextual feedback messages for typical user actions.
You can add an optional close icon to alert. For inline dismissal use the Alerts jQuery plugin.
You can add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger). The following example demonstrates this −
<div class = "alert alert-success">Success! Well done its submitted.</div>
<div class = "alert alert-info">Info! take this info.</div>
<div class = "alert alert-warning">Warning ! Dont submit this.</div>
<div class = "alert alert-danger">Error ! Change few things.</div>
To build a dismissal alert −
Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)
Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)
Also add optional .alert-dismissable to the above <div> class.
Also add optional .alert-dismissable to the above <div> class.
Add a close button.
Add a close button.
The following example demonstrates this −
<div class = "alert alert-success alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Success! Well done its submitted.
</div>
<div class = "alert alert-info alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Info! take this info.
</div>
<div class = "alert alert-warning alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Warning ! Dont submit this.
</div>
<div class = "alert alert-danger alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
×
</button>
Error ! Change few things.
</div>
To get links in alerts −
Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)
Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)
Use the .alert-link utility class to quickly provide matching colored links within any alert.
Use the .alert-link utility class to quickly provide matching colored links within any alert.
<div class = "alert alert-success">
<a href = "#" class = "alert-link">Success! Well done its submitted.</a>
</div>
<div class = "alert alert-info">
<a href = "#" class = "alert-link">Info! take this info.</a>
</div>
<div class = "alert alert-warning">
<a href = "#" class = "alert-link">Warning ! Dont submit this.</a>
</div>
<div class = "alert alert-danger">
<a href = "#" class = "alert-link">Error ! Change few things.</a>
</div>
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3537,
"s": 3331,
"text": "This chapter will discuss about alerts and the classes Bootstrap provides for alerts. Alerts provide a way to style messages to the user. They provide contextual feedback messages for typical user actions."
},
{
"code": null,
"e": 3633,
"s": 3537,
"text": "You can add an optional close icon to alert. For inline dismissal use the Alerts jQuery plugin."
},
{
"code": null,
"e": 3865,
"s": 3633,
"text": "You can add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger). The following example demonstrates this −"
},
{
"code": null,
"e": 4137,
"s": 3865,
"text": "\n<div class = \"alert alert-success\">Success! Well done its submitted.</div>\n<div class = \"alert alert-info\">Info! take this info.</div>\n<div class = \"alert alert-warning\">Warning ! Dont submit this.</div>\n<div class = \"alert alert-danger\">Error ! Change few things.</div>"
},
{
"code": null,
"e": 4166,
"s": 4137,
"text": "To build a dismissal alert −"
},
{
"code": null,
"e": 4347,
"s": 4166,
"text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)"
},
{
"code": null,
"e": 4528,
"s": 4347,
"text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)"
},
{
"code": null,
"e": 4591,
"s": 4528,
"text": "Also add optional .alert-dismissable to the above <div> class."
},
{
"code": null,
"e": 4654,
"s": 4591,
"text": "Also add optional .alert-dismissable to the above <div> class."
},
{
"code": null,
"e": 4674,
"s": 4654,
"text": "Add a close button."
},
{
"code": null,
"e": 4694,
"s": 4674,
"text": "Add a close button."
},
{
"code": null,
"e": 4736,
"s": 4694,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 5570,
"s": 4736,
"text": "<div class = \"alert alert-success alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n\t\n Success! Well done its submitted.\n</div>\n\n<div class = \"alert alert-info alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n\t\n Info! take this info.\n</div>\n\n<div class = \"alert alert-warning alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n\t\n Warning ! Dont submit this.\n</div>\n\n<div class = \"alert alert-danger alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n ×\n </button>\n\t\n Error ! Change few things.\n</div>"
},
{
"code": null,
"e": 5595,
"s": 5570,
"text": "To get links in alerts −"
},
{
"code": null,
"e": 5776,
"s": 5595,
"text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)"
},
{
"code": null,
"e": 5957,
"s": 5776,
"text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)"
},
{
"code": null,
"e": 6051,
"s": 5957,
"text": "Use the .alert-link utility class to quickly provide matching colored links within any alert."
},
{
"code": null,
"e": 6145,
"s": 6051,
"text": "Use the .alert-link utility class to quickly provide matching colored links within any alert."
},
{
"code": null,
"e": 6595,
"s": 6145,
"text": "<div class = \"alert alert-success\">\n <a href = \"#\" class = \"alert-link\">Success! Well done its submitted.</a>\n</div>\n\n<div class = \"alert alert-info\">\n <a href = \"#\" class = \"alert-link\">Info! take this info.</a>\n</div>\n\n<div class = \"alert alert-warning\">\n <a href = \"#\" class = \"alert-link\">Warning ! Dont submit this.</a>\n</div>\n\n<div class = \"alert alert-danger\">\n <a href = \"#\" class = \"alert-link\">Error ! Change few things.</a>\n</div>"
},
{
"code": null,
"e": 6628,
"s": 6595,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6642,
"s": 6628,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6677,
"s": 6642,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6694,
"s": 6677,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6731,
"s": 6694,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 6759,
"s": 6731,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6792,
"s": 6759,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6804,
"s": 6792,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6839,
"s": 6804,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6856,
"s": 6839,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 6889,
"s": 6856,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6909,
"s": 6889,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6916,
"s": 6909,
"text": " Print"
},
{
"code": null,
"e": 6927,
"s": 6916,
"text": " Add Notes"
}
] |
14 Popular Evaluation Metrics in Machine Learning | by Satyam Kumar | Towards Data Science
|
The evaluation metric is used to measure the performance of a machine learning model. A correct choice of an evaluation metric is very essential for a model. This article will cover all the metrics used in classification and regression machine learning models.
Evaluation Metrics discussed in the article:
Metrics used in Classification Models:
For a classification machine learning algorithm, the output of the model can be a target class label or probability score. The different evaluation metric is used for these two approaches.
Confusion Matrix:
A confusion matrix is the easiest way to measure the performance of a classification problem. It is used to visualize and observe the performance of the prediction of ML models. For a k class classification model, a matrix of size k*k is used to observe the prediction. For a binary class classification problem, a standard 2*2 size matrix is used.
Notations,TP: True Postive: Number of Points which are actually positive and predicted to be positiveFN: False Negative: Number of Points which are actually positive but predicted to be negativeFP: False Positive: Number of Points which are actually negative but predicted to be positiveTN: True Negative: Number of Points which are actually negative and predicted to be negative
An ML model is considered good if the numbers on principal diagonal are maximum and the number on off-diagonal should be minimum. For a binary confusion matrix, TP and TN should be high and FN and FP should be low.
Different problems have different metrics to choose from:
For the problem of cancer diagnosis, TP should be high and FN should me very low close to 0. Patients having cancer should never be predicted to be not cancer which is the case of FN.
For the problem of spam detection, FP should be very low. No mails should be predicted to be spam which is not spam.
What are type I and type II errors?
A type I error is also known as a false positive (FP). A type II error is also known as a false negative (FN).
Accuracy:
Accuracy is the most common performance metric used for classification algorithms. Accuracy is mainly used for a balanced dataset. It is defined as the ratio of the number of correct predictions made to all the predictions made.
The accuracy metric may not work well with unbalanced datasets as it may get biased towards the majority class. Below mentioned metrics overcomes this disadvantage.
TPR (True Positive Rate):
TPR is the ratio of the number of correctly predicted positive class to the total number of positive classes.
TNR (True Negative Rate):
TNR is the ratio of the number of correctly predicted negative class to the total number of negative classes.
FPR (False Positive Rate):
FPR is the ratio of the number of wrongly predicted positive class to the total number of negative classes.
FNR (False Negative Rate):
TNR is the ratio of the number of correctly wrongly negative class to the total number of positive classes.
Precision:
The precision metric used in information retrieval is defined as from all the points predicted to positive how many of them are actually positive.
The precision metric is used for ML models where low False Positive (FP) is important such as spam detection.
Recall:
The recall metric is also known as sensitivity is defined as from all the points which are actually positive how many of them are predicted to be positive. The recall is the same as the true positive rate (TPR).
The recall metric is used for ML models where low False Negative (FN) is important such as cancer diagnosis.
F-beta score:
For ML models where both FN and FP have equal importance to be low, then we can use combine the advantage of Precision and Recall in a new metric called F-beta score.
Here beta is a variable,(Beta < 1) is used when FP have more impact than FN(Beta > 1) is used when FN have more impact than FP(Beta == 1) is used when FN and FP have equal importance
when Beta=1 then the metric is called F1 score giving equal importance to precision and recall.
ROC Curve and AUC:
ROC ( Receiver Operating Characteristic) curve is used mainly for binary classification based ML models. ROC curve and AUC (Area Under Curve) can be implemented for ML models that output probability scores.
ROC curve is a curve drawn joining all the points for different threshold values in a plot of TPR vs FPR.
The output of the ML model is the probability value, for different values of threshold find y_hat values and then compute TPR and FPR. Further, draw a plot to observe the ROC curve and AUC.
For the below sample dataset:
Notation,x_i: ith data pointy: target binary class labely_hat: predicted probability valuey_hat(t): predicted binary class label for threshold - t
The ROC curve (Blue Curve) for about sample dataset is below:
For a real-world dataset the ROC curve will seem like:
The above plot is the ROC curve (Blue curve), and the area under the curve is called AUC (Area Under Curve). The orange line is the x=y line, and the ROC curve will always be above this line.
Log Loss:
Log Loss is also known as cross-entropy loss uses probability estimates to compute the performance of the model. The probability estimate of the model is between 0 and 1. The log loss of the model is always greater than 0, a score of 0 being the best model. Log Loss is the amount of uncertainty of our prediction based on how much it varies from the actual label. With the help of the Log Loss value, we can have a more accurate view of the performance of our model. The equation of log loss of binary classification is:
Notations,n: number of points in datasetp_i: predicted probability of ith pointy_i: actual output class label
Below is a sample dataset:
Notation,x_i: ith data pointy: target binary class labely_hat: predicted probability value
Metrics used in Regression Models:
For regression problems, the output of ML models is real-valued. Various metrics to compute the performance of regression models are:
Mean Absolute Error (MAE):
MAE is the simplest error metric used in regression problems. MAE is defined as the sum of the average of the absolute difference between the predicted and actual values. It computes the performance of the regression model by summing the variability of prediction from the actual value.
Notation,n: number of data pointy: actual real valuey_hat: predicted real value
Root Mean Squared Error (RMSE) and Mean Squared Error (MSE):
MSE is the same as the MAE, but the only difference is that it squares the difference between actual and predicted output values before summing them all instead of using the absolute value. RMSE is taking the square root of MSE.
Notation,n: number of data pointy: actual real valuey_hat: predicted real value
R squared Error:
R Squared metric is generally used for explanatory purposes and indicates the goodness of fit of a set of predicted output values to the actual output values.
Notation,n: number of data pointy_i: ith actual real valuey_hat: predicted real valuey_bar: mean of y
Thank You for Reading!
|
[
{
"code": null,
"e": 433,
"s": 172,
"text": "The evaluation metric is used to measure the performance of a machine learning model. A correct choice of an evaluation metric is very essential for a model. This article will cover all the metrics used in classification and regression machine learning models."
},
{
"code": null,
"e": 478,
"s": 433,
"text": "Evaluation Metrics discussed in the article:"
},
{
"code": null,
"e": 517,
"s": 478,
"text": "Metrics used in Classification Models:"
},
{
"code": null,
"e": 706,
"s": 517,
"text": "For a classification machine learning algorithm, the output of the model can be a target class label or probability score. The different evaluation metric is used for these two approaches."
},
{
"code": null,
"e": 724,
"s": 706,
"text": "Confusion Matrix:"
},
{
"code": null,
"e": 1073,
"s": 724,
"text": "A confusion matrix is the easiest way to measure the performance of a classification problem. It is used to visualize and observe the performance of the prediction of ML models. For a k class classification model, a matrix of size k*k is used to observe the prediction. For a binary class classification problem, a standard 2*2 size matrix is used."
},
{
"code": null,
"e": 1453,
"s": 1073,
"text": "Notations,TP: True Postive: Number of Points which are actually positive and predicted to be positiveFN: False Negative: Number of Points which are actually positive but predicted to be negativeFP: False Positive: Number of Points which are actually negative but predicted to be positiveTN: True Negative: Number of Points which are actually negative and predicted to be negative"
},
{
"code": null,
"e": 1668,
"s": 1453,
"text": "An ML model is considered good if the numbers on principal diagonal are maximum and the number on off-diagonal should be minimum. For a binary confusion matrix, TP and TN should be high and FN and FP should be low."
},
{
"code": null,
"e": 1726,
"s": 1668,
"text": "Different problems have different metrics to choose from:"
},
{
"code": null,
"e": 1910,
"s": 1726,
"text": "For the problem of cancer diagnosis, TP should be high and FN should me very low close to 0. Patients having cancer should never be predicted to be not cancer which is the case of FN."
},
{
"code": null,
"e": 2027,
"s": 1910,
"text": "For the problem of spam detection, FP should be very low. No mails should be predicted to be spam which is not spam."
},
{
"code": null,
"e": 2063,
"s": 2027,
"text": "What are type I and type II errors?"
},
{
"code": null,
"e": 2174,
"s": 2063,
"text": "A type I error is also known as a false positive (FP). A type II error is also known as a false negative (FN)."
},
{
"code": null,
"e": 2184,
"s": 2174,
"text": "Accuracy:"
},
{
"code": null,
"e": 2413,
"s": 2184,
"text": "Accuracy is the most common performance metric used for classification algorithms. Accuracy is mainly used for a balanced dataset. It is defined as the ratio of the number of correct predictions made to all the predictions made."
},
{
"code": null,
"e": 2578,
"s": 2413,
"text": "The accuracy metric may not work well with unbalanced datasets as it may get biased towards the majority class. Below mentioned metrics overcomes this disadvantage."
},
{
"code": null,
"e": 2604,
"s": 2578,
"text": "TPR (True Positive Rate):"
},
{
"code": null,
"e": 2714,
"s": 2604,
"text": "TPR is the ratio of the number of correctly predicted positive class to the total number of positive classes."
},
{
"code": null,
"e": 2740,
"s": 2714,
"text": "TNR (True Negative Rate):"
},
{
"code": null,
"e": 2850,
"s": 2740,
"text": "TNR is the ratio of the number of correctly predicted negative class to the total number of negative classes."
},
{
"code": null,
"e": 2877,
"s": 2850,
"text": "FPR (False Positive Rate):"
},
{
"code": null,
"e": 2985,
"s": 2877,
"text": "FPR is the ratio of the number of wrongly predicted positive class to the total number of negative classes."
},
{
"code": null,
"e": 3012,
"s": 2985,
"text": "FNR (False Negative Rate):"
},
{
"code": null,
"e": 3120,
"s": 3012,
"text": "TNR is the ratio of the number of correctly wrongly negative class to the total number of positive classes."
},
{
"code": null,
"e": 3131,
"s": 3120,
"text": "Precision:"
},
{
"code": null,
"e": 3278,
"s": 3131,
"text": "The precision metric used in information retrieval is defined as from all the points predicted to positive how many of them are actually positive."
},
{
"code": null,
"e": 3388,
"s": 3278,
"text": "The precision metric is used for ML models where low False Positive (FP) is important such as spam detection."
},
{
"code": null,
"e": 3396,
"s": 3388,
"text": "Recall:"
},
{
"code": null,
"e": 3608,
"s": 3396,
"text": "The recall metric is also known as sensitivity is defined as from all the points which are actually positive how many of them are predicted to be positive. The recall is the same as the true positive rate (TPR)."
},
{
"code": null,
"e": 3717,
"s": 3608,
"text": "The recall metric is used for ML models where low False Negative (FN) is important such as cancer diagnosis."
},
{
"code": null,
"e": 3731,
"s": 3717,
"text": "F-beta score:"
},
{
"code": null,
"e": 3898,
"s": 3731,
"text": "For ML models where both FN and FP have equal importance to be low, then we can use combine the advantage of Precision and Recall in a new metric called F-beta score."
},
{
"code": null,
"e": 4081,
"s": 3898,
"text": "Here beta is a variable,(Beta < 1) is used when FP have more impact than FN(Beta > 1) is used when FN have more impact than FP(Beta == 1) is used when FN and FP have equal importance"
},
{
"code": null,
"e": 4177,
"s": 4081,
"text": "when Beta=1 then the metric is called F1 score giving equal importance to precision and recall."
},
{
"code": null,
"e": 4196,
"s": 4177,
"text": "ROC Curve and AUC:"
},
{
"code": null,
"e": 4403,
"s": 4196,
"text": "ROC ( Receiver Operating Characteristic) curve is used mainly for binary classification based ML models. ROC curve and AUC (Area Under Curve) can be implemented for ML models that output probability scores."
},
{
"code": null,
"e": 4509,
"s": 4403,
"text": "ROC curve is a curve drawn joining all the points for different threshold values in a plot of TPR vs FPR."
},
{
"code": null,
"e": 4699,
"s": 4509,
"text": "The output of the ML model is the probability value, for different values of threshold find y_hat values and then compute TPR and FPR. Further, draw a plot to observe the ROC curve and AUC."
},
{
"code": null,
"e": 4729,
"s": 4699,
"text": "For the below sample dataset:"
},
{
"code": null,
"e": 4876,
"s": 4729,
"text": "Notation,x_i: ith data pointy: target binary class labely_hat: predicted probability valuey_hat(t): predicted binary class label for threshold - t"
},
{
"code": null,
"e": 4938,
"s": 4876,
"text": "The ROC curve (Blue Curve) for about sample dataset is below:"
},
{
"code": null,
"e": 4993,
"s": 4938,
"text": "For a real-world dataset the ROC curve will seem like:"
},
{
"code": null,
"e": 5185,
"s": 4993,
"text": "The above plot is the ROC curve (Blue curve), and the area under the curve is called AUC (Area Under Curve). The orange line is the x=y line, and the ROC curve will always be above this line."
},
{
"code": null,
"e": 5195,
"s": 5185,
"text": "Log Loss:"
},
{
"code": null,
"e": 5717,
"s": 5195,
"text": "Log Loss is also known as cross-entropy loss uses probability estimates to compute the performance of the model. The probability estimate of the model is between 0 and 1. The log loss of the model is always greater than 0, a score of 0 being the best model. Log Loss is the amount of uncertainty of our prediction based on how much it varies from the actual label. With the help of the Log Loss value, we can have a more accurate view of the performance of our model. The equation of log loss of binary classification is:"
},
{
"code": null,
"e": 5827,
"s": 5717,
"text": "Notations,n: number of points in datasetp_i: predicted probability of ith pointy_i: actual output class label"
},
{
"code": null,
"e": 5854,
"s": 5827,
"text": "Below is a sample dataset:"
},
{
"code": null,
"e": 5945,
"s": 5854,
"text": "Notation,x_i: ith data pointy: target binary class labely_hat: predicted probability value"
},
{
"code": null,
"e": 5980,
"s": 5945,
"text": "Metrics used in Regression Models:"
},
{
"code": null,
"e": 6114,
"s": 5980,
"text": "For regression problems, the output of ML models is real-valued. Various metrics to compute the performance of regression models are:"
},
{
"code": null,
"e": 6141,
"s": 6114,
"text": "Mean Absolute Error (MAE):"
},
{
"code": null,
"e": 6428,
"s": 6141,
"text": "MAE is the simplest error metric used in regression problems. MAE is defined as the sum of the average of the absolute difference between the predicted and actual values. It computes the performance of the regression model by summing the variability of prediction from the actual value."
},
{
"code": null,
"e": 6508,
"s": 6428,
"text": "Notation,n: number of data pointy: actual real valuey_hat: predicted real value"
},
{
"code": null,
"e": 6569,
"s": 6508,
"text": "Root Mean Squared Error (RMSE) and Mean Squared Error (MSE):"
},
{
"code": null,
"e": 6798,
"s": 6569,
"text": "MSE is the same as the MAE, but the only difference is that it squares the difference between actual and predicted output values before summing them all instead of using the absolute value. RMSE is taking the square root of MSE."
},
{
"code": null,
"e": 6878,
"s": 6798,
"text": "Notation,n: number of data pointy: actual real valuey_hat: predicted real value"
},
{
"code": null,
"e": 6895,
"s": 6878,
"text": "R squared Error:"
},
{
"code": null,
"e": 7054,
"s": 6895,
"text": "R Squared metric is generally used for explanatory purposes and indicates the goodness of fit of a set of predicted output values to the actual output values."
},
{
"code": null,
"e": 7156,
"s": 7054,
"text": "Notation,n: number of data pointy_i: ith actual real valuey_hat: predicted real valuey_bar: mean of y"
}
] |
SAP ABAP - While Loop
|
A WHILE loop statement repeatedly executes a target statement as long as a given condition is true.
The general format for the WHILE command is as follows −
WHILE <logical expression>
<statement block>.
ENDWHILE.
The statement block may be a single statement or a block of statements.
The WHILE loop executes the statements enclosed by the WHILE and ENDWHILE commands until the logical expression becomes false.
The WHILE command is preferable while considering the performance of programs. The loop continues until the logical statement is found to be untrue and exits the loop if a false statement is found, and the first statement after the WHILE loop is executed.
REPORT YS_SEP_15.
DATA: a type i.
a = 0.
WHILE a <> 8.
Write: / 'This is the line:', a.
a = a + 1.
ENDWHILE.
The above code produces the following output −
This is the line: 0
This is the line: 1
This is the line: 2
This is the line: 3
This is the line: 4
This is the line: 5
This is the line: 6
This is the line: 7
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2998,
"s": 2898,
"text": "A WHILE loop statement repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 3055,
"s": 2998,
"text": "The general format for the WHILE command is as follows −"
},
{
"code": null,
"e": 3121,
"s": 3055,
"text": "WHILE <logical expression> \n\n<statement block>. \n \nENDWHILE.\n"
},
{
"code": null,
"e": 3193,
"s": 3121,
"text": "The statement block may be a single statement or a block of statements."
},
{
"code": null,
"e": 3320,
"s": 3193,
"text": "The WHILE loop executes the statements enclosed by the WHILE and ENDWHILE commands until the logical expression becomes false."
},
{
"code": null,
"e": 3576,
"s": 3320,
"text": "The WHILE command is preferable while considering the performance of programs. The loop continues until the logical statement is found to be untrue and exits the loop if a false statement is found, and the first statement after the WHILE loop is executed."
},
{
"code": null,
"e": 3709,
"s": 3576,
"text": "REPORT YS_SEP_15.\n \nDATA: a type i. \n \na = 0.\n \nWHILE a <> 8.\n \n Write: / 'This is the line:', a. \n a = a + 1.\n \nENDWHILE."
},
{
"code": null,
"e": 3756,
"s": 3709,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 3924,
"s": 3756,
"text": "This is the line: 0 \nThis is the line: 1 \nThis is the line: 2 \nThis is the line: 3 \nThis is the line: 4 \nThis is the line: 5 \nThis is the line: 6 \nThis is the line: 7\n"
},
{
"code": null,
"e": 3957,
"s": 3924,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3971,
"s": 3957,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 4004,
"s": 3971,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4016,
"s": 4004,
"text": " Neha Gupta"
},
{
"code": null,
"e": 4051,
"s": 4016,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4066,
"s": 4051,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4099,
"s": 4066,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4114,
"s": 4099,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 4149,
"s": 4114,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4161,
"s": 4149,
"text": " Neha Malik"
},
{
"code": null,
"e": 4196,
"s": 4161,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4208,
"s": 4196,
"text": " Neha Malik"
},
{
"code": null,
"e": 4215,
"s": 4208,
"text": " Print"
},
{
"code": null,
"e": 4226,
"s": 4215,
"text": " Add Notes"
}
] |
How to get String Length in PHP ? - GeeksforGeeks
|
20 May, 2021
In this article, we learn how to find the length of the string in PHP.
Approach: This task can be done by using the built-in function strlen() in PHP. This method is used to return the length of the string. It returns a numeric value that represents the length of the given string.
Syntax:
strlen($string)
Example 1:
PHP
<?php// PHP program to count all// characters in a string$str = "GeeksforGeekslover"; // Using strlen() function to// get the length of string$len = strlen($str); // Printing the resultecho $len;?>
Output:
18
Example 2: Below code demonstrates the use of strlen() function in PHP where the string has special characters and escape sequences.
PHP
<?php// PHP program to find the length of// a given string which has special// characters$str = "\n LuckyGeeks ;"; // Here '\n' has been counted as 1echo strlen($str);?>
Output:
14
PHP-function
PHP-Questions
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to pass form variables from one page to other page in PHP ?
|
[
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25044,
"s": 24972,
"text": "In this article, we learn how to find the length of the string in PHP. "
},
{
"code": null,
"e": 25256,
"s": 25044,
"text": "Approach: This task can be done by using the built-in function strlen() in PHP. This method is used to return the length of the string. It returns a numeric value that represents the length of the given string. "
},
{
"code": null,
"e": 25264,
"s": 25256,
"text": "Syntax:"
},
{
"code": null,
"e": 25280,
"s": 25264,
"text": "strlen($string)"
},
{
"code": null,
"e": 25292,
"s": 25280,
"text": "Example 1: "
},
{
"code": null,
"e": 25296,
"s": 25292,
"text": "PHP"
},
{
"code": "<?php// PHP program to count all// characters in a string$str = \"GeeksforGeekslover\"; // Using strlen() function to// get the length of string$len = strlen($str); // Printing the resultecho $len;?>",
"e": 25500,
"s": 25296,
"text": null
},
{
"code": null,
"e": 25508,
"s": 25500,
"text": "Output:"
},
{
"code": null,
"e": 25511,
"s": 25508,
"text": "18"
},
{
"code": null,
"e": 25644,
"s": 25511,
"text": "Example 2: Below code demonstrates the use of strlen() function in PHP where the string has special characters and escape sequences."
},
{
"code": null,
"e": 25648,
"s": 25644,
"text": "PHP"
},
{
"code": "<?php// PHP program to find the length of// a given string which has special// characters$str = \"\\n LuckyGeeks ;\"; // Here '\\n' has been counted as 1echo strlen($str);?>",
"e": 25823,
"s": 25648,
"text": null
},
{
"code": null,
"e": 25831,
"s": 25823,
"text": "Output:"
},
{
"code": null,
"e": 25834,
"s": 25831,
"text": "14"
},
{
"code": null,
"e": 25847,
"s": 25834,
"text": "PHP-function"
},
{
"code": null,
"e": 25861,
"s": 25847,
"text": "PHP-Questions"
},
{
"code": null,
"e": 25868,
"s": 25861,
"text": "Picked"
},
{
"code": null,
"e": 25872,
"s": 25868,
"text": "PHP"
},
{
"code": null,
"e": 25885,
"s": 25872,
"text": "PHP Programs"
},
{
"code": null,
"e": 25902,
"s": 25885,
"text": "Web Technologies"
},
{
"code": null,
"e": 25906,
"s": 25902,
"text": "PHP"
},
{
"code": null,
"e": 26004,
"s": 25906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26086,
"s": 26004,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26137,
"s": 26086,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26211,
"s": 26137,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 26253,
"s": 26211,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26290,
"s": 26253,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 26342,
"s": 26290,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 26424,
"s": 26342,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26466,
"s": 26424,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26489,
"s": 26466,
"text": "PHP | Ternary Operator"
}
] |
Program to check idempotent matrix in C++
|
Given a matrix M[r][c], ‘r’ denotes number of rows and ‘c’ denotes number of columns such that r = c forming a square matrix. We have to check whether the given square matrix is an Idempotent matrix or not.
Idempotent Matrix
A matrix ‘M’ is called Idempotent matrix if and only the matrix ‘M’ multiplied by itself returns the same matrix ‘M’ i.e. M * M = M.
Like in the given example below −
We can say that the above matrix is multiplied by itself and returns the same matrix; hence the matrix is Idempotent matrix.
Input: m[3][3] = { {2, -2, -4},
{-1, 3, 4},
{1, -2, -3}}
Output: Idempotent
Input: m[3][3] == { {3, 0, 0},
{0, 2, 0},
{0, 0, 3} }
Output: Not Idempotent
Start
Step 1 -> define macro as #define size 3
Step 2 -> declare function for matrix multiplication
void multiply(int arr[][size], int res[][size])
Loop For int i = 0 and i < size and i++
Loop For int j = 0 and j < size and j++
Set res[i][j] = 0
Loop for int k = 0 and k < size and k++
Set res[i][j] += arr[i][k] * arr[k][j]
End
End
End
Step 3 -> declare function to check idempotent or not
bool check(int arr[][size])
declare int res[size][size]
call multiply(arr, res)
Loop For int i = 0 and i < size and i++
Loop For int j = 0 and j < size and j++
IF (arr[i][j] != res[i][j])
return false
End
End
End
return true
step 4 -> In main()
declare int arr[size][size] = {{1, -1, -1},
{-1, 1, 1},
{1, -1, -1}}
IF (check(arr))
Print its an idempotent matrix
Else
Print its not an idempotent matrix
Stop
#include<bits/stdc++.h>
#define size 3
using namespace std;
//matrix multiplication.
void multiply(int arr[][size], int res[][size]){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
res[i][j] = 0;
for (int k = 0; k < size; k++)
res[i][j] += arr[i][k] * arr[k][j];
}
}
}
//check idempotent or not
bool check(int arr[][size]){
int res[size][size];
multiply(arr, res);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (arr[i][j] != res[i][j])
return false;
return true;
}
int main(){
int arr[size][size] = {{1, -1, -1},
{-1, 1, 1},
{1, -1, -1}};
if (check(arr))
cout << "its an idempotent matrix";
else
cout << "its not an idempotent matrix";
return 0;
}
its an idempotent matrix
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Given a matrix M[r][c], ‘r’ denotes number of rows and ‘c’ denotes number of columns such that r = c forming a square matrix. We have to check whether the given square matrix is an Idempotent matrix or not."
},
{
"code": null,
"e": 1287,
"s": 1269,
"text": "Idempotent Matrix"
},
{
"code": null,
"e": 1420,
"s": 1287,
"text": "A matrix ‘M’ is called Idempotent matrix if and only the matrix ‘M’ multiplied by itself returns the same matrix ‘M’ i.e. M * M = M."
},
{
"code": null,
"e": 1454,
"s": 1420,
"text": "Like in the given example below −"
},
{
"code": null,
"e": 1580,
"s": 1454,
"text": "We can say that the above matrix is multiplied by itself and returns the same matrix; hence the matrix is Idempotent matrix. "
},
{
"code": null,
"e": 1745,
"s": 1580,
"text": "Input: m[3][3] = { {2, -2, -4},\n {-1, 3, 4},\n {1, -2, -3}}\nOutput: Idempotent\nInput: m[3][3] == { {3, 0, 0},\n {0, 2, 0},\n {0, 0, 3} }\nOutput: Not Idempotent"
},
{
"code": null,
"e": 2716,
"s": 1745,
"text": "Start\nStep 1 -> define macro as #define size 3\nStep 2 -> declare function for matrix multiplication\n void multiply(int arr[][size], int res[][size])\n Loop For int i = 0 and i < size and i++\n Loop For int j = 0 and j < size and j++\n Set res[i][j] = 0\n Loop for int k = 0 and k < size and k++\n Set res[i][j] += arr[i][k] * arr[k][j]\n End\n End\n End\nStep 3 -> declare function to check idempotent or not\n bool check(int arr[][size])\n declare int res[size][size]\n call multiply(arr, res)\n Loop For int i = 0 and i < size and i++\n Loop For int j = 0 and j < size and j++\n IF (arr[i][j] != res[i][j])\n return false\n End\n End\n End\n return true\nstep 4 -> In main()\n declare int arr[size][size] = {{1, -1, -1},\n {-1, 1, 1},\n {1, -1, -1}}\n IF (check(arr))\n Print its an idempotent matrix\n Else\n Print its not an idempotent matrix\nStop"
},
{
"code": null,
"e": 3514,
"s": 2716,
"text": "#include<bits/stdc++.h>\n#define size 3\nusing namespace std;\n//matrix multiplication.\nvoid multiply(int arr[][size], int res[][size]){\n for (int i = 0; i < size; i++){\n for (int j = 0; j < size; j++){\n res[i][j] = 0;\n for (int k = 0; k < size; k++)\n res[i][j] += arr[i][k] * arr[k][j];\n }\n }\n}\n//check idempotent or not\nbool check(int arr[][size]){\n int res[size][size];\n multiply(arr, res);\n for (int i = 0; i < size; i++)\n for (int j = 0; j < size; j++)\n if (arr[i][j] != res[i][j])\n return false;\n return true;\n}\nint main(){\n int arr[size][size] = {{1, -1, -1},\n {-1, 1, 1},\n {1, -1, -1}};\n if (check(arr))\n cout << \"its an idempotent matrix\";\n else\n cout << \"its not an idempotent matrix\";\n return 0;\n}"
},
{
"code": null,
"e": 3539,
"s": 3514,
"text": "its an idempotent matrix"
}
] |
Check if user inputted string is in the array in JavaScript
|
We are required to write a JavaScript program that provides the user an input to enter a string value.
The program should then check the input value against some hard-coded array values. Our program should print true to the screen if the input string value is included in the array, false otherwise.
The code for this will be −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>CHECK EXISTENCE</title>
</head>
<body>
<script>
const arr = ['arsenal', 'chelsea', 'everton', 'fulham',
'swansea'];
const checkExistence = () => {
const userInput = document.getElementById("input").value;
const exists = arr.includes(userInput);
document.getElementById('result').innerText = exists;
};
</script>
<input type="text" id="input">
<button onclick="checkExistence()">Check</button>
<p id='result'></p>
</body>
</html>
And the output on the screen will be −
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "We are required to write a JavaScript program that provides the user an input to enter a string value."
},
{
"code": null,
"e": 1362,
"s": 1165,
"text": "The program should then check the input value against some hard-coded array values. Our program should print true to the screen if the input string value is included in the array, false otherwise."
},
{
"code": null,
"e": 1390,
"s": 1362,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2006,
"s": 1390,
"text": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>CHECK EXISTENCE</title>\n</head>\n<body>\n <script>\n const arr = ['arsenal', 'chelsea', 'everton', 'fulham',\n 'swansea'];\n const checkExistence = () => {\n const userInput = document.getElementById(\"input\").value;\n const exists = arr.includes(userInput);\n document.getElementById('result').innerText = exists;\n };\n </script>\n <input type=\"text\" id=\"input\">\n <button onclick=\"checkExistence()\">Check</button>\n <p id='result'></p>\n</body>\n</html>"
},
{
"code": null,
"e": 2045,
"s": 2006,
"text": "And the output on the screen will be −"
}
] |
How to convert a PyTorch DataParallel project to use DistributedDataParallel | by Omri Bar | Towards Data Science
|
Many posts discuss the differences between PyTorch DataParallel and DistributedDataParallel and why it is best practice to use DistributedDataParallel.
PyTorch documentation summarizes this as:
“DataParallel is usually slower than DistributedDataParallel even on a single machine due to GIL contention across threads, per-iteration replicated model, and additional overhead introduced by scattering inputs and gathering outputs.”
But the truth is that for development and prototyping, when working on a new project, or when building on top of an existing GitHub repository [which already uses DataParallel], it is simpler to use the DataParallel version out-of-the-box, especially when using a single server [that has one or several GPUs]. The most prominent advantage is that it is easier to debug with DataParallel.
Still, there will come the point where you would like to convert your existing DataParallel project to the big league and use DistributedDataParallel — this is apparently not trivial as it should be.
So in this post, I will not discuss further the advantages and disadvantages of each of the methods but rather focus on the practical aspects of converting an existing project, implemented with DataParallel, into a DistributedDataParallel project.
I’ll try to describe the different pieces as general as possible, but of course, your use case is unique 😃 and might require careful and specific adjustments based on how your implementation and code look like.
Let’s go...
The first step is the wrapper. DataParallel uses single-process with multi-thread, but DistributedDataParallel is multi-process by design, so the first thing we should do is to wrap the entire code — our main function — using a multi-process wrapper.
To do so, we are going to use a wrapper provided by FAIR in the Detectron2 repository. We will also need the comm file, which gives some nice functionality for handling distribution resources.
The function that we need to run is called launch(). Let’s review the input parameters:
We need to provide it with the number of machines we are using, for this post we will use a single machine with four GPUs, so num_machines=1 and num_gpus_per_machine=4. The machine_rank is used to specify the number [or the index] of the machine when using more than one machine, for our example machine_rank=0. dist_url is used to provide the master machine IP address when using several machines in distributed training, but since we only use one we can use dist_url=“auto”, which will use the localhost as IP and a free port. The main_func variable provides the main functionality of our code, this should be the main function used until now to run your flow in the DataParallel case. Finally, we can provide the args variable, these are all the input arguments to our main_func function.
Under the hood, the launch function will spin multiple processes using the torch multiprocessing module [torch.multiprocessing] and the spawn function, which will start the processes as new child processes — one for each GPU.
It is important to note that after running the launch function the exact same code will run in each child process simultaneously. So all pre-setup code, that needs to run only once at the beginning, should be called before running the launch function. For example, connecting to your experiments manager application, getting arguments from a config file that should be passed to all processes in advance, syncing data to the local server, etc.
Now that we have a working wrapper we can adjust our model. We need to “convert” our model, which was initialized on the CPU, to a DistributedDataParallel GPU model.
If in the DataParallel case we needed to wrap our model with:
model = torch.nn.DataParallel(model)
In the distributed case we will wrap the model with the DistributedDataParallel class, and this call will be done by each one of the processes independently. So, we first need to figure out what is the “rank” of our current process [rank is basically our GPU index], copy the model from the CPU to that specific GPU, and set it up as a DistributedDataParallel model:
The broadcast_buffers is an important parameter, it means whether or not to sync variables that are statistics-based between GPUs during training, such as the mean and variance of BatchNorm layers.
So we have the main wrapper and a model, next we need to adjust the data loading part.
In the DataParalle case, we have a single batch of size N, and during the forward pass it is automatically scattered evenly across our 4 GPUs, providing each GPU with its minibatch of size N/4. Now in the Distributed case, we need each GPU process to read only the samples relevant to its mini-batch out of the full samples batch. This is done with PyTorch DistributedSampler:
The sampler splits the samples based on the number of processes we have and provides each process with the relevant sample indexes for his minibatch. After initializing the sampler, we need to provide the DataLoader class with this sampler instance and set its shuffle parameter to False. We will also need to call the sampler’s set_epoch(epoch) function as part of our epoch for-loop to get a different order of training samples in each epoch.
At this point, we basically have the three main components: a multiprocess wrapper, a model defined as a Distributed type, and a way to handle the data loading part. Next, we will review other important adjustments we can make in our code related to logging, reporting, and metrics calculation.
As all processes run the same code, using prints and a logger to report to the console [or a file] will repeatedly cause the same prints to be written. Although some might be important and relevant to report for each process, many are not, and we can use the following command to report a message only once in the main process [which is our rank 0 process]:
if comm.is_main_process(): print(“something that is printed only once”)
This trick is also valuable when reporting metrics to an external tool or when saving the model weights. You can use it to make sure an action only happens once in the flow by the main process.
Now, what about the metrics?
Using the PyTorch DistributedDataParallel module, you don’t need to manage and “collect” [gather] the loss values from all processes to run the backward step, the loss.backward() will do it for you under the hood, and since it runs for each process, it will provide the same gradients correction to all model replications on all GPUs.
However, this is only relevant to the loss value that is used inside the backward pass. In order to report the actual loss values or their average, you will need to collect the loss per process and have the main process report their average:
loss = criterion(outputs, labels)...all_loss = comm.gather(loss)if comm.is_main_process(): report_avg(all_loss)
Now, all_loss has the loss values of all processes, and the main process can average them, accumulate them, and report what is needed.
Note that the gather command requires all processes to provide their values to the main process, slowing down the entire flow. A better way to handle this is to have each process collect and store its loss values and run the gather every number of iterations or at the end of an epoch.
Additional important comments:
A valuable trick is the ability to sync all processes at specific points in the code and force them to wait for each other. This can be the cure for the following scenario: the flow runs and for some reason just hangs. Looking at nvidia-smi you see that all GPUs are at 100% utilization while one GPU is at 0%. This is one example of a frustrating case that occurs when working with the distribution mode and might happen because the main GPU is processing something that takes more time, like saving and uploading your model. Forcing the processes to sync at some specific points in the flow might help, for instance, when going from the evaluation step back to the next training epoch. This can be done with a barrier function by using the following command: comm.synchronize()This function puts a barrier in the code, forcing all processes to wait for the rest to arrive and pass that point together 😃.
The DistributedDataParallel module transfers information between the processes, for this to happen PyTorch serializes the variables that are part of the data loader class. This requires that such variables are valid for serialization. The error is pretty informative, so you know when you are facing such an issue. I had issues with serializing part of my logger instances since it had a filter that uses a different class which was not suitable for serialization.
That’s it. I hope this guide will help you transition from a PyTorch DataParallel implementation to a DistributedDataParallel mechanism and enjoy the benefits and speed it provides.
Further reading:
https://pytorch.org/tutorials/beginner/dist_overview.html
https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel
PyTorch Distributed: Experiences on Accelerating Data Parallel Training [https://arxiv.org/pdf/2006.15704.pdf]
|
[
{
"code": null,
"e": 324,
"s": 172,
"text": "Many posts discuss the differences between PyTorch DataParallel and DistributedDataParallel and why it is best practice to use DistributedDataParallel."
},
{
"code": null,
"e": 366,
"s": 324,
"text": "PyTorch documentation summarizes this as:"
},
{
"code": null,
"e": 602,
"s": 366,
"text": "“DataParallel is usually slower than DistributedDataParallel even on a single machine due to GIL contention across threads, per-iteration replicated model, and additional overhead introduced by scattering inputs and gathering outputs.”"
},
{
"code": null,
"e": 990,
"s": 602,
"text": "But the truth is that for development and prototyping, when working on a new project, or when building on top of an existing GitHub repository [which already uses DataParallel], it is simpler to use the DataParallel version out-of-the-box, especially when using a single server [that has one or several GPUs]. The most prominent advantage is that it is easier to debug with DataParallel."
},
{
"code": null,
"e": 1190,
"s": 990,
"text": "Still, there will come the point where you would like to convert your existing DataParallel project to the big league and use DistributedDataParallel — this is apparently not trivial as it should be."
},
{
"code": null,
"e": 1438,
"s": 1190,
"text": "So in this post, I will not discuss further the advantages and disadvantages of each of the methods but rather focus on the practical aspects of converting an existing project, implemented with DataParallel, into a DistributedDataParallel project."
},
{
"code": null,
"e": 1649,
"s": 1438,
"text": "I’ll try to describe the different pieces as general as possible, but of course, your use case is unique 😃 and might require careful and specific adjustments based on how your implementation and code look like."
},
{
"code": null,
"e": 1661,
"s": 1649,
"text": "Let’s go..."
},
{
"code": null,
"e": 1912,
"s": 1661,
"text": "The first step is the wrapper. DataParallel uses single-process with multi-thread, but DistributedDataParallel is multi-process by design, so the first thing we should do is to wrap the entire code — our main function — using a multi-process wrapper."
},
{
"code": null,
"e": 2105,
"s": 1912,
"text": "To do so, we are going to use a wrapper provided by FAIR in the Detectron2 repository. We will also need the comm file, which gives some nice functionality for handling distribution resources."
},
{
"code": null,
"e": 2193,
"s": 2105,
"text": "The function that we need to run is called launch(). Let’s review the input parameters:"
},
{
"code": null,
"e": 2985,
"s": 2193,
"text": "We need to provide it with the number of machines we are using, for this post we will use a single machine with four GPUs, so num_machines=1 and num_gpus_per_machine=4. The machine_rank is used to specify the number [or the index] of the machine when using more than one machine, for our example machine_rank=0. dist_url is used to provide the master machine IP address when using several machines in distributed training, but since we only use one we can use dist_url=“auto”, which will use the localhost as IP and a free port. The main_func variable provides the main functionality of our code, this should be the main function used until now to run your flow in the DataParallel case. Finally, we can provide the args variable, these are all the input arguments to our main_func function."
},
{
"code": null,
"e": 3211,
"s": 2985,
"text": "Under the hood, the launch function will spin multiple processes using the torch multiprocessing module [torch.multiprocessing] and the spawn function, which will start the processes as new child processes — one for each GPU."
},
{
"code": null,
"e": 3655,
"s": 3211,
"text": "It is important to note that after running the launch function the exact same code will run in each child process simultaneously. So all pre-setup code, that needs to run only once at the beginning, should be called before running the launch function. For example, connecting to your experiments manager application, getting arguments from a config file that should be passed to all processes in advance, syncing data to the local server, etc."
},
{
"code": null,
"e": 3821,
"s": 3655,
"text": "Now that we have a working wrapper we can adjust our model. We need to “convert” our model, which was initialized on the CPU, to a DistributedDataParallel GPU model."
},
{
"code": null,
"e": 3883,
"s": 3821,
"text": "If in the DataParallel case we needed to wrap our model with:"
},
{
"code": null,
"e": 3920,
"s": 3883,
"text": "model = torch.nn.DataParallel(model)"
},
{
"code": null,
"e": 4287,
"s": 3920,
"text": "In the distributed case we will wrap the model with the DistributedDataParallel class, and this call will be done by each one of the processes independently. So, we first need to figure out what is the “rank” of our current process [rank is basically our GPU index], copy the model from the CPU to that specific GPU, and set it up as a DistributedDataParallel model:"
},
{
"code": null,
"e": 4485,
"s": 4287,
"text": "The broadcast_buffers is an important parameter, it means whether or not to sync variables that are statistics-based between GPUs during training, such as the mean and variance of BatchNorm layers."
},
{
"code": null,
"e": 4572,
"s": 4485,
"text": "So we have the main wrapper and a model, next we need to adjust the data loading part."
},
{
"code": null,
"e": 4949,
"s": 4572,
"text": "In the DataParalle case, we have a single batch of size N, and during the forward pass it is automatically scattered evenly across our 4 GPUs, providing each GPU with its minibatch of size N/4. Now in the Distributed case, we need each GPU process to read only the samples relevant to its mini-batch out of the full samples batch. This is done with PyTorch DistributedSampler:"
},
{
"code": null,
"e": 5394,
"s": 4949,
"text": "The sampler splits the samples based on the number of processes we have and provides each process with the relevant sample indexes for his minibatch. After initializing the sampler, we need to provide the DataLoader class with this sampler instance and set its shuffle parameter to False. We will also need to call the sampler’s set_epoch(epoch) function as part of our epoch for-loop to get a different order of training samples in each epoch."
},
{
"code": null,
"e": 5689,
"s": 5394,
"text": "At this point, we basically have the three main components: a multiprocess wrapper, a model defined as a Distributed type, and a way to handle the data loading part. Next, we will review other important adjustments we can make in our code related to logging, reporting, and metrics calculation."
},
{
"code": null,
"e": 6047,
"s": 5689,
"text": "As all processes run the same code, using prints and a logger to report to the console [or a file] will repeatedly cause the same prints to be written. Although some might be important and relevant to report for each process, many are not, and we can use the following command to report a message only once in the main process [which is our rank 0 process]:"
},
{
"code": null,
"e": 6122,
"s": 6047,
"text": "if comm.is_main_process(): print(“something that is printed only once”)"
},
{
"code": null,
"e": 6316,
"s": 6122,
"text": "This trick is also valuable when reporting metrics to an external tool or when saving the model weights. You can use it to make sure an action only happens once in the flow by the main process."
},
{
"code": null,
"e": 6345,
"s": 6316,
"text": "Now, what about the metrics?"
},
{
"code": null,
"e": 6680,
"s": 6345,
"text": "Using the PyTorch DistributedDataParallel module, you don’t need to manage and “collect” [gather] the loss values from all processes to run the backward step, the loss.backward() will do it for you under the hood, and since it runs for each process, it will provide the same gradients correction to all model replications on all GPUs."
},
{
"code": null,
"e": 6922,
"s": 6680,
"text": "However, this is only relevant to the loss value that is used inside the backward pass. In order to report the actual loss values or their average, you will need to collect the loss per process and have the main process report their average:"
},
{
"code": null,
"e": 7037,
"s": 6922,
"text": "loss = criterion(outputs, labels)...all_loss = comm.gather(loss)if comm.is_main_process(): report_avg(all_loss)"
},
{
"code": null,
"e": 7172,
"s": 7037,
"text": "Now, all_loss has the loss values of all processes, and the main process can average them, accumulate them, and report what is needed."
},
{
"code": null,
"e": 7458,
"s": 7172,
"text": "Note that the gather command requires all processes to provide their values to the main process, slowing down the entire flow. A better way to handle this is to have each process collect and store its loss values and run the gather every number of iterations or at the end of an epoch."
},
{
"code": null,
"e": 7489,
"s": 7458,
"text": "Additional important comments:"
},
{
"code": null,
"e": 8395,
"s": 7489,
"text": "A valuable trick is the ability to sync all processes at specific points in the code and force them to wait for each other. This can be the cure for the following scenario: the flow runs and for some reason just hangs. Looking at nvidia-smi you see that all GPUs are at 100% utilization while one GPU is at 0%. This is one example of a frustrating case that occurs when working with the distribution mode and might happen because the main GPU is processing something that takes more time, like saving and uploading your model. Forcing the processes to sync at some specific points in the flow might help, for instance, when going from the evaluation step back to the next training epoch. This can be done with a barrier function by using the following command: comm.synchronize()This function puts a barrier in the code, forcing all processes to wait for the rest to arrive and pass that point together 😃."
},
{
"code": null,
"e": 8860,
"s": 8395,
"text": "The DistributedDataParallel module transfers information between the processes, for this to happen PyTorch serializes the variables that are part of the data loader class. This requires that such variables are valid for serialization. The error is pretty informative, so you know when you are facing such an issue. I had issues with serializing part of my logger instances since it had a filter that uses a different class which was not suitable for serialization."
},
{
"code": null,
"e": 9042,
"s": 8860,
"text": "That’s it. I hope this guide will help you transition from a PyTorch DataParallel implementation to a DistributedDataParallel mechanism and enjoy the benefits and speed it provides."
},
{
"code": null,
"e": 9059,
"s": 9042,
"text": "Further reading:"
},
{
"code": null,
"e": 9117,
"s": 9059,
"text": "https://pytorch.org/tutorials/beginner/dist_overview.html"
},
{
"code": null,
"e": 9238,
"s": 9117,
"text": "https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel"
}
] |
Java Program to Get the TreeSet Element By Index - GeeksforGeeks
|
28 Dec, 2020
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided.
We have the element in the TreeSet and we want to print the Element from the TreeSet using the index.
TreeSet<Integer> set = new TreeSet();
set.add(2);
set.add(3);
set.add(9);
set.add(5);
// TreeSet always used to get prevent
// from the duplicates in the increasing order
Set Contains -> [2,3,5,9]
So, we have the Element in set -> [2, 3, 5, 9] .Now we cannot access the Element Directly So to access the Element we need to convert the set to array or list to access the element.
So there are many ways to get the element by index:
Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one.Converting TreeSet to array using .toArray() method.Converting TreeSet to ArrayList.
Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one.
Converting TreeSet to array using .toArray() method.
Converting TreeSet to ArrayList.
Method 1: Simply converting the TreeSet to array
We simply create an empty array.
We traverse the given set and one by one add elements to the array
Java
// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); int arr[] = new int[n]; int i = 0; // using for-each loop to traverse through // the set and adding each element to array for (int ele : s) arr[i++] = ele; for(int res : arr) { System.out.print(res+ " "); } System.out.println(); // getting the element at index 2 System.out.print(arr[2]); }}
2 3 5 9
5
Method 2: Using .toArray() Method
First converting the set to array using .toArray() method.
And accessing the Element from the Array by index.
Java
// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); Integer arr[] = new Integer[n]; // .toArray() method converts the // set s to array here arr = s.toArray(arr); for(int ele : arr) { System.out.print(ele+" "); } System.out.println(); // getting the element at index 2 System.out.print(arr[2]); }}
2 3 5 9
5
Method 3: Converting to ArrayList
First Converting the set to list by directly using the constructor.
And then getting the Element from the List through index
Java
// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); // this constructor converts directly // the whole TreeSet to list List<Integer> list= new ArrayList<Integer>(s); for(int ele : list){ System.out.print(ele+" "); } System.out.println(); // getting the element at index 2 System.out.print(list.get(2)); }}
2 3 5 9
5
java-treeset
Picked
Technical Scripter 2020
Java
JavaScript
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24198,
"s": 23948,
"text": "TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided."
},
{
"code": null,
"e": 24301,
"s": 24198,
"text": "We have the element in the TreeSet and we want to print the Element from the TreeSet using the index. "
},
{
"code": null,
"e": 24500,
"s": 24301,
"text": "TreeSet<Integer> set = new TreeSet();\nset.add(2);\nset.add(3);\nset.add(9);\nset.add(5);\n\n// TreeSet always used to get prevent\n// from the duplicates in the increasing order\nSet Contains -> [2,3,5,9] "
},
{
"code": null,
"e": 24682,
"s": 24500,
"text": "So, we have the Element in set -> [2, 3, 5, 9] .Now we cannot access the Element Directly So to access the Element we need to convert the set to array or list to access the element."
},
{
"code": null,
"e": 24734,
"s": 24682,
"text": "So there are many ways to get the element by index:"
},
{
"code": null,
"e": 24930,
"s": 24734,
"text": "Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one.Converting TreeSet to array using .toArray() method.Converting TreeSet to ArrayList."
},
{
"code": null,
"e": 25042,
"s": 24930,
"text": "Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one."
},
{
"code": null,
"e": 25095,
"s": 25042,
"text": "Converting TreeSet to array using .toArray() method."
},
{
"code": null,
"e": 25128,
"s": 25095,
"text": "Converting TreeSet to ArrayList."
},
{
"code": null,
"e": 25177,
"s": 25128,
"text": "Method 1: Simply converting the TreeSet to array"
},
{
"code": null,
"e": 25211,
"s": 25177,
"text": "We simply create an empty array. "
},
{
"code": null,
"e": 25278,
"s": 25211,
"text": "We traverse the given set and one by one add elements to the array"
},
{
"code": null,
"e": 25283,
"s": 25278,
"text": "Java"
},
{
"code": "// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); int arr[] = new int[n]; int i = 0; // using for-each loop to traverse through // the set and adding each element to array for (int ele : s) arr[i++] = ele; for(int res : arr) { System.out.print(res+ \" \"); } System.out.println(); // getting the element at index 2 System.out.print(arr[2]); }}",
"e": 26031,
"s": 25283,
"text": null
},
{
"code": null,
"e": 26042,
"s": 26031,
"text": "2 3 5 9 \n5"
},
{
"code": null,
"e": 26076,
"s": 26042,
"text": "Method 2: Using .toArray() Method"
},
{
"code": null,
"e": 26135,
"s": 26076,
"text": "First converting the set to array using .toArray() method."
},
{
"code": null,
"e": 26186,
"s": 26135,
"text": "And accessing the Element from the Array by index."
},
{
"code": null,
"e": 26191,
"s": 26186,
"text": "Java"
},
{
"code": "// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); Integer arr[] = new Integer[n]; // .toArray() method converts the // set s to array here arr = s.toArray(arr); for(int ele : arr) { System.out.print(ele+\" \"); } System.out.println(); // getting the element at index 2 System.out.print(arr[2]); }}",
"e": 26872,
"s": 26191,
"text": null
},
{
"code": null,
"e": 26883,
"s": 26872,
"text": "2 3 5 9 \n5"
},
{
"code": null,
"e": 26917,
"s": 26883,
"text": "Method 3: Converting to ArrayList"
},
{
"code": null,
"e": 26985,
"s": 26917,
"text": "First Converting the set to list by directly using the constructor."
},
{
"code": null,
"e": 27042,
"s": 26985,
"text": "And then getting the Element from the List through index"
},
{
"code": null,
"e": 27047,
"s": 27042,
"text": "Java"
},
{
"code": "// Java Program to Get the TreeSet Element By Index import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { TreeSet<Integer> s = new TreeSet<Integer>(); s.add(2); s.add(3); s.add(9); s.add(5); int n = s.size(); // this constructor converts directly // the whole TreeSet to list List<Integer> list= new ArrayList<Integer>(s); for(int ele : list){ System.out.print(ele+\" \"); } System.out.println(); // getting the element at index 2 System.out.print(list.get(2)); }}",
"e": 27725,
"s": 27047,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27725,
"text": "2 3 5 9 \n5"
},
{
"code": null,
"e": 27749,
"s": 27736,
"text": "java-treeset"
},
{
"code": null,
"e": 27756,
"s": 27749,
"text": "Picked"
},
{
"code": null,
"e": 27780,
"s": 27756,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27785,
"s": 27780,
"text": "Java"
},
{
"code": null,
"e": 27796,
"s": 27785,
"text": "JavaScript"
},
{
"code": null,
"e": 27815,
"s": 27796,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27820,
"s": 27815,
"text": "Java"
},
{
"code": null,
"e": 27918,
"s": 27820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27927,
"s": 27918,
"text": "Comments"
},
{
"code": null,
"e": 27940,
"s": 27927,
"text": "Old Comments"
},
{
"code": null,
"e": 27986,
"s": 27940,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28007,
"s": 27986,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28022,
"s": 28007,
"text": "Stream In Java"
},
{
"code": null,
"e": 28039,
"s": 28022,
"text": "Generics in Java"
},
{
"code": null,
"e": 28058,
"s": 28039,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28103,
"s": 28058,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28172,
"s": 28103,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 28233,
"s": 28172,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28305,
"s": 28233,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Setting Up Proxy Connection to a System in Java
|
28 Apr, 2021
In today’s networking environments, categorically corporate ones, application developers have to deal with proxies virtually as often as system administrators. In some cases the application should utilize the system default settings, in other cases, it will be additive to have very tight control over what goes through which proxy, and, somewhere in the middle, most applications will be ecstatic to delegate the decision to their users by providing them with a GUI to set the proxy settings, as is the case in most browsers.
Proxy servers act as interfaces between client applications and other servers. In an enterprise setting, we often use them to help provide control over the content that users consume, usually across network boundaries.
Approaches:
We will figure out two ways by which we can connect across proxy servers in java which are as follows:
Legacy approach that is JVM-wide and configured with system properties.Using Proxy class which provides more control by permitting configuration on the basis of each connection.
Legacy approach that is JVM-wide and configured with system properties.
Using Proxy class which provides more control by permitting configuration on the basis of each connection.
Method 1: Using a Global Setting
Java exhibits a set of system properties that can be used to set up the JVM-wide behavior. This “universal” approach is often the simplest to implement if it is appropriate for the use case. We can set the required properties from the command line during the invocation of the JVM. Alternatively, we can also define them using System.setProperty() at runtime. Here’s how to define them using the command line as shown below:
2.1. Set via Command Line Arguments
We can define proxies at the command line bypassing the parameters as system properties:
java -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8080 com.geeksforgeeks.networking.proxies.CommandLineProxyDemo
When starting a process that way, we can just use openConnection() on the URL with no extra work:
URL url = new URL(RESOURCE_URL);
URLConnection con = url.openConnection();
2.3 Set Proxy Using the System.setProperty() method
If there are problems when using the command line, there is another way to do this using the System.setProperty() method. To set up a proxy.
System.setProperty(“http.proxyHost”, “127.0.0.1”);
System.setProperty(“http.proxyPort”, “8080”);
URL url = new URL(RESOURCE_URL);
URLConnection con = url.openConnection();
// ...
If we then manually disable the relevant system properties, then the proxy will not be used anymore:
System.setProperty(“http.proxyHost”, null);
Now with this there do comes limitations of global configuration which is as described further.
The global configuration approach is the easiest way to define the proxy, but there are certain limitations to this approach.
This approach provides the implementation on the JVM-wide, so the settings define for a particular protocol are active for the life of the JVM or until we unset them manually.
Note: To get over this limitation, it may be attractive to flip the settings on and off, if needed. But, it would be necessary to ensure the measures to protect against concurrency issues in a multi-threaded program.
So, as an alternative, the Proxy API is more efficient and provides more control over proxy configuration. As an alternative, the Proxy API provides more granular control over proxy configuration. This gives out birth to another approach that via Proxy API
Method 2: Using the Proxy API
The Proxy class gives us a flexible way to configure proxies on a per-connection basis. If there are any existing JVM-wide proxy settings, connection-based proxy settings using the Proxy class will override them. Here are three types of proxies that we can define by Proxy Type:
HTTP is a proxy using the HTTP protocolSOCKS is a proxy using the SOCKS protocolDIRECT is an explicitly configured direct connection without a proxy
HTTP is a proxy using the HTTP protocol
SOCKS is a proxy using the SOCKS protocol
DIRECT is an explicitly configured direct connection without a proxy
(A) Using an HTTP Proxy
To use an HTTP proxy, we first wrap a SocketAddress instance with a Proxy and type of Proxy.Type.HTTP. Next, we simply pass the Proxy instance to URLConnection.openConnection():
URL weburl = new URL(URL_STRING);
Proxy webProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(“127.0.0.1”, 8080));
HttpURLConnection webProxyConnection = (HttpURLConnection) weburl.openConnection(webProxy);
Now, we’ll connect to URL_STRING but then route that connection through a proxy server hosted at 127.0.0.1:8080.
(B) Using a DIRECT Proxy
We may have a requirement to connect directly to a host. In this case, we can explicitly bypass a proxy that may be configured globally by using the static Proxy.NO_PROXY instance. Under the covers, the API constructs a new instance of Proxy for us, using Proxy.Type.DIRECT as the type:
HttpURLConnection directConnection = (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY);
(C) Using a SOCKS Proxy
The Socks proxy works similarly to the HTTP variant while dealing with URLConnection. In Socks proxy, first, we wrap a SocketAddress instance with a Proxy using the Proxy.Type.SOCKS type. After that, the Proxy instance is passed to URLConnection.openConnection.
Proxy socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(“127.0.0.1”, 1080));
HttpURLConnection socksConnection = (HttpURLConnection) weburl.openConnection(socksProxy);
It’s also possible to use a SOCKS proxy when connecting to a TCP socket. First, we use the Proxy instance to construct a Socket. Afterward, we pass the destination SocketAddress instance to Socket.connect() as follows:
Socket proxySocket = new Socket(socksProxy);
InetSocketAddress socketHost = new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT);
proxySocket.connect(socketHost);
Example:
Java
// Java Program to Create a Simple Proxy Server // Importing input output classesimport java.io.*;// Importingimport java.net.*; public class SimpleProxyServer { public static void main(String[] args) throws IOException { try { String host = "your Proxy Server"; int remoteport = 100; int localport = 111; // Print a start-up message System.out.println("Starting proxy for " + host + ":" + remoteport + " on port " + localport); // And start running the server runServer(host, remoteport, localport); // never returns } catch (Exception e) { System.err.println(e); } } /** * runs a single-threaded proxy server on * the specified local port. It never returns. */ public static void runServer(String host, int remoteport, int localport) throws IOException { // Create a ServerSocket to listen for connections // with ServerSocket ss = new ServerSocket(localport); final byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (true) { Socket client = null, server = null; try { // Wait for a connection on the local port client = ss.accept(); final InputStream streamFromClient = client.getInputStream(); final OutputStream streamToClient = client.getOutputStream(); // Make a connection to the real server. // If we cannot connect to the server, send // an error to the client, disconnect, and // continue waiting for connections. try { server = new Socket(host, remoteport); } catch (IOException e) { PrintWriter out = new PrintWriter(streamToClient); out.print( "Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n"); out.flush(); client.close(); continue; } // Get server streams. final InputStream streamFromServer = server.getInputStream(); final OutputStream streamToServer = server.getOutputStream(); // a thread to read the client's requests // and pass them to the server. A separate // thread for asynchronous. Thread t = new Thread() { public void run() { int bytesRead; try { while ((bytesRead = streamFromClient.read( request)) != -1) { streamToServer.write( request, 0, bytesRead); streamToServer.flush(); } } catch (IOException e) { } // the client closed the connection // to us, so close our connection to // the server. try { streamToServer.close(); } catch (IOException e) { } } }; // Start the client-to-server request thread // running t.start(); // Read the server's responses // and pass them back to the client. int bytesRead; try { while ((bytesRead = streamFromServer.read(reply)) != -1) { streamToClient.write(reply, 0, bytesRead); streamToClient.flush(); } } catch (IOException e) { } // The server closed its connection to us, // so we close our connection to our client. streamToClient.close(); } catch (IOException e) { System.err.println(e); } finally { try { if (server != null) server.close(); if (client != null) client.close(); } catch (IOException e) { } } } }}
Output:
Conclusion: As per the output we peek out how to work with proxy servers in core Java. First, we looked at the older, more global style of connecting through proxy servers using system properties. Then, we saw how to use the Proxy class, which provides fine-grained control when connecting through proxy servers.
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 555,
"s": 28,
"text": "In today’s networking environments, categorically corporate ones, application developers have to deal with proxies virtually as often as system administrators. In some cases the application should utilize the system default settings, in other cases, it will be additive to have very tight control over what goes through which proxy, and, somewhere in the middle, most applications will be ecstatic to delegate the decision to their users by providing them with a GUI to set the proxy settings, as is the case in most browsers."
},
{
"code": null,
"e": 774,
"s": 555,
"text": "Proxy servers act as interfaces between client applications and other servers. In an enterprise setting, we often use them to help provide control over the content that users consume, usually across network boundaries."
},
{
"code": null,
"e": 786,
"s": 774,
"text": "Approaches:"
},
{
"code": null,
"e": 889,
"s": 786,
"text": "We will figure out two ways by which we can connect across proxy servers in java which are as follows:"
},
{
"code": null,
"e": 1067,
"s": 889,
"text": "Legacy approach that is JVM-wide and configured with system properties.Using Proxy class which provides more control by permitting configuration on the basis of each connection."
},
{
"code": null,
"e": 1139,
"s": 1067,
"text": "Legacy approach that is JVM-wide and configured with system properties."
},
{
"code": null,
"e": 1246,
"s": 1139,
"text": "Using Proxy class which provides more control by permitting configuration on the basis of each connection."
},
{
"code": null,
"e": 1279,
"s": 1246,
"text": "Method 1: Using a Global Setting"
},
{
"code": null,
"e": 1704,
"s": 1279,
"text": "Java exhibits a set of system properties that can be used to set up the JVM-wide behavior. This “universal” approach is often the simplest to implement if it is appropriate for the use case. We can set the required properties from the command line during the invocation of the JVM. Alternatively, we can also define them using System.setProperty() at runtime. Here’s how to define them using the command line as shown below:"
},
{
"code": null,
"e": 1740,
"s": 1704,
"text": "2.1. Set via Command Line Arguments"
},
{
"code": null,
"e": 1829,
"s": 1740,
"text": "We can define proxies at the command line bypassing the parameters as system properties:"
},
{
"code": null,
"e": 1941,
"s": 1829,
"text": "java -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8080 com.geeksforgeeks.networking.proxies.CommandLineProxyDemo"
},
{
"code": null,
"e": 2039,
"s": 1941,
"text": "When starting a process that way, we can just use openConnection() on the URL with no extra work:"
},
{
"code": null,
"e": 2072,
"s": 2039,
"text": "URL url = new URL(RESOURCE_URL);"
},
{
"code": null,
"e": 2114,
"s": 2072,
"text": "URLConnection con = url.openConnection();"
},
{
"code": null,
"e": 2166,
"s": 2114,
"text": "2.3 Set Proxy Using the System.setProperty() method"
},
{
"code": null,
"e": 2307,
"s": 2166,
"text": "If there are problems when using the command line, there is another way to do this using the System.setProperty() method. To set up a proxy."
},
{
"code": null,
"e": 2360,
"s": 2307,
"text": "System.setProperty(“http.proxyHost”, “127.0.0.1”); "
},
{
"code": null,
"e": 2408,
"s": 2360,
"text": "System.setProperty(“http.proxyPort”, “8080”); "
},
{
"code": null,
"e": 2443,
"s": 2408,
"text": "URL url = new URL(RESOURCE_URL); "
},
{
"code": null,
"e": 2487,
"s": 2443,
"text": "URLConnection con = url.openConnection(); "
},
{
"code": null,
"e": 2496,
"s": 2487,
"text": "// ... "
},
{
"code": null,
"e": 2597,
"s": 2496,
"text": "If we then manually disable the relevant system properties, then the proxy will not be used anymore:"
},
{
"code": null,
"e": 2642,
"s": 2597,
"text": "System.setProperty(“http.proxyHost”, null); "
},
{
"code": null,
"e": 2738,
"s": 2642,
"text": "Now with this there do comes limitations of global configuration which is as described further."
},
{
"code": null,
"e": 2864,
"s": 2738,
"text": "The global configuration approach is the easiest way to define the proxy, but there are certain limitations to this approach."
},
{
"code": null,
"e": 3040,
"s": 2864,
"text": "This approach provides the implementation on the JVM-wide, so the settings define for a particular protocol are active for the life of the JVM or until we unset them manually."
},
{
"code": null,
"e": 3257,
"s": 3040,
"text": "Note: To get over this limitation, it may be attractive to flip the settings on and off, if needed. But, it would be necessary to ensure the measures to protect against concurrency issues in a multi-threaded program."
},
{
"code": null,
"e": 3514,
"s": 3257,
"text": "So, as an alternative, the Proxy API is more efficient and provides more control over proxy configuration. As an alternative, the Proxy API provides more granular control over proxy configuration. This gives out birth to another approach that via Proxy API"
},
{
"code": null,
"e": 3544,
"s": 3514,
"text": "Method 2: Using the Proxy API"
},
{
"code": null,
"e": 3823,
"s": 3544,
"text": "The Proxy class gives us a flexible way to configure proxies on a per-connection basis. If there are any existing JVM-wide proxy settings, connection-based proxy settings using the Proxy class will override them. Here are three types of proxies that we can define by Proxy Type:"
},
{
"code": null,
"e": 3973,
"s": 3823,
"text": "HTTP is a proxy using the HTTP protocolSOCKS is a proxy using the SOCKS protocolDIRECT is an explicitly configured direct connection without a proxy"
},
{
"code": null,
"e": 4014,
"s": 3973,
"text": "HTTP is a proxy using the HTTP protocol"
},
{
"code": null,
"e": 4056,
"s": 4014,
"text": "SOCKS is a proxy using the SOCKS protocol"
},
{
"code": null,
"e": 4125,
"s": 4056,
"text": "DIRECT is an explicitly configured direct connection without a proxy"
},
{
"code": null,
"e": 4149,
"s": 4125,
"text": "(A) Using an HTTP Proxy"
},
{
"code": null,
"e": 4327,
"s": 4149,
"text": "To use an HTTP proxy, we first wrap a SocketAddress instance with a Proxy and type of Proxy.Type.HTTP. Next, we simply pass the Proxy instance to URLConnection.openConnection():"
},
{
"code": null,
"e": 4361,
"s": 4327,
"text": "URL weburl = new URL(URL_STRING);"
},
{
"code": null,
"e": 4448,
"s": 4361,
"text": "Proxy webProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(“127.0.0.1”, 8080));"
},
{
"code": null,
"e": 4540,
"s": 4448,
"text": "HttpURLConnection webProxyConnection = (HttpURLConnection) weburl.openConnection(webProxy);"
},
{
"code": null,
"e": 4653,
"s": 4540,
"text": "Now, we’ll connect to URL_STRING but then route that connection through a proxy server hosted at 127.0.0.1:8080."
},
{
"code": null,
"e": 4678,
"s": 4653,
"text": "(B) Using a DIRECT Proxy"
},
{
"code": null,
"e": 4965,
"s": 4678,
"text": "We may have a requirement to connect directly to a host. In this case, we can explicitly bypass a proxy that may be configured globally by using the static Proxy.NO_PROXY instance. Under the covers, the API constructs a new instance of Proxy for us, using Proxy.Type.DIRECT as the type:"
},
{
"code": null,
"e": 5062,
"s": 4965,
"text": "HttpURLConnection directConnection = (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY); "
},
{
"code": null,
"e": 5086,
"s": 5062,
"text": "(C) Using a SOCKS Proxy"
},
{
"code": null,
"e": 5348,
"s": 5086,
"text": "The Socks proxy works similarly to the HTTP variant while dealing with URLConnection. In Socks proxy, first, we wrap a SocketAddress instance with a Proxy using the Proxy.Type.SOCKS type. After that, the Proxy instance is passed to URLConnection.openConnection."
},
{
"code": null,
"e": 5439,
"s": 5348,
"text": "Proxy socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(“127.0.0.1”, 1080));"
},
{
"code": null,
"e": 5530,
"s": 5439,
"text": "HttpURLConnection socksConnection = (HttpURLConnection) weburl.openConnection(socksProxy);"
},
{
"code": null,
"e": 5749,
"s": 5530,
"text": "It’s also possible to use a SOCKS proxy when connecting to a TCP socket. First, we use the Proxy instance to construct a Socket. Afterward, we pass the destination SocketAddress instance to Socket.connect() as follows:"
},
{
"code": null,
"e": 5794,
"s": 5749,
"text": "Socket proxySocket = new Socket(socksProxy);"
},
{
"code": null,
"e": 5888,
"s": 5794,
"text": "InetSocketAddress socketHost = new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT);"
},
{
"code": null,
"e": 5921,
"s": 5888,
"text": "proxySocket.connect(socketHost);"
},
{
"code": null,
"e": 5930,
"s": 5921,
"text": "Example:"
},
{
"code": null,
"e": 5935,
"s": 5930,
"text": "Java"
},
{
"code": "// Java Program to Create a Simple Proxy Server // Importing input output classesimport java.io.*;// Importingimport java.net.*; public class SimpleProxyServer { public static void main(String[] args) throws IOException { try { String host = \"your Proxy Server\"; int remoteport = 100; int localport = 111; // Print a start-up message System.out.println(\"Starting proxy for \" + host + \":\" + remoteport + \" on port \" + localport); // And start running the server runServer(host, remoteport, localport); // never returns } catch (Exception e) { System.err.println(e); } } /** * runs a single-threaded proxy server on * the specified local port. It never returns. */ public static void runServer(String host, int remoteport, int localport) throws IOException { // Create a ServerSocket to listen for connections // with ServerSocket ss = new ServerSocket(localport); final byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (true) { Socket client = null, server = null; try { // Wait for a connection on the local port client = ss.accept(); final InputStream streamFromClient = client.getInputStream(); final OutputStream streamToClient = client.getOutputStream(); // Make a connection to the real server. // If we cannot connect to the server, send // an error to the client, disconnect, and // continue waiting for connections. try { server = new Socket(host, remoteport); } catch (IOException e) { PrintWriter out = new PrintWriter(streamToClient); out.print( \"Proxy server cannot connect to \" + host + \":\" + remoteport + \":\\n\" + e + \"\\n\"); out.flush(); client.close(); continue; } // Get server streams. final InputStream streamFromServer = server.getInputStream(); final OutputStream streamToServer = server.getOutputStream(); // a thread to read the client's requests // and pass them to the server. A separate // thread for asynchronous. Thread t = new Thread() { public void run() { int bytesRead; try { while ((bytesRead = streamFromClient.read( request)) != -1) { streamToServer.write( request, 0, bytesRead); streamToServer.flush(); } } catch (IOException e) { } // the client closed the connection // to us, so close our connection to // the server. try { streamToServer.close(); } catch (IOException e) { } } }; // Start the client-to-server request thread // running t.start(); // Read the server's responses // and pass them back to the client. int bytesRead; try { while ((bytesRead = streamFromServer.read(reply)) != -1) { streamToClient.write(reply, 0, bytesRead); streamToClient.flush(); } } catch (IOException e) { } // The server closed its connection to us, // so we close our connection to our client. streamToClient.close(); } catch (IOException e) { System.err.println(e); } finally { try { if (server != null) server.close(); if (client != null) client.close(); } catch (IOException e) { } } } }}",
"e": 10906,
"s": 5935,
"text": null
},
{
"code": null,
"e": 10914,
"s": 10906,
"text": "Output:"
},
{
"code": null,
"e": 11227,
"s": 10914,
"text": "Conclusion: As per the output we peek out how to work with proxy servers in core Java. First, we looked at the older, more global style of connecting through proxy servers using system properties. Then, we saw how to use the Proxy class, which provides fine-grained control when connecting through proxy servers."
},
{
"code": null,
"e": 11234,
"s": 11227,
"text": "Picked"
},
{
"code": null,
"e": 11239,
"s": 11234,
"text": "Java"
},
{
"code": null,
"e": 11253,
"s": 11239,
"text": "Java Programs"
},
{
"code": null,
"e": 11258,
"s": 11253,
"text": "Java"
},
{
"code": null,
"e": 11356,
"s": 11258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11371,
"s": 11356,
"text": "Stream In Java"
},
{
"code": null,
"e": 11392,
"s": 11371,
"text": "Introduction to Java"
},
{
"code": null,
"e": 11413,
"s": 11392,
"text": "Constructors in Java"
},
{
"code": null,
"e": 11432,
"s": 11413,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 11449,
"s": 11432,
"text": "Generics in Java"
},
{
"code": null,
"e": 11475,
"s": 11449,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 11509,
"s": 11475,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 11556,
"s": 11509,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 11594,
"s": 11556,
"text": "Factory method design pattern in Java"
}
] |
How to remove empty tags using BeautifulSoup in Python?
|
26 Nov, 2020
Prerequisite: Requests, BeautifulSoup, strip
The task is to write a program that removes the empty tag from HTML code. In Beautiful Soup there is no in-built method to remove tags that has no content.
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: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Get HTML Code
Iterate through each tagFetching text from the tag and remove whitespaces using the strip.After removing whitespace, check If the length of the text is zero remove the tag from HTML code.
Fetching text from the tag and remove whitespaces using the strip.
After removing whitespace, check If the length of the text is zero remove the tag from HTML code.
Example 1: Remove empty tag.
Python3
# Import Modulefrom bs4 import BeautifulSoup # HTML Objecthtml_object = """ <p><p></p><strong>some<br>text<br>here</strong></p> """ # Get HTML Codesoup = BeautifulSoup( html_object , "lxml") # Iterate each linefor x in soup.find_all(): # fetching text from tag and remove whitespaces if len(x.get_text(strip=True)) == 0: # Remove empty tag x.extract() # Print HTML Code with removed empty tagsprint(soup)
Output:
<html><body><strong>sometexthere</strong>
</body></html>
Example 2: Remove empty tag from a given URL.
Python3
# Import Modulefrom bs4 import BeautifulSoupimport requests # Page URLURL = "https://www.geeksforgeeks.org/" # Page content from Website URLpage = requests.get( URL ) # Get HTML Codesoup = BeautifulSoup( page.content , "lxml" ) # Iterate each linefor x in soup.find_all(): # fetching text from tag and remove whitespaces if len( x.get_text ( strip = True )) == 0: # Remove empty tag x.extract() # Print HTML Code with removed empty tagsprint(soup)
Output:
Python BeautifulSoup
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 73,
"s": 28,
"text": "Prerequisite: Requests, BeautifulSoup, strip"
},
{
"code": null,
"e": 229,
"s": 73,
"text": "The task is to write a program that removes the empty tag from HTML code. In Beautiful Soup there is no in-built method to remove tags that has no content."
},
{
"code": null,
"e": 422,
"s": 229,
"text": "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": 439,
"s": 422,
"text": "pip install bs4\n"
},
{
"code": null,
"e": 624,
"s": 439,
"text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 646,
"s": 624,
"text": "pip install requests\n"
},
{
"code": null,
"e": 660,
"s": 646,
"text": "Get HTML Code"
},
{
"code": null,
"e": 848,
"s": 660,
"text": "Iterate through each tagFetching text from the tag and remove whitespaces using the strip.After removing whitespace, check If the length of the text is zero remove the tag from HTML code."
},
{
"code": null,
"e": 915,
"s": 848,
"text": "Fetching text from the tag and remove whitespaces using the strip."
},
{
"code": null,
"e": 1013,
"s": 915,
"text": "After removing whitespace, check If the length of the text is zero remove the tag from HTML code."
},
{
"code": null,
"e": 1042,
"s": 1013,
"text": "Example 1: Remove empty tag."
},
{
"code": null,
"e": 1050,
"s": 1042,
"text": "Python3"
},
{
"code": "# Import Modulefrom bs4 import BeautifulSoup # HTML Objecthtml_object = \"\"\" <p><p></p><strong>some<br>text<br>here</strong></p> \"\"\" # Get HTML Codesoup = BeautifulSoup( html_object , \"lxml\") # Iterate each linefor x in soup.find_all(): # fetching text from tag and remove whitespaces if len(x.get_text(strip=True)) == 0: # Remove empty tag x.extract() # Print HTML Code with removed empty tagsprint(soup)",
"e": 1493,
"s": 1050,
"text": null
},
{
"code": null,
"e": 1501,
"s": 1493,
"text": "Output:"
},
{
"code": null,
"e": 1559,
"s": 1501,
"text": "<html><body><strong>sometexthere</strong>\n</body></html>\n"
},
{
"code": null,
"e": 1605,
"s": 1559,
"text": "Example 2: Remove empty tag from a given URL."
},
{
"code": null,
"e": 1613,
"s": 1605,
"text": "Python3"
},
{
"code": "# Import Modulefrom bs4 import BeautifulSoupimport requests # Page URLURL = \"https://www.geeksforgeeks.org/\" # Page content from Website URLpage = requests.get( URL ) # Get HTML Codesoup = BeautifulSoup( page.content , \"lxml\" ) # Iterate each linefor x in soup.find_all(): # fetching text from tag and remove whitespaces if len( x.get_text ( strip = True )) == 0: # Remove empty tag x.extract() # Print HTML Code with removed empty tagsprint(soup)",
"e": 2090,
"s": 1613,
"text": null
},
{
"code": null,
"e": 2098,
"s": 2090,
"text": "Output:"
},
{
"code": null,
"e": 2119,
"s": 2098,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 2143,
"s": 2119,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2150,
"s": 2143,
"text": "Python"
},
{
"code": null,
"e": 2169,
"s": 2150,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2267,
"s": 2169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2299,
"s": 2267,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2326,
"s": 2299,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2347,
"s": 2326,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2370,
"s": 2347,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2401,
"s": 2370,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2457,
"s": 2401,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2499,
"s": 2457,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2541,
"s": 2499,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2580,
"s": 2541,
"text": "Python | Get unique values from a list"
}
] |
Subarray with given sum | Practice | GeeksforGeeks
|
Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S.
In case of multiple subarrays, return the subarray which comes first on moving from left to right.
Example 1:
Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elements
from 2nd position to 4th position
is 12.
Example 2:
Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elements
from 1st position to 5th position
is 15.
Your Task:
You don't need to read input or print anything. The task is to complete the function subarraySum() which takes arr, N and S as input parameters and returns an arraylist containing the starting and ending positions of the first such occurring subarray from the left where sum equals to S. The two indexes in the array should be according to 1-based indexing. If no such subarray is found, return an array consisting only one element that is -1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
1 <= Ai <= 109
0
abhinayabhi141in 7 hours
class Solution{ //Function to find a continuous sub-array which adds up to a given number. static ArrayList<Integer> subarraySum(int[] arr, int n, int s) { // Your code here ArrayList<Integer> list=new ArrayList<>(); int sum = 0 , index = 0, count = 0; for(int i = index ; i < n ; i++){ sum += arr[i]; if(sum == s){ list.add(index+1); list.add(i+1); count++; break; } if(sum > s){ i=index++; sum=0; } } if(count != 0){ return list; } else{ list.add(-1); return list; } }}
0
royabhisek
This comment was deleted.
0
parvezrahaman1219in 4 hours
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int s = sc.nextInt();
int[] m = new int[n];
for (int j = 0; j < n; j++) {
m[j] = sc.nextInt();
}
Solution obj = new Solution();
ArrayList<Integer> res = obj.subarraySum(m, n, s);
for(int ii = 0;ii<res.size();ii++)
System.out.print(res.get(ii) + " ");
System.out.println();
}
}
}// } Driver Code Ends
class Solution
{
//Function to find a continuous sub-array which adds up to a given number.
static ArrayList<Integer> subarraySum(int[] arr, int n, int s)
{
//in this code 62 tc pass cz of time limit
/*int i,j,sum,eidx;
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(i=0;i<n;i++){
sum=arr[i];
for(j=i+1;j<=n;j++){
if(sum==s){
eidx=j;
numbers.add(i+1);
numbers.add(eidx);
}
if(numbers.size()>0 || sum>s || j==n){
break;
}
sum+=arr[j];
}
}
if(numbers.isEmpty()){
numbers.add(-1);
}
return numbers;*/
//in this code 72 tc pass cz of time limit
int i,sum=0,index=0;
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(i=index;i<n;i++){
sum+=arr[i];
if(sum==s){
numbers.add(index+1);
numbers.add(i+1);
break;
}
if(sum>s){
i=index++;
sum=0;
}
}
if(numbers.size()!=0){
return numbers;
}
else{
numbers.add(-1);
return numbers;
}
}
}
0
shivampathak12aps
This comment was deleted.
0
akarshbarar5 hours ago
class Solution{ //Function to find a continuous sub-array which adds up to a given number. static ArrayList<Integer> subarraySum(int[] arr, int n, int s) { // Your code here ArrayList<Integer> list=new ArrayList<>(); int sum = 0 , index = 0, count = 0; for(int i = index ; i < n ; i++){ sum += arr[i]; if(sum == s){ list.add(index+1); list.add(i+1); count++; break; } if(sum > s){ i=index++; sum=0; } } if(count != 0){ return list; } else{ list.add(-1); return list; } }}
0
saikriteja13 hours ago
C++ Solution
vector<int> subarraySum(int arr[], int n, long long s)
{
int i=0,j=0;
long long sum=arr[0];
vector<int> v;
for(int i=0;i<n;i++){
if(sum<s){
j++;
sum+=arr[j];
i--;
}
else if(sum>s){
j=i+1;
sum=arr[j];
}
else if(sum==s){
v.push_back(i+1);
v.push_back(j+1);
return v;
}
}
v.push_back(-1);
return v;
}
0
alycentra14 hours ago
I don't why it turn error
class Solution:
def subArraySum(self,arr, n, s):
#Write your code here
for i in range(n):
sum1=0
x=i+1
while x<=n :
sum1=sum(arr[i:x])
if sum1 == s:
return str(i+1)+ str(x)
else:
x+=1
return -1
-1
prateekgoyal217 hours ago
How do we think through this problem? Explained simply here:-
0
siddharthsingh11801 day ago
class Solution: def subArraySum(self,arr, n, s): i=0 j=0 sum=0 for i in range(n): sum=arr[i] j=i+1 while j<=n: if sum==s: return [i+1,j] elif sum>s: sum-=arr[i] i=i+1 else: sum+=arr[j] j=j+1
-10
ndenkala2 days ago
python
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 376,
"s": 238,
"text": "Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S."
},
{
"code": null,
"e": 475,
"s": 376,
"text": "In case of multiple subarrays, return the subarray which comes first on moving from left to right."
},
{
"code": null,
"e": 488,
"s": 477,
"text": "Example 1:"
},
{
"code": null,
"e": 615,
"s": 488,
"text": "Input:\nN = 5, S = 12\nA[] = {1,2,3,7,5}\nOutput: 2 4\nExplanation: The sum of elements \nfrom 2nd position to 4th position \nis 12."
},
{
"code": null,
"e": 628,
"s": 617,
"text": "Example 2:"
},
{
"code": null,
"e": 767,
"s": 628,
"text": "Input:\nN = 10, S = 15\nA[] = {1,2,3,4,5,6,7,8,9,10}\nOutput: 1 5\nExplanation: The sum of elements \nfrom 1st position to 5th position\nis 15.\n"
},
{
"code": null,
"e": 1224,
"s": 769,
"text": "Your Task:\nYou don't need to read input or print anything. The task is to complete the function subarraySum() which takes arr, N and S as input parameters and returns an arraylist containing the starting and ending positions of the first such occurring subarray from the left where sum equals to S. The two indexes in the array should be according to 1-based indexing. If no such subarray is found, return an array consisting only one element that is -1."
},
{
"code": null,
"e": 1288,
"s": 1226,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1332,
"s": 1290,
"text": "Constraints:\n1 <= N <= 105\n1 <= Ai <= 109"
},
{
"code": null,
"e": 1336,
"s": 1334,
"text": "0"
},
{
"code": null,
"e": 1361,
"s": 1336,
"text": "abhinayabhi141in 7 hours"
},
{
"code": null,
"e": 2021,
"s": 1361,
"text": "class Solution{ //Function to find a continuous sub-array which adds up to a given number. static ArrayList<Integer> subarraySum(int[] arr, int n, int s) { // Your code here ArrayList<Integer> list=new ArrayList<>(); int sum = 0 , index = 0, count = 0; for(int i = index ; i < n ; i++){ sum += arr[i]; if(sum == s){ list.add(index+1); list.add(i+1); count++; break; } if(sum > s){ i=index++; sum=0; } } if(count != 0){ return list; } else{ list.add(-1); return list; } }}"
},
{
"code": null,
"e": 2023,
"s": 2021,
"text": "0"
},
{
"code": null,
"e": 2034,
"s": 2023,
"text": "royabhisek"
},
{
"code": null,
"e": 2060,
"s": 2034,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2062,
"s": 2060,
"text": "0"
},
{
"code": null,
"e": 2090,
"s": 2062,
"text": "parvezrahaman1219in 4 hours"
},
{
"code": null,
"e": 4223,
"s": 2090,
"text": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\n\nclass Main{\n\tpublic static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n\n int t = sc.nextInt();\n\n for (int i = 0; i < t; i++) {\n int n = sc.nextInt();\n int s = sc.nextInt();\n\n int[] m = new int[n];\n for (int j = 0; j < n; j++) {\n m[j] = sc.nextInt();\n }\n \n Solution obj = new Solution();\n ArrayList<Integer> res = obj.subarraySum(m, n, s);\n for(int ii = 0;ii<res.size();ii++)\n System.out.print(res.get(ii) + \" \");\n System.out.println();\n }\n }\n\n}// } Driver Code Ends\n\n\nclass Solution\n{\n //Function to find a continuous sub-array which adds up to a given number.\n static ArrayList<Integer> subarraySum(int[] arr, int n, int s) \n {\n //in this code 62 tc pass cz of time limit\n /*int i,j,sum,eidx;\n ArrayList<Integer> numbers = new ArrayList<Integer>();\n for(i=0;i<n;i++){\n sum=arr[i];\n for(j=i+1;j<=n;j++){\n if(sum==s){\n eidx=j;\n numbers.add(i+1);\n numbers.add(eidx);\n }\n if(numbers.size()>0 || sum>s || j==n){\n break; \n }\n sum+=arr[j];\n }\n }\n if(numbers.isEmpty()){\n numbers.add(-1);\n }\n return numbers;*/\n \n //in this code 72 tc pass cz of time limit\n int i,sum=0,index=0;\n ArrayList<Integer> numbers = new ArrayList<Integer>();\n for(i=index;i<n;i++){\n sum+=arr[i];\n if(sum==s){\n numbers.add(index+1);\n numbers.add(i+1);\n break;\n }\n if(sum>s){\n i=index++;\n sum=0;\n }\n }\n if(numbers.size()!=0){\n return numbers;\n }\n else{\n numbers.add(-1);\n return numbers;\n }\n }\n}"
},
{
"code": null,
"e": 4225,
"s": 4223,
"text": "0"
},
{
"code": null,
"e": 4243,
"s": 4225,
"text": "shivampathak12aps"
},
{
"code": null,
"e": 4269,
"s": 4243,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4271,
"s": 4269,
"text": "0"
},
{
"code": null,
"e": 4294,
"s": 4271,
"text": "akarshbarar5 hours ago"
},
{
"code": null,
"e": 4981,
"s": 4294,
"text": "class Solution{ //Function to find a continuous sub-array which adds up to a given number. static ArrayList<Integer> subarraySum(int[] arr, int n, int s) { // Your code here ArrayList<Integer> list=new ArrayList<>(); int sum = 0 , index = 0, count = 0; for(int i = index ; i < n ; i++){ sum += arr[i]; if(sum == s){ list.add(index+1); list.add(i+1); count++; break; } if(sum > s){ i=index++; sum=0; } } if(count != 0){ return list; } else{ list.add(-1); return list; } }} "
},
{
"code": null,
"e": 4983,
"s": 4981,
"text": "0"
},
{
"code": null,
"e": 5006,
"s": 4983,
"text": "saikriteja13 hours ago"
},
{
"code": null,
"e": 5542,
"s": 5006,
"text": "C++ Solution\nvector<int> subarraySum(int arr[], int n, long long s)\n {\n int i=0,j=0;\n long long sum=arr[0];\n vector<int> v;\n for(int i=0;i<n;i++){\n if(sum<s){\n j++;\n sum+=arr[j];\n i--;\n }\n else if(sum>s){\n j=i+1;\n sum=arr[j];\n }\n else if(sum==s){\n v.push_back(i+1);\n v.push_back(j+1);\n return v;\n }\n }\n v.push_back(-1);\n return v;\n }"
},
{
"code": null,
"e": 5544,
"s": 5542,
"text": "0"
},
{
"code": null,
"e": 5566,
"s": 5544,
"text": "alycentra14 hours ago"
},
{
"code": null,
"e": 5593,
"s": 5566,
"text": "I don't why it turn error "
},
{
"code": null,
"e": 6023,
"s": 5593,
"text": "class Solution:\n\n def subArraySum(self,arr, n, s):\n\n \n\n \n\n #Write your code here\n\n for i in range(n):\n\n sum1=0\n\n\n\n x=i+1\n\n while x<=n :\n\n \n\n sum1=sum(arr[i:x])\n\n if sum1 == s:\n\n return str(i+1)+ str(x) \n\n \n\n else: \n\n x+=1\n\n return -1 \n"
},
{
"code": null,
"e": 6030,
"s": 6027,
"text": "-1"
},
{
"code": null,
"e": 6056,
"s": 6030,
"text": "prateekgoyal217 hours ago"
},
{
"code": null,
"e": 6119,
"s": 6056,
"text": "How do we think through this problem? Explained simply here:- "
},
{
"code": null,
"e": 6121,
"s": 6119,
"text": "0"
},
{
"code": null,
"e": 6149,
"s": 6121,
"text": "siddharthsingh11801 day ago"
},
{
"code": null,
"e": 6584,
"s": 6149,
"text": "class Solution: def subArraySum(self,arr, n, s): i=0 j=0 sum=0 for i in range(n): sum=arr[i] j=i+1 while j<=n: if sum==s: return [i+1,j] elif sum>s: sum-=arr[i] i=i+1 else: sum+=arr[j] j=j+1 "
},
{
"code": null,
"e": 6588,
"s": 6584,
"text": "-10"
},
{
"code": null,
"e": 6607,
"s": 6588,
"text": "ndenkala2 days ago"
},
{
"code": null,
"e": 6614,
"s": 6607,
"text": "python"
},
{
"code": null,
"e": 6760,
"s": 6614,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6796,
"s": 6760,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6806,
"s": 6796,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6816,
"s": 6806,
"text": "\nContest\n"
},
{
"code": null,
"e": 6879,
"s": 6816,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7064,
"s": 6879,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7348,
"s": 7064,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 7494,
"s": 7348,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 7571,
"s": 7494,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 7612,
"s": 7571,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 7640,
"s": 7612,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 7711,
"s": 7640,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 7898,
"s": 7711,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Search in a Rotated Array | Practice | GeeksforGeeks
|
Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element key. The task is to find the index of the given element key in the array A.
Example 1:
Input:
N = 9
A[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}
key = 10
Output:
5
Explanation: 10 is found at index 5.
Example 2:
Input:
N = 4
A[] = {3, 5, 1, 2}
key = 6
Output:
-1
Explanation: There is no element that has value 6.
Your Task:
Complete the function search() which takes an array arr[] and start, end index of the array and the K as input parameters, and returns the answer.
Can you solve it in expected time complexity?
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
0 ≤ A[i] ≤ 108
1 ≤ key ≤ 108
0
js997778812 hours ago
Why this JavaScript code giving TLE every time after passing 428 test cases? And also I have tried O(N) approach, that also gives same TLE.
class Solution {
binarySearch(arr, low, high, key){
let mid = Math.floor((low + high) / 2);
while(low <= high){
if(key === arr[mid]){
return mid;
}
else if(key > arr[mid]){
low = mid + 1;
}else{
high = mid - 1;
}
mid = Math.floor((low + high) / 2);
}
return -1;
}
pivot(arr, low, high){
let mid = Math.floor((low + high) / 2);
while(low < high){
if(arr[mid] < arr[0]){
high = mid;
}else{
low = mid + 1;
}
mid = Math.floor((low + high) / 2);
}
return mid;
}
search(arr, low, high, key) {
//code here
let pivot = this.pivot(arr, low, high);
if(arr[pivot] <= key && key <= arr[high]){
return this.binarySearch(arr, pivot, high, key);
}else{
return this.binarySearch(arr, 0, pivot - 1, key)
}
}
}
0
manjeetsachan12342 days ago
// simple c++ solution
class Solution{ public: int search(int A[], int l, int h, int key){ //complete the function here while(l<=h){ int mid=l+(h-l)/2; if(A[mid]==key){ return mid; } if(A[l]<=A[mid]){ if(A[l]<=key && key<=A[mid]){ h=mid-1; } else{ l=mid+1; } } else{ if(A[mid]<=key && key<=A[h]){ l=mid+1; } else{ h=mid-1; } } } return -1; }};
-1
mayank180919992 days ago
int search(int A[], int l, int h, int key){
//complete the function here
h=h+1;
for(int i=0;i<h;i++){
if(A[i]==key){
return i;
}
}
return -1;
}
-1
officialsurajpandey553 days ago
if first part is sorted than why this condition is required
if we previously check the middle element
if(A[low] <= A[mid])
if(A[low] <= A[mid]){
if(A[low] <= key and A[mid] > key)
high = mid-1; //key is persent in this part
else
low = mid+1;
}
0
20je01175 days ago
binary search:-
int search(int A[],int l,int h,int key){ int mid; while(l<=h){ mid=(l+h)/2; if((A[mid]>=A[0]) == (key>=A[0])){ if(A[mid]==key)return mid; else if(key>A[mid])l=mid+1; else h=mid-1; } else{ if(A[mid]>=A[0])l=mid+1; else h=mid-1; } } return -1; }
-9
lovemurari20181 week ago
//C++ easy solution
int ans = -1; for(int i = 0; i < l+h; i++) { if(key == A[i]) { ans = i; break; } } return ans;
0
dharpranoy22551 week ago
Python Solution : 1.78/3.17
def search(self, A : list, l : int, h : int, key : int): j=0 for i in range(h-1,0,-1): if key==A[i]: return i if A[i-1]>A[i]: j=i-1 break i=0 while i<=j: mid=(i+j)//2 if A[mid]==key: return mid if key>A[mid]: i=mid+1 elif key<A[mid]: j=mid-1 return -1
0
raje_1431 week ago
//simple solution in c++
int search(int arr[], int start, int end, int target){
//complete the function here
while(start<=end)
{
int mid=start+(end-start)/2;
if(arr[mid] == target){
return mid;
}
if(arr[mid]>=arr[start])
{
if(target>=arr[start] && target<=arr[mid]){
end=mid-1;
}
else{
start=mid+1;
}
}
else{
if(target<=arr[end] && target>=arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
}
}
return -1;
}
0
jayprakashpandey47b1 week ago
int search(int A[], int l, int h, int key){
//complete the function here
int mid=(l+h)/2;
if(A[mid]==key) return mid;
if(l>=h) return -1;
if(A[mid]<=A[l]){
if(A[mid]<=key && A[h]>=key) l=mid+1;
else h=mid-1;
}else{
if(A[mid]>=key && A[l]<=key) h=mid-1;
else l=mid+1;
}
return search(A,l,h,key);
}
//binary search log(n)
-3
subhambhttachariya031 week ago
int ans = -1; for(int i = 0; i < l+h; i++) { if(key == A[i]) { ans = i; break; } } return ans;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 425,
"s": 238,
"text": "Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element key. The task is to find the index of the given element key in the array A."
},
{
"code": null,
"e": 436,
"s": 425,
"text": "Example 1:"
},
{
"code": null,
"e": 540,
"s": 436,
"text": "Input:\nN = 9\nA[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}\nkey = 10\nOutput:\n5\nExplanation: 10 is found at index 5."
},
{
"code": null,
"e": 551,
"s": 540,
"text": "Example 2:"
},
{
"code": null,
"e": 653,
"s": 551,
"text": "Input:\nN = 4\nA[] = {3, 5, 1, 2}\nkey = 6\nOutput:\n-1\nExplanation: There is no element that has value 6."
},
{
"code": null,
"e": 858,
"s": 653,
"text": "Your Task:\nComplete the function search() which takes an array arr[] and start, end index of the array and the K as input parameters, and returns the answer.\n\nCan you solve it in expected time complexity?"
},
{
"code": null,
"e": 926,
"s": 858,
"text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 980,
"s": 926,
"text": "Constraints:\n1 ≤ N ≤ 107\n0 ≤ A[i] ≤ 108\n1 ≤ key ≤ 108"
},
{
"code": null,
"e": 984,
"s": 982,
"text": "0"
},
{
"code": null,
"e": 1006,
"s": 984,
"text": "js997778812 hours ago"
},
{
"code": null,
"e": 1146,
"s": 1006,
"text": "Why this JavaScript code giving TLE every time after passing 428 test cases? And also I have tried O(N) approach, that also gives same TLE."
},
{
"code": null,
"e": 2165,
"s": 1148,
"text": "class Solution {\n binarySearch(arr, low, high, key){\n let mid = Math.floor((low + high) / 2);\n while(low <= high){\n if(key === arr[mid]){\n return mid;\n }\n else if(key > arr[mid]){\n low = mid + 1;\n }else{\n high = mid - 1;\n }\n mid = Math.floor((low + high) / 2);\n }\n return -1;\n }\n pivot(arr, low, high){\n let mid = Math.floor((low + high) / 2);\n while(low < high){\n if(arr[mid] < arr[0]){\n high = mid;\n }else{\n low = mid + 1;\n }\n mid = Math.floor((low + high) / 2);\n }\n return mid;\n }\n search(arr, low, high, key) {\n //code here\n let pivot = this.pivot(arr, low, high);\n if(arr[pivot] <= key && key <= arr[high]){\n return this.binarySearch(arr, pivot, high, key);\n }else{\n return this.binarySearch(arr, 0, pivot - 1, key)\n }\n }\n}"
},
{
"code": null,
"e": 2167,
"s": 2165,
"text": "0"
},
{
"code": null,
"e": 2195,
"s": 2167,
"text": "manjeetsachan12342 days ago"
},
{
"code": null,
"e": 2218,
"s": 2195,
"text": "// simple c++ solution"
},
{
"code": null,
"e": 2718,
"s": 2218,
"text": "class Solution{ public: int search(int A[], int l, int h, int key){ //complete the function here while(l<=h){ int mid=l+(h-l)/2; if(A[mid]==key){ return mid; } if(A[l]<=A[mid]){ if(A[l]<=key && key<=A[mid]){ h=mid-1; } else{ l=mid+1; } } else{ if(A[mid]<=key && key<=A[h]){ l=mid+1; } else{ h=mid-1; } } } return -1; }}; "
},
{
"code": null,
"e": 2721,
"s": 2718,
"text": "-1"
},
{
"code": null,
"e": 2746,
"s": 2721,
"text": "mayank180919992 days ago"
},
{
"code": null,
"e": 2978,
"s": 2746,
"text": " int search(int A[], int l, int h, int key){\n //complete the function here\n h=h+1;\n for(int i=0;i<h;i++){\n if(A[i]==key){\n return i;\n }\n }\n return -1;\n }"
},
{
"code": null,
"e": 2981,
"s": 2978,
"text": "-1"
},
{
"code": null,
"e": 3013,
"s": 2981,
"text": "officialsurajpandey553 days ago"
},
{
"code": null,
"e": 3073,
"s": 3013,
"text": "if first part is sorted than why this condition is required"
},
{
"code": null,
"e": 3115,
"s": 3073,
"text": "if we previously check the middle element"
},
{
"code": null,
"e": 3137,
"s": 3115,
"text": " if(A[low] <= A[mid])"
},
{
"code": null,
"e": 3342,
"s": 3137,
"text": " if(A[low] <= A[mid]){\n if(A[low] <= key and A[mid] > key)\n high = mid-1; //key is persent in this part \n else \n low = mid+1;\n }"
},
{
"code": null,
"e": 3344,
"s": 3342,
"text": "0"
},
{
"code": null,
"e": 3363,
"s": 3344,
"text": "20je01175 days ago"
},
{
"code": null,
"e": 3379,
"s": 3363,
"text": "binary search:-"
},
{
"code": null,
"e": 3770,
"s": 3381,
"text": "int search(int A[],int l,int h,int key){ int mid; while(l<=h){ mid=(l+h)/2; if((A[mid]>=A[0]) == (key>=A[0])){ if(A[mid]==key)return mid; else if(key>A[mid])l=mid+1; else h=mid-1; } else{ if(A[mid]>=A[0])l=mid+1; else h=mid-1; } } return -1; }"
},
{
"code": null,
"e": 3773,
"s": 3770,
"text": "-9"
},
{
"code": null,
"e": 3798,
"s": 3773,
"text": "lovemurari20181 week ago"
},
{
"code": null,
"e": 3818,
"s": 3798,
"text": "//C++ easy solution"
},
{
"code": null,
"e": 3995,
"s": 3820,
"text": "int ans = -1; for(int i = 0; i < l+h; i++) { if(key == A[i]) { ans = i; break; } } return ans;"
},
{
"code": null,
"e": 3997,
"s": 3995,
"text": "0"
},
{
"code": null,
"e": 4022,
"s": 3997,
"text": "dharpranoy22551 week ago"
},
{
"code": null,
"e": 4050,
"s": 4022,
"text": "Python Solution : 1.78/3.17"
},
{
"code": null,
"e": 4476,
"s": 4050,
"text": "def search(self, A : list, l : int, h : int, key : int): j=0 for i in range(h-1,0,-1): if key==A[i]: return i if A[i-1]>A[i]: j=i-1 break i=0 while i<=j: mid=(i+j)//2 if A[mid]==key: return mid if key>A[mid]: i=mid+1 elif key<A[mid]: j=mid-1 return -1"
},
{
"code": null,
"e": 4478,
"s": 4476,
"text": "0"
},
{
"code": null,
"e": 4497,
"s": 4478,
"text": "raje_1431 week ago"
},
{
"code": null,
"e": 5257,
"s": 4497,
"text": "\n//simple solution in c++\n\nint search(int arr[], int start, int end, int target){\n //complete the function here\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n if(arr[mid] == target){\n return mid;\n }\n if(arr[mid]>=arr[start])\n {\n if(target>=arr[start] && target<=arr[mid]){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n else{\n if(target<=arr[end] && target>=arr[mid]){\n start=mid+1;\n }\n else{\n end=mid-1;\n }\n }\n }\n return -1;\n }"
},
{
"code": null,
"e": 5259,
"s": 5257,
"text": "0"
},
{
"code": null,
"e": 5289,
"s": 5259,
"text": "jayprakashpandey47b1 week ago"
},
{
"code": null,
"e": 5681,
"s": 5289,
"text": "int search(int A[], int l, int h, int key){\n //complete the function here\n int mid=(l+h)/2;\n if(A[mid]==key) return mid;\n if(l>=h) return -1;\n if(A[mid]<=A[l]){\n if(A[mid]<=key && A[h]>=key) l=mid+1;\n else h=mid-1;\n }else{\n if(A[mid]>=key && A[l]<=key) h=mid-1;\n else l=mid+1;\n }\n return search(A,l,h,key);\n }\n //binary search log(n)"
},
{
"code": null,
"e": 5684,
"s": 5681,
"text": "-3"
},
{
"code": null,
"e": 5715,
"s": 5684,
"text": "subhambhttachariya031 week ago"
},
{
"code": null,
"e": 5891,
"s": 5715,
"text": " int ans = -1; for(int i = 0; i < l+h; i++) { if(key == A[i]) { ans = i; break; } } return ans;"
},
{
"code": null,
"e": 6037,
"s": 5891,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6073,
"s": 6037,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6083,
"s": 6073,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6093,
"s": 6083,
"text": "\nContest\n"
},
{
"code": null,
"e": 6156,
"s": 6093,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6341,
"s": 6156,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6625,
"s": 6341,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6771,
"s": 6625,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6848,
"s": 6771,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6889,
"s": 6848,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6917,
"s": 6889,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6988,
"s": 6917,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 7175,
"s": 6988,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Smallest subarray with k distinct numbers
|
08 Jun, 2022
We are given an array consisting of n integers and an integer k. We need to find the minimum range in array [l, r] (both l and r are inclusive) such that there are exactly k different numbers. If such subarray doesn’t exist print “Invalid k”.Examples:
Input : arr[] = { 1, 1, 2, 2, 3, 3, 4, 5}
k = 3
Output : 5 7
Input : arr[] = { 1, 2, 2, 3}
k = 2
Output : 0 1
Input : arr[] = {1, 1, 2, 1, 2}
k = 3
Output : Invalid k
Approach 1 : (Brute Force Method)
The simplest approach in this problem is, try to generate all the subarrays and check for which subarray the size is k. But there are some points we need to take care.Steps:
1. Pick each of the elements from the given array as the starting element [ i-th element ] of our required subarray.
2. In each iteration initialize an empty set to store the distinct elements of the subarray
Pick each remaining element [ i, i+1,..n – 1] from the array as the last element [ j-th element ].
Add the current element to the set.
If the set size equals k then update the results and break from the inner loop (already found k distinct elements increasing the size of the subarray has 2 possibilities either will get more distinct elements, or increase the subarray size with repeated elements which are not to be considered in the required results).
3. If (j == n) or j = size of the array, i.e. we have not found any desired subarray starting from i-th index and going forward we will be having fewer elements to consider. ( For example : consider given array is 4 5 5 4 5 and k = 3, when start from 0th index we will not find any subarray of k size and j will reach end so that means we won’t get any element that can make a k = 3 size required subarray). So, Break from the outer loop.
4. Print the output if found, otherwise, print “Invalid k”.
C++
Java
Python 3
C#
Javascript
// C++ program to find minimum range that// contains exactly k distinct numbers.#include <bits/stdc++.h>using namespace std; // Prints the minimum range that contains exactly// k distinct numbers.void minRange(int arr[], int n, int k){ // Starting and ending index of resultant subarray int start = 0, end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct elements unordered_set<int> set; // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.insert(arr[j]); /* If set contains exactly k elements, then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already k distinct elements // now, no need to consider further elements break; } } // If there are no k distinct elements // left in the array starting from index i we will // break if (j == n) { break; } } // If no window found then print -1 if (start == 0 && end == n) cout << "Invalid k"; else cout << start << " " << end;} // Driver code for above function.int main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0;} // This code is contributed by Rajdeep
// Java program to find minimum// range that contains exactly// k distinct numbers.import java.util.*;import java.util.ArrayList;import java.util.HashSet; class GFG { // Prints the minimum range // that contains exactly k // distinct numbers. static void minRange(int arr[], int n, int k) { // start -> start index of resultant subarray // end -> end index of resultant subarray int start = 0; int end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct // elements HashSet<Integer> set = new HashSet<Integer>(); // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.add(arr[j]); /* If set contains exactly k elements,then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already 'k' distinct // elements now, no need to consider // further elements break; } } // If there are no k distinct elements left // in the array starting from index i we will break if (j == n) break; } // If no window found then print -1 if (start == 0 && end == n) System.out.println("Invalid k"); else System.out.println(start + " " + end); } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int k = 3; minRange(arr, n, k); }} // This code is contributed by Rajdeep
# Python 3 program to find minimum range# that contains exactly k distinct numbers. # Prints the minimum range that contains# exactly k distinct numbers.def minRange(arr, n, k): l = 0 r = n # Consider every element as # starting point. for i in range(n): # Find the smallest window starting # with arr[i] and containing exactly # k distinct elements. s = [] for j in range(i, n) : s.append(arr[j]) if (len(s) == k): if ((j - i) < (r - l)) : r = j l = i break # There are less than k distinct # elements now, so no need to continue. if (j == n): break # If there was no window with k distinct # elements (k is greater than total # distinct elements) if (l == 0 and r == n): print("Invalid k") else: print(l, r) # Driver codeif __name__ == "__main__": arr = [ 1, 2, 3, 4, 5 ] n = len(arr) k = 3 minRange(arr, n, k) # This code is contributed# by ChitraNayal
// C# program to find minimum // range that contains exactly // k distinct numbers.using System;using System.Collections.Generic; public class GFG{ // Prints the minimum range // that contains exactly k // distinct numbers.public static void minRange(int[] arr, int n, int k){ int l = 0, r = n; // Consider every element // as starting point. for (int i = 0; i < n; i++) { // Find the smallest window // starting with arr[i] and // containing exactly k // distinct elements. ISet<int> s = new HashSet<int>(); int j; for (j = i; j < n; j++) { s.Add(arr[j]); if (s.Count == k) { if ((j - i) < (r - l)) { r = j; l = i; } break; } } // There are less than k // distinct elements now, // so no need to continue. if (j == n) { break; } } // If there was no window // with k distinct elements // (k is greater than total // distinct elements) if (l == 0 && r == n) { Console.WriteLine("Invalid k"); } else { Console.WriteLine(l + " " + r); }} // Driver code public static void Main(string[] args){ int[] arr = new int[] {1, 2, 3, 4, 5}; int n = arr.Length; int k = 3; minRange(arr, n, k);}} // This code is contributed by Shrikant13
<script>// Javascript program to find minimum// range that contains exactly// k distinct numbers. // Prints the minimum range // that contains exactly k // distinct numbers. function minRange(arr,n,k) { let l = 0, r = n; // Consider every element // as starting point. for (let i = 0; i < n; i++) { // Find the smallest window // starting with arr[i] and // containing exactly k // distinct elements. let s = new Set(); let j; for (j = i; j < n; j++) { s.add(arr[j]); if (s.size == k) { if ((j - i) < (r - l)) { r = j; l = i; } break; } } // There are less than k // distinct elements now, // so no need to continue. if (j == n) break; } // If there was no window // with k distinct elements // (k is greater than total // distinct elements) if (l == 0 && r == n) document.write("Invalid k"); else document.write(l + " " + r); } // Driver code let arr=[1, 2, 3, 4, 5]; let n = arr.length; let k = 3; minRange(arr, n, k); // This code is contributed by avanitrachhadiya2155</script>
0 2
Time Complexity : O(N^2) ,where N is the number of elements in the arrayEvery time picking the end points of the subarray using two nested loops(one inside another) makes the time complexity O(N^2).
Space Complexity : O(N)In the worst case, we can have all ‘N’ elements in our set.
Approach 2 : (Sliding Window Approach)
Optimization is get rid of the repeated work while making all subarray, all subarray will not help to find the resultant. The approach is –
Steps :
Initialize a map to store the frequencies of each element.
Taking two variables as taken before : start and end of the required subarray.
And here we are using i and j as the starting and ending index of the window respectively, initializing as i = 0 and j = 0.
Will traverse the array while the ending pointer of our window reach the end of given array. i.e. while( j < n) 1. Add the current element to the map map[ arr[j] ]++ and make j pointing to the next index 2. Consider the window [ i, j-1 ] (reason for ‘j-1’ is as we incremented the value of ‘j’ just after insertion in last step) check whether its size is equal to k 3. If window size is lesser then k then continue 4. But if window size == k, then check its length whether it is the resultant subarray or not. 5. After that we need to move our window, but in order to move our window, we have to check the starting element of our current window (i.e. i-th). If the i-th element is having a frequency of 1 then erase it from the map and else decrease its frequency by 1. And increase the i-value. Make i to point to the next element.( For understanding the reason of erase and decreasing frequency, take an example : 4 2 2 3 4 4 3 and k = 3 when we are dealing with the window 2 2 3 4 then ‘i’ would have pointed to the start of window (first 2) and ‘j’ would have pointed to the last of window (at 4). Now while moving forward (by one position), if the window totally erase 2 from the map, (and make window 2 3 4 4) then map would contain the information that 2 is not in the map but it is wrong so we will decrease the count of 2. Similarly, in case of having frequency == 1, and about to leave the window, the map should not contain the frequency of the element which not there in the window. )
C++
Java
Python3
C#
Javascript
// C++ program to find minimum range that// contains exactly k distinct numbers.#include <bits/stdc++.h>using namespace std; // prints the minimum range that contains exactly// k distinct numbers.void minRange(int arr[], int n, int k){ /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; unordered_map<int, int> map; /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map[arr[j]]++; j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (subArrayLen > windowLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map[arr[i]] == 1) map.erase(arr[i]); // decrease freq by 1 else map[arr[i]]--; // move the starting index of window i++; } } if (start == 0 && end == n) cout << "Invalid k" << endl; else cout << start << " " << end << endl;} // Driver code for above function.int main(){ int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0;} // This code is contributed by Rajdeep
// Java program to find minimum range that// contains exactly k distinct numbers.import java.util.*; class GFG { // Prints the minimum range that contains exactly // k distinct numbers. static void minRange(int arr[], int n, int k) { /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; HashMap<Integer, Integer> map = new HashMap<>(); /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map.put(arr[j], map.getOrDefault(arr[j], 0) + 1); j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (windowLen < subArrayLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map.get(arr[i]) == 1) map.remove(arr[i]); // decrease freq by 1 else map.put(arr[i], map.get(arr[i]) - 1); // move the starting index of window i++; } } if (start == 0 && end == n) System.out.println("Invalid k"); else System.out.println(start + " " + end); } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = arr.length; int k = 3; minRange(arr, n, k); }} // This code is contributed by Rajdeep
# Python3 program to find the minimum range# that contains exactly k distinct numbers.from collections import defaultdict # Prints the minimum range that contains# exactly k distinct numbers.def minRange(arr, n, k): # Initially left and right side is -1 # and -1, number of distinct elements # are zero and range is n. l, r = 0, n i = 0 j = -1 # Initialize right side hm = defaultdict(lambda:0) while i < n: while j < n: # increment right side. j += 1 # if number of distinct elements less than k. if len(hm) < k and j < n: hm[arr[j]] += 1 # if distinct elements are equal to k # and length is less than previous length. if len(hm) == k and ((r - l) >= (j - i)): l, r = i, j break # if number of distinct elements less # than k, then break. if len(hm) < k: break # if distinct elements equals to k then # try to increment left side. while len(hm) == k: if hm[arr[i]] == 1: del(hm[arr[i]]) else: hm[arr[i]] -= 1 # increment left side. i += 1 # it is same as explained in above loop. if len(hm) == k and (r - l) >= (j - i): l, r = i, j if hm[arr[i]] == 1: del(hm[arr[i]]) else: hm[arr[i]] -= 1 i += 1 if l == 0 and r == n: print("Invalid k") else: print(l, r) # Driver code for above function.if __name__ == "__main__": arr = [1, 1, 2, 2, 3, 3, 4, 5] n = len(arr) k = 3 minRange(arr, n, k) # This code is contributed by Rituraj Jain
// C# program to find minimum// range that contains exactly// k distinct numbers.using System;using System.Collections.Generic;class GFG{ // Prints the minimum// range that contains exactly// k distinct numbers.static void minRange(int []arr, int n, int k){ // Initially left and // right side is -1 and -1, // number of distinct // elements are zero and // range is n. int l = 0, r = n; // Initialize right side int j = -1; Dictionary<int, int> hm = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { while (j < n) { // Increment right side. j++; // If number of distinct elements less // than k. if (j < n && hm.Count < k) if(hm.ContainsKey(arr[j])) hm[arr[j]] = hm[arr[j]] + 1; else hm.Add(arr[j], 1); // If distinct elements are equal to k // and length is less than previous length. if (hm.Count == k && ((r - l) >= (j - i))) { l = i; r = j; break; } } // If number of distinct elements less // than k, then break. if (hm.Count < k) break; // If distinct elements equals to k then // try to increment left side. while (hm.Count == k) { if (hm.ContainsKey(arr[i]) && hm[arr[i]] == 1) hm.Remove(arr[i]); else { if(hm.ContainsKey(arr[i])) hm[arr[i]] = hm[arr[i]] - 1; } // Increment left side. i++; // It is same as explained in above loop. if (hm.Count == k && (r - l) >= (j - i)) { l = i; r = j; } } if (hm.ContainsKey(arr[i]) && hm[arr[i]] == 1) hm.Remove(arr[i]); else if(hm.ContainsKey(arr[i])) hm[arr[i]] = hm[arr[i]] - 1; } if (l == 0 && r == n) Console.WriteLine("Invalid k"); else Console.WriteLine(l + " " + r);} // Driver codepublic static void Main(String[] args){ int []arr = {1, 1, 2, 2, 3, 3, 4, 5}; int n = arr.Length; int k = 3; minRange(arr, n, k);}} // This code is contributed by shikhasingrajput
<script>// Javascript program to find minimum// range that contains exactly// k distinct numbers // Prints the minimum// range that contains exactly// k distinct numbers. function minRange(arr,n,k) { // Initially left and right side is -1 and -1, // number of distinct elements are zero and // range is n. let l = 0, r = n; // Initialize right side let j = -1; let hm = new Map(); for(let i = 0; i < n; i++) { while (j < n) { // Increment right side. j++; // If number of distinct elements less // than k. if (j < n && hm.size < k) { if(hm.has(arr[j])) hm.set(arr[j], hm.get(arr[j]) + 1); else hm.set(arr[j],1); } // If distinct elements are equal to k // and length is less than previous length. if (hm.size == k && ((r - l) >= (j - i))) { l = i; r = j; break; } } // If number of distinct elements less // than k, then break. if (hm.size < k) break; // If distinct elements equals to k then // try to increment left side. while (hm.size == k) { if (hm.has(arr[i]) && hm.get(arr[i]) == 1) hm.delete(arr[i]); else if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) - 1); // Increment left side. i++; // It is same as explained in above loop. if (hm.size == k && (r - l) >= (j - i)) { l = i; r = j; } } if (hm.has(arr[i]) && hm.get(arr[i]) == 1) hm.delete(arr[i]); else if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) - 1); } if (l == 0 && r == n) document.write("Invalid k"); else document.write(l + " " + r); } // Driver code let arr=[1, 1, 2, 2, 3, 3, 4, 5]; let n = arr.length; let k = 3; minRange(arr, n, k); // This code is contributed by rag2127</script>
5 7
Time Complexity : O(N) ,where N is the number of elements in the arrayIn the worst case, each element will be added once and removed once from the map.
Space Complexity : O(K)In the worst case, we can have only ‘K’ elements in our map.
This article is contributed by Rajdeep Mallick. 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.
Kirti_Mangal
shrikanth13
ukasp
rituraj_jain
jrishabh99
shikhasingrajput
avanitrachhadiya2155
rag2127
rajdeepmallick999
sagartomar9927
cpp-unordered_map
sliding-window
Arrays
Hash
sliding-window
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 305,
"s": 52,
"text": "We are given an array consisting of n integers and an integer k. We need to find the minimum range in array [l, r] (both l and r are inclusive) such that there are exactly k different numbers. If such subarray doesn’t exist print “Invalid k”.Examples: "
},
{
"code": null,
"e": 512,
"s": 305,
"text": "Input : arr[] = { 1, 1, 2, 2, 3, 3, 4, 5} \n k = 3\nOutput : 5 7\n\nInput : arr[] = { 1, 2, 2, 3} \n k = 2\nOutput : 0 1\n\nInput : arr[] = {1, 1, 2, 1, 2}\n k = 3\nOutput : Invalid k"
},
{
"code": null,
"e": 546,
"s": 512,
"text": "Approach 1 : (Brute Force Method)"
},
{
"code": null,
"e": 720,
"s": 546,
"text": "The simplest approach in this problem is, try to generate all the subarrays and check for which subarray the size is k. But there are some points we need to take care.Steps:"
},
{
"code": null,
"e": 840,
"s": 720,
"text": " 1. Pick each of the elements from the given array as the starting element [ i-th element ] of our required subarray."
},
{
"code": null,
"e": 935,
"s": 840,
"text": " 2. In each iteration initialize an empty set to store the distinct elements of the subarray"
},
{
"code": null,
"e": 1034,
"s": 935,
"text": "Pick each remaining element [ i, i+1,..n – 1] from the array as the last element [ j-th element ]."
},
{
"code": null,
"e": 1070,
"s": 1034,
"text": "Add the current element to the set."
},
{
"code": null,
"e": 1390,
"s": 1070,
"text": "If the set size equals k then update the results and break from the inner loop (already found k distinct elements increasing the size of the subarray has 2 possibilities either will get more distinct elements, or increase the subarray size with repeated elements which are not to be considered in the required results)."
},
{
"code": null,
"e": 1845,
"s": 1390,
"text": " 3. If (j == n) or j = size of the array, i.e. we have not found any desired subarray starting from i-th index and going forward we will be having fewer elements to consider. ( For example : consider given array is 4 5 5 4 5 and k = 3, when start from 0th index we will not find any subarray of k size and j will reach end so that means we won’t get any element that can make a k = 3 size required subarray). So, Break from the outer loop."
},
{
"code": null,
"e": 1908,
"s": 1845,
"text": " 4. Print the output if found, otherwise, print “Invalid k”."
},
{
"code": null,
"e": 1912,
"s": 1908,
"text": "C++"
},
{
"code": null,
"e": 1917,
"s": 1912,
"text": "Java"
},
{
"code": null,
"e": 1926,
"s": 1917,
"text": "Python 3"
},
{
"code": null,
"e": 1929,
"s": 1926,
"text": "C#"
},
{
"code": null,
"e": 1940,
"s": 1929,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum range that// contains exactly k distinct numbers.#include <bits/stdc++.h>using namespace std; // Prints the minimum range that contains exactly// k distinct numbers.void minRange(int arr[], int n, int k){ // Starting and ending index of resultant subarray int start = 0, end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct elements unordered_set<int> set; // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.insert(arr[j]); /* If set contains exactly k elements, then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already k distinct elements // now, no need to consider further elements break; } } // If there are no k distinct elements // left in the array starting from index i we will // break if (j == n) { break; } } // If no window found then print -1 if (start == 0 && end == n) cout << \"Invalid k\"; else cout << start << \" \" << end;} // Driver code for above function.int main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0;} // This code is contributed by Rajdeep",
"e": 3596,
"s": 1940,
"text": null
},
{
"code": "// Java program to find minimum// range that contains exactly// k distinct numbers.import java.util.*;import java.util.ArrayList;import java.util.HashSet; class GFG { // Prints the minimum range // that contains exactly k // distinct numbers. static void minRange(int arr[], int n, int k) { // start -> start index of resultant subarray // end -> end index of resultant subarray int start = 0; int end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct // elements HashSet<Integer> set = new HashSet<Integer>(); // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.add(arr[j]); /* If set contains exactly k elements,then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already 'k' distinct // elements now, no need to consider // further elements break; } } // If there are no k distinct elements left // in the array starting from index i we will break if (j == n) break; } // If no window found then print -1 if (start == 0 && end == n) System.out.println(\"Invalid k\"); else System.out.println(start + \" \" + end); } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int k = 3; minRange(arr, n, k); }} // This code is contributed by Rajdeep",
"e": 5670,
"s": 3596,
"text": null
},
{
"code": "# Python 3 program to find minimum range# that contains exactly k distinct numbers. # Prints the minimum range that contains# exactly k distinct numbers.def minRange(arr, n, k): l = 0 r = n # Consider every element as # starting point. for i in range(n): # Find the smallest window starting # with arr[i] and containing exactly # k distinct elements. s = [] for j in range(i, n) : s.append(arr[j]) if (len(s) == k): if ((j - i) < (r - l)) : r = j l = i break # There are less than k distinct # elements now, so no need to continue. if (j == n): break # If there was no window with k distinct # elements (k is greater than total # distinct elements) if (l == 0 and r == n): print(\"Invalid k\") else: print(l, r) # Driver codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 4, 5 ] n = len(arr) k = 3 minRange(arr, n, k) # This code is contributed# by ChitraNayal",
"e": 6766,
"s": 5670,
"text": null
},
{
"code": "// C# program to find minimum // range that contains exactly // k distinct numbers.using System;using System.Collections.Generic; public class GFG{ // Prints the minimum range // that contains exactly k // distinct numbers.public static void minRange(int[] arr, int n, int k){ int l = 0, r = n; // Consider every element // as starting point. for (int i = 0; i < n; i++) { // Find the smallest window // starting with arr[i] and // containing exactly k // distinct elements. ISet<int> s = new HashSet<int>(); int j; for (j = i; j < n; j++) { s.Add(arr[j]); if (s.Count == k) { if ((j - i) < (r - l)) { r = j; l = i; } break; } } // There are less than k // distinct elements now, // so no need to continue. if (j == n) { break; } } // If there was no window // with k distinct elements // (k is greater than total // distinct elements) if (l == 0 && r == n) { Console.WriteLine(\"Invalid k\"); } else { Console.WriteLine(l + \" \" + r); }} // Driver code public static void Main(string[] args){ int[] arr = new int[] {1, 2, 3, 4, 5}; int n = arr.Length; int k = 3; minRange(arr, n, k);}} // This code is contributed by Shrikant13",
"e": 8238,
"s": 6766,
"text": null
},
{
"code": "<script>// Javascript program to find minimum// range that contains exactly// k distinct numbers. // Prints the minimum range // that contains exactly k // distinct numbers. function minRange(arr,n,k) { let l = 0, r = n; // Consider every element // as starting point. for (let i = 0; i < n; i++) { // Find the smallest window // starting with arr[i] and // containing exactly k // distinct elements. let s = new Set(); let j; for (j = i; j < n; j++) { s.add(arr[j]); if (s.size == k) { if ((j - i) < (r - l)) { r = j; l = i; } break; } } // There are less than k // distinct elements now, // so no need to continue. if (j == n) break; } // If there was no window // with k distinct elements // (k is greater than total // distinct elements) if (l == 0 && r == n) document.write(\"Invalid k\"); else document.write(l + \" \" + r); } // Driver code let arr=[1, 2, 3, 4, 5]; let n = arr.length; let k = 3; minRange(arr, n, k); // This code is contributed by avanitrachhadiya2155</script>",
"e": 9582,
"s": 8238,
"text": null
},
{
"code": null,
"e": 9586,
"s": 9582,
"text": "0 2"
},
{
"code": null,
"e": 9785,
"s": 9586,
"text": "Time Complexity : O(N^2) ,where N is the number of elements in the arrayEvery time picking the end points of the subarray using two nested loops(one inside another) makes the time complexity O(N^2)."
},
{
"code": null,
"e": 9869,
"s": 9785,
"text": "Space Complexity : O(N)In the worst case, we can have all ‘N’ elements in our set."
},
{
"code": null,
"e": 9908,
"s": 9869,
"text": "Approach 2 : (Sliding Window Approach)"
},
{
"code": null,
"e": 10048,
"s": 9908,
"text": "Optimization is get rid of the repeated work while making all subarray, all subarray will not help to find the resultant. The approach is –"
},
{
"code": null,
"e": 10056,
"s": 10048,
"text": "Steps :"
},
{
"code": null,
"e": 10116,
"s": 10056,
"text": "Initialize a map to store the frequencies of each element. "
},
{
"code": null,
"e": 10196,
"s": 10116,
"text": "Taking two variables as taken before : start and end of the required subarray. "
},
{
"code": null,
"e": 10321,
"s": 10196,
"text": "And here we are using i and j as the starting and ending index of the window respectively, initializing as i = 0 and j = 0. "
},
{
"code": null,
"e": 11848,
"s": 10321,
"text": "Will traverse the array while the ending pointer of our window reach the end of given array. i.e. while( j < n) 1. Add the current element to the map map[ arr[j] ]++ and make j pointing to the next index 2. Consider the window [ i, j-1 ] (reason for ‘j-1’ is as we incremented the value of ‘j’ just after insertion in last step) check whether its size is equal to k 3. If window size is lesser then k then continue 4. But if window size == k, then check its length whether it is the resultant subarray or not. 5. After that we need to move our window, but in order to move our window, we have to check the starting element of our current window (i.e. i-th). If the i-th element is having a frequency of 1 then erase it from the map and else decrease its frequency by 1. And increase the i-value. Make i to point to the next element.( For understanding the reason of erase and decreasing frequency, take an example : 4 2 2 3 4 4 3 and k = 3 when we are dealing with the window 2 2 3 4 then ‘i’ would have pointed to the start of window (first 2) and ‘j’ would have pointed to the last of window (at 4). Now while moving forward (by one position), if the window totally erase 2 from the map, (and make window 2 3 4 4) then map would contain the information that 2 is not in the map but it is wrong so we will decrease the count of 2. Similarly, in case of having frequency == 1, and about to leave the window, the map should not contain the frequency of the element which not there in the window. ) "
},
{
"code": null,
"e": 11852,
"s": 11848,
"text": "C++"
},
{
"code": null,
"e": 11857,
"s": 11852,
"text": "Java"
},
{
"code": null,
"e": 11865,
"s": 11857,
"text": "Python3"
},
{
"code": null,
"e": 11868,
"s": 11865,
"text": "C#"
},
{
"code": null,
"e": 11879,
"s": 11868,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum range that// contains exactly k distinct numbers.#include <bits/stdc++.h>using namespace std; // prints the minimum range that contains exactly// k distinct numbers.void minRange(int arr[], int n, int k){ /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; unordered_map<int, int> map; /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map[arr[j]]++; j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (subArrayLen > windowLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map[arr[i]] == 1) map.erase(arr[i]); // decrease freq by 1 else map[arr[i]]--; // move the starting index of window i++; } } if (start == 0 && end == n) cout << \"Invalid k\" << endl; else cout << start << \" \" << end << endl;} // Driver code for above function.int main(){ int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0;} // This code is contributed by Rajdeep",
"e": 13738,
"s": 11879,
"text": null
},
{
"code": "// Java program to find minimum range that// contains exactly k distinct numbers.import java.util.*; class GFG { // Prints the minimum range that contains exactly // k distinct numbers. static void minRange(int arr[], int n, int k) { /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; HashMap<Integer, Integer> map = new HashMap<>(); /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map.put(arr[j], map.getOrDefault(arr[j], 0) + 1); j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (windowLen < subArrayLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map.get(arr[i]) == 1) map.remove(arr[i]); // decrease freq by 1 else map.put(arr[i], map.get(arr[i]) - 1); // move the starting index of window i++; } } if (start == 0 && end == n) System.out.println(\"Invalid k\"); else System.out.println(start + \" \" + end); } // Driver code public static void main(String[] args) { int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = arr.length; int k = 3; minRange(arr, n, k); }} // This code is contributed by Rajdeep",
"e": 16002,
"s": 13738,
"text": null
},
{
"code": "# Python3 program to find the minimum range# that contains exactly k distinct numbers.from collections import defaultdict # Prints the minimum range that contains# exactly k distinct numbers.def minRange(arr, n, k): # Initially left and right side is -1 # and -1, number of distinct elements # are zero and range is n. l, r = 0, n i = 0 j = -1 # Initialize right side hm = defaultdict(lambda:0) while i < n: while j < n: # increment right side. j += 1 # if number of distinct elements less than k. if len(hm) < k and j < n: hm[arr[j]] += 1 # if distinct elements are equal to k # and length is less than previous length. if len(hm) == k and ((r - l) >= (j - i)): l, r = i, j break # if number of distinct elements less # than k, then break. if len(hm) < k: break # if distinct elements equals to k then # try to increment left side. while len(hm) == k: if hm[arr[i]] == 1: del(hm[arr[i]]) else: hm[arr[i]] -= 1 # increment left side. i += 1 # it is same as explained in above loop. if len(hm) == k and (r - l) >= (j - i): l, r = i, j if hm[arr[i]] == 1: del(hm[arr[i]]) else: hm[arr[i]] -= 1 i += 1 if l == 0 and r == n: print(\"Invalid k\") else: print(l, r) # Driver code for above function.if __name__ == \"__main__\": arr = [1, 1, 2, 2, 3, 3, 4, 5] n = len(arr) k = 3 minRange(arr, n, k) # This code is contributed by Rituraj Jain",
"e": 17831,
"s": 16002,
"text": null
},
{
"code": "// C# program to find minimum// range that contains exactly// k distinct numbers.using System;using System.Collections.Generic;class GFG{ // Prints the minimum// range that contains exactly// k distinct numbers.static void minRange(int []arr, int n, int k){ // Initially left and // right side is -1 and -1, // number of distinct // elements are zero and // range is n. int l = 0, r = n; // Initialize right side int j = -1; Dictionary<int, int> hm = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { while (j < n) { // Increment right side. j++; // If number of distinct elements less // than k. if (j < n && hm.Count < k) if(hm.ContainsKey(arr[j])) hm[arr[j]] = hm[arr[j]] + 1; else hm.Add(arr[j], 1); // If distinct elements are equal to k // and length is less than previous length. if (hm.Count == k && ((r - l) >= (j - i))) { l = i; r = j; break; } } // If number of distinct elements less // than k, then break. if (hm.Count < k) break; // If distinct elements equals to k then // try to increment left side. while (hm.Count == k) { if (hm.ContainsKey(arr[i]) && hm[arr[i]] == 1) hm.Remove(arr[i]); else { if(hm.ContainsKey(arr[i])) hm[arr[i]] = hm[arr[i]] - 1; } // Increment left side. i++; // It is same as explained in above loop. if (hm.Count == k && (r - l) >= (j - i)) { l = i; r = j; } } if (hm.ContainsKey(arr[i]) && hm[arr[i]] == 1) hm.Remove(arr[i]); else if(hm.ContainsKey(arr[i])) hm[arr[i]] = hm[arr[i]] - 1; } if (l == 0 && r == n) Console.WriteLine(\"Invalid k\"); else Console.WriteLine(l + \" \" + r);} // Driver codepublic static void Main(String[] args){ int []arr = {1, 1, 2, 2, 3, 3, 4, 5}; int n = arr.Length; int k = 3; minRange(arr, n, k);}} // This code is contributed by shikhasingrajput",
"e": 19958,
"s": 17831,
"text": null
},
{
"code": "<script>// Javascript program to find minimum// range that contains exactly// k distinct numbers // Prints the minimum// range that contains exactly// k distinct numbers. function minRange(arr,n,k) { // Initially left and right side is -1 and -1, // number of distinct elements are zero and // range is n. let l = 0, r = n; // Initialize right side let j = -1; let hm = new Map(); for(let i = 0; i < n; i++) { while (j < n) { // Increment right side. j++; // If number of distinct elements less // than k. if (j < n && hm.size < k) { if(hm.has(arr[j])) hm.set(arr[j], hm.get(arr[j]) + 1); else hm.set(arr[j],1); } // If distinct elements are equal to k // and length is less than previous length. if (hm.size == k && ((r - l) >= (j - i))) { l = i; r = j; break; } } // If number of distinct elements less // than k, then break. if (hm.size < k) break; // If distinct elements equals to k then // try to increment left side. while (hm.size == k) { if (hm.has(arr[i]) && hm.get(arr[i]) == 1) hm.delete(arr[i]); else if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) - 1); // Increment left side. i++; // It is same as explained in above loop. if (hm.size == k && (r - l) >= (j - i)) { l = i; r = j; } } if (hm.has(arr[i]) && hm.get(arr[i]) == 1) hm.delete(arr[i]); else if(hm.has(arr[i])) hm.set(arr[i],hm.get(arr[i]) - 1); } if (l == 0 && r == n) document.write(\"Invalid k\"); else document.write(l + \" \" + r); } // Driver code let arr=[1, 1, 2, 2, 3, 3, 4, 5]; let n = arr.length; let k = 3; minRange(arr, n, k); // This code is contributed by rag2127</script>",
"e": 22289,
"s": 19958,
"text": null
},
{
"code": null,
"e": 22293,
"s": 22289,
"text": "5 7"
},
{
"code": null,
"e": 22445,
"s": 22293,
"text": "Time Complexity : O(N) ,where N is the number of elements in the arrayIn the worst case, each element will be added once and removed once from the map."
},
{
"code": null,
"e": 22530,
"s": 22445,
"text": "Space Complexity : O(K)In the worst case, we can have only ‘K’ elements in our map."
},
{
"code": null,
"e": 22954,
"s": 22530,
"text": "This article is contributed by Rajdeep Mallick. 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": 22967,
"s": 22954,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 22979,
"s": 22967,
"text": "shrikanth13"
},
{
"code": null,
"e": 22985,
"s": 22979,
"text": "ukasp"
},
{
"code": null,
"e": 22998,
"s": 22985,
"text": "rituraj_jain"
},
{
"code": null,
"e": 23009,
"s": 22998,
"text": "jrishabh99"
},
{
"code": null,
"e": 23026,
"s": 23009,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 23047,
"s": 23026,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 23055,
"s": 23047,
"text": "rag2127"
},
{
"code": null,
"e": 23073,
"s": 23055,
"text": "rajdeepmallick999"
},
{
"code": null,
"e": 23088,
"s": 23073,
"text": "sagartomar9927"
},
{
"code": null,
"e": 23106,
"s": 23088,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 23121,
"s": 23106,
"text": "sliding-window"
},
{
"code": null,
"e": 23128,
"s": 23121,
"text": "Arrays"
},
{
"code": null,
"e": 23133,
"s": 23128,
"text": "Hash"
},
{
"code": null,
"e": 23148,
"s": 23133,
"text": "sliding-window"
},
{
"code": null,
"e": 23155,
"s": 23148,
"text": "Arrays"
},
{
"code": null,
"e": 23160,
"s": 23155,
"text": "Hash"
}
] |
Add elements to HashSet in Java
|
First, create a HashSet −
HashSet hs = new HashSet();
Now, add some elements using the add() method. Set the elements as a parameter. Here, we have set string −
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
The following is an example to add elements to a HashSet −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");
System.out.println(hs);
}
}
[A, B, C, D, E, F, K, M, N]
|
[
{
"code": null,
"e": 1213,
"s": 1187,
"text": "First, create a HashSet −"
},
{
"code": null,
"e": 1241,
"s": 1213,
"text": "HashSet hs = new HashSet();"
},
{
"code": null,
"e": 1348,
"s": 1241,
"text": "Now, add some elements using the add() method. Set the elements as a parameter. Here, we have set string −"
},
{
"code": null,
"e": 1452,
"s": 1348,
"text": "hs.add(\"B\");\nhs.add(\"A\");\nhs.add(\"D\");\nhs.add(\"E\");\nhs.add(\"C\");\nhs.add(\"F\");\nhs.add(\"K\");\nhs.add(\"M\");"
},
{
"code": null,
"e": 1511,
"s": 1452,
"text": "The following is an example to add elements to a HashSet −"
},
{
"code": null,
"e": 1522,
"s": 1511,
"text": " Live Demo"
},
{
"code": null,
"e": 1886,
"s": 1522,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n HashSet hs = new HashSet();\n // add elements to the hash set\n hs.add(\"B\");\n hs.add(\"A\");\n hs.add(\"D\");\n hs.add(\"E\");\n hs.add(\"C\");\n hs.add(\"F\");\n hs.add(\"K\");\n hs.add(\"M\");\n hs.add(\"N\");\n System.out.println(hs);\n }\n}"
},
{
"code": null,
"e": 1914,
"s": 1886,
"text": "[A, B, C, D, E, F, K, M, N]"
}
] |
How to format numbers as currency string in JavaScript ?
|
30 Sep, 2019
A number, represented as monetary value, creates an impact and becomes much more readable, and that’s the reason behind formatting a number as currency.For example, a number, let’s say 100000 when represented as $100,000.00 it becomes pretty much understand that it represents a monetary value, and the currency in which it is formatted is USD.
Different countries have different currencies, as well as different conventions to display monetary values. For example, USA follows the International Numbering System for representing USD, on the other hand, India follows Indian Numbering System for representing INR.
Syntax:
Intl.NumberFormat('en-US', {style: 'currency', currency: 'target currency'})
.format(monetary_value);
Explanation:The ‘en-INR’ and ‘en-US’ is used as the locale here, a list of all the locales can be found from here, and the currency used here is ‘INR’ and ‘USD’, but all the standard currencies are supported. Choosing a different locale and currency will format you monetary value accordingly.
Example 1:
<!DOCTYPE html><html> <head> <title> Formating number in currency string </title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h4> Formatting 4800 as INR </h4> <script> var format = new Intl.NumberFormat('en-INR', { style: 'currency', currency: 'INR', minimumFractionDigits: 2, }); // for 4800 INR document.write(format.format(4800)); </script> <center></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Currency format</title> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <!-- End of CDN --></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Format numbers as currency string in JavaScript </h4> <b>Example 1: Locale: 'en-IN' Currency: 'INR'</b> <p>Course ABC Fees: 783984.356 (Formatting Not Used)</p> <p>Course ABC Fees: <span class="currency-inr">783984.356</span> (Formatting Used) </p> <b>Example 2: Locale: 'en-US' Currency: 'USD'</b> <p>Course ABC Fees: 783984.356 (Formatting Not Used)</p> <p>Course ABC Fees: <span class="currency-usd">783984.356</span> (Formatting Used) </p> <script type="text/javascript"> $('.currency-inr').each(function() { var monetary_value = $(this).text(); var i = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(monetary_value); $(this).text(i); }); $('.currency-usd').each(function() { var monetary_value = $(this).text(); var i = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(monetary_value); $(this).text(i); }); </script> </center></body> </html>
Output:Note: We are using ECMAScript Internationalization API (Intl Object) for formatting purpose, that comes under the category of JavaScript Standard built-in objects and jQuery for DOM Manipulation.
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
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": 54,
"s": 26,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 399,
"s": 54,
"text": "A number, represented as monetary value, creates an impact and becomes much more readable, and that’s the reason behind formatting a number as currency.For example, a number, let’s say 100000 when represented as $100,000.00 it becomes pretty much understand that it represents a monetary value, and the currency in which it is formatted is USD."
},
{
"code": null,
"e": 668,
"s": 399,
"text": "Different countries have different currencies, as well as different conventions to display monetary values. For example, USA follows the International Numbering System for representing USD, on the other hand, India follows Indian Numbering System for representing INR."
},
{
"code": null,
"e": 676,
"s": 668,
"text": "Syntax:"
},
{
"code": null,
"e": 783,
"s": 676,
"text": "Intl.NumberFormat('en-US', {style: 'currency', currency: 'target currency'})\n.format(monetary_value); \n"
},
{
"code": null,
"e": 1077,
"s": 783,
"text": "Explanation:The ‘en-INR’ and ‘en-US’ is used as the locale here, a list of all the locales can be found from here, and the currency used here is ‘INR’ and ‘USD’, but all the standard currencies are supported. Choosing a different locale and currency will format you monetary value accordingly."
},
{
"code": null,
"e": 1088,
"s": 1077,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Formating number in currency string </title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h4> Formatting 4800 as INR </h4> <script> var format = new Intl.NumberFormat('en-INR', { style: 'currency', currency: 'INR', minimumFractionDigits: 2, }); // for 4800 INR document.write(format.format(4800)); </script> <center></body> </html>",
"e": 1634,
"s": 1088,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Output:"
},
{
"code": null,
"e": 1653,
"s": 1642,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>Currency format</title> <!-- jQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"> </script> <!-- End of CDN --></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Format numbers as currency string in JavaScript </h4> <b>Example 1: Locale: 'en-IN' Currency: 'INR'</b> <p>Course ABC Fees: 783984.356 (Formatting Not Used)</p> <p>Course ABC Fees: <span class=\"currency-inr\">783984.356</span> (Formatting Used) </p> <b>Example 2: Locale: 'en-US' Currency: 'USD'</b> <p>Course ABC Fees: 783984.356 (Formatting Not Used)</p> <p>Course ABC Fees: <span class=\"currency-usd\">783984.356</span> (Formatting Used) </p> <script type=\"text/javascript\"> $('.currency-inr').each(function() { var monetary_value = $(this).text(); var i = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(monetary_value); $(this).text(i); }); $('.currency-usd').each(function() { var monetary_value = $(this).text(); var i = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(monetary_value); $(this).text(i); }); </script> </center></body> </html> ",
"e": 3449,
"s": 1653,
"text": null
},
{
"code": null,
"e": 3652,
"s": 3449,
"text": "Output:Note: We are using ECMAScript Internationalization API (Intl Object) for formatting purpose, that comes under the category of JavaScript Standard built-in objects and jQuery for DOM Manipulation."
},
{
"code": null,
"e": 3668,
"s": 3652,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3675,
"s": 3668,
"text": "Picked"
},
{
"code": null,
"e": 3686,
"s": 3675,
"text": "JavaScript"
},
{
"code": null,
"e": 3705,
"s": 3686,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3722,
"s": 3705,
"text": "Web Technologies"
},
{
"code": null,
"e": 3749,
"s": 3722,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3847,
"s": 3749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3908,
"s": 3847,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3980,
"s": 3908,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4020,
"s": 3980,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4062,
"s": 4020,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4103,
"s": 4062,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4136,
"s": 4103,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4198,
"s": 4136,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4259,
"s": 4198,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4309,
"s": 4259,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Kth largest pairwise product possible from given two Arrays
|
11 Feb, 2022
Given two arrays arr[] and brr[] containing integers. The task is to find the Kth largest product of a pair (arr[i], brr[j]).
Examples:
Input: arr[] = {1, -2, 3}, brr[] = {3, -4, 0}, K = 3Output: 3Explanation: All product combinations in descending order are : [9, 8, 3, 0, 0, 0, -4, -6, -12] and 3rd largest element is 3.
Input: arr[] = {-1, -5, -3}, brr[] = {-3, -4, 0}, K =5Output: 4Explanation: All product combinations in descending order are : [20, 15, 12, 9, 4, 3, 0, 0, 0] and 5th largest element is 4.
Naive Approach: Generate all the possible products combination for each element in array arr[] with each element in array brr[]. Then sort the array of results and return the Kth element of the results array.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int solve(int a[ ], int n, int b[ ], int m, int k) { vector<int> ans; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.push_back(prod); } } // Sort array in descending order sort(ans.begin(), ans.end(), greater<int>()); // Finally return (k - 1)th index // as indexing begin from 0. return ans[k - 1];} // Driver codeint main(){ int arr[ ] = { 1, -2, 3 }; int brr[ ] = { 3, -4, 0 }; int K = 3; int n = sizeof(arr) / sizeof(int); int m = sizeof(brr) / sizeof(int); // Function Call int val = solve(arr, n, brr, m, K); cout << val; return 0;} // This code is contributed by hrithikgarg03188
// Java code for the above approachimport java.util.Collections;import java.util.LinkedList;import java.util.List; class GFG { static int solve(int[] a, int[] b, int k) { List<Integer> ans = new LinkedList<>(); int n = a.length; int m = b.length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.add(prod); } } // Sort array in descending order Collections.sort(ans, (x, y) -> y - x); // Finally return (k - 1)th index // as indexing begins from 0. return (ans.get(k - 1)); } // Driver Code public static void main(String[] args) { int[] arr = { 1, -2, 3 }; int[] brr = { 3, -4, 0 }; int K = 3; // Function Call int val = solve(arr, brr, K); System.out.println(val); }} // This code is contributed by 29AjayKumar
# Python program for above approachdef solve(a, b, k): ans = [] n = len(a) m = len(b) for i in range(n): for j in range(m): # take product prod = a[i]*b[j] ans.append(prod) # Sort array in descending order ans.sort(reverse = True) # Finally return (k-1)th index # as indexing begins from 0. return (ans[k-1]) # Driver Codearr = [1, -2, 3]brr = [3, -4, 0]K = 3 # Function Callval = solve(arr, brr, K) print(val)
// C# code for the above approachusing System;using System.Collections.Generic; public class GFG { static int solve(int[] a, int[] b, int k) { List<int> ans = new List<int>(); int n = a.Length; int m = b.Length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.Add(prod); } } // Sort array in descending order ans.Sort((x, y) => y - x); // Finally return (k - 1)th index // as indexing begins from 0. return (ans[k - 1]); } // Driver Code public static void Main(String[] args) { int[] arr = { 1, -2, 3 }; int[] brr = { 3, -4, 0 }; int K = 3; // Function Call int val = solve(arr, brr, K); Console.WriteLine(val); }} // This code is contributed by 29AjayKumar
<script> // JavaScript code for the above approach function solve(a, b, k) { ans = [] n = a.length m = b.length for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // take product prod = a[i] * b[j] ans.push(prod) } } // Sort array in descending order ans.sort(function (a, b) { return b - a }) // Finally return (k - 1)th index // as indexing begins from 0. return (ans[k - 1]) } // Driver Code arr = [1, -2, 3] brr = [3, -4, 0] K = 3 // Function Call val = solve(arr, brr, K) document.write(val) // This code is contributed by Potta Lokesh </script>
3
Time Complexity: O(N*M + (N+M) * Log(N+M)) Auxiliary Space: O(N+M)
Efficient Approach: This problem can be solved by using the Greedy Approach and Heaps. Follow the steps below to solve the given problem.
Sort the brr[] array.
Keep larger size array in the array arr[].
Create a max heap to store the elements with their respective indices.
Traverse each element from array arr[]. The element can be either positive or negative.
Positive: Multiply current element from arr[] with the largest element of sorted array brr[]. To ensure that maximum element is obtained.
Negative: In this case multiply with the smallest value, i.e. with the first element from array brr[]. This is due to the property of negation, as a larger value can be obtained by multiplying with the smallest one.
Insert three values into heap such that : ( product, i, j ) where i & j are the indices of arrays arr[] and brr[].
Now run a for loop K times and pop elements from the heap.
Now check if the value present at arr[i] is positive or negative
Positive: So next_j = ( current_j – 1) because as max heap is been used, all the higher indices might have been already popped from the heap.
Negative: next_j = (current_j +1) because all the smaller values yielding larger elements might have been already popped from the heap.
Finally, return the answer
Note: Max heap is implemented with the help of min-heap, by negating the signs of the values while inserting them into the heap in Python.
Below is the implementation of the above approach.
Python3
# Python program for above approachfrom heap import heappush as push, heappop as pop def solve(a, b, k): # Sorting array b in ascending order b.sort() n, m = len(a), len(b) # Checking if size(a) > size(b) if (n < m): # Otherwise swap the arrays return solve(b, a, k) heap = [] # Traverse all elements in array a for i in range(n): curr = a[i] # curr element is negative if (curr < 0): # Product with smallest value val = curr * b[0] # Pushing negative val due to max heap # and i as well jth index push(heap, (-val, i, 0)) else: # Product with largest value val = curr * b[-1] # Pushing negative val due to max heap # and i as well jth index push(heap, (-val, i, m-1)) # Subtract 1 due to zero indexing k = k-1 # Remove k-1 largest items from heap for _ in range(k): val, i, j = pop(heap) val = -val # if a[i] is negative, increment ith index if (a[i] < 0): next_j = j + 1 # if a[i] is positive, decrement jth index else: next_j = j-1 # if index is valid if (0 <= next_j < m): new_val = a[i] * b[next_j] # Pushing new_val in the heap push(heap, (-new_val, i, next_j)) # Finally return first val in the heap return -(heap[0][0]) # Driver Codearr = [1, -2, 3]brr = [3, -4, 0]K = 3 # Function Callval = solve(arr, brr, K) # Print the resultprint(val)
3
Time Complexity: O(M*Log(M) + K*Log(N)) Auxiliary Space: O(N)
lokeshpotta20
29AjayKumar
hrithikgarg03188
rkbhola5
simmytarika5
surinderdawra388
avtarkumar719
Algo-Geek 2021
Algo Geek
Arrays
Greedy
Heap
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Number of ways to divide a N elements equally into group of at least 2
Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X
Sort strings on the basis of their numeric part
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Check if the given string is valid English word or not
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "Given two arrays arr[] and brr[] containing integers. The task is to find the Kth largest product of a pair (arr[i], brr[j])."
},
{
"code": null,
"e": 165,
"s": 154,
"text": "Examples: "
},
{
"code": null,
"e": 352,
"s": 165,
"text": "Input: arr[] = {1, -2, 3}, brr[] = {3, -4, 0}, K = 3Output: 3Explanation: All product combinations in descending order are : [9, 8, 3, 0, 0, 0, -4, -6, -12] and 3rd largest element is 3."
},
{
"code": null,
"e": 540,
"s": 352,
"text": "Input: arr[] = {-1, -5, -3}, brr[] = {-3, -4, 0}, K =5Output: 4Explanation: All product combinations in descending order are : [20, 15, 12, 9, 4, 3, 0, 0, 0] and 5th largest element is 4."
},
{
"code": null,
"e": 749,
"s": 540,
"text": "Naive Approach: Generate all the possible products combination for each element in array arr[] with each element in array brr[]. Then sort the array of results and return the Kth element of the results array."
},
{
"code": null,
"e": 753,
"s": 749,
"text": "C++"
},
{
"code": null,
"e": 758,
"s": 753,
"text": "Java"
},
{
"code": null,
"e": 766,
"s": 758,
"text": "Python3"
},
{
"code": null,
"e": 769,
"s": 766,
"text": "C#"
},
{
"code": null,
"e": 780,
"s": 769,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int solve(int a[ ], int n, int b[ ], int m, int k) { vector<int> ans; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.push_back(prod); } } // Sort array in descending order sort(ans.begin(), ans.end(), greater<int>()); // Finally return (k - 1)th index // as indexing begin from 0. return ans[k - 1];} // Driver codeint main(){ int arr[ ] = { 1, -2, 3 }; int brr[ ] = { 3, -4, 0 }; int K = 3; int n = sizeof(arr) / sizeof(int); int m = sizeof(brr) / sizeof(int); // Function Call int val = solve(arr, n, brr, m, K); cout << val; return 0;} // This code is contributed by hrithikgarg03188",
"e": 1515,
"s": 780,
"text": null
},
{
"code": "// Java code for the above approachimport java.util.Collections;import java.util.LinkedList;import java.util.List; class GFG { static int solve(int[] a, int[] b, int k) { List<Integer> ans = new LinkedList<>(); int n = a.length; int m = b.length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.add(prod); } } // Sort array in descending order Collections.sort(ans, (x, y) -> y - x); // Finally return (k - 1)th index // as indexing begins from 0. return (ans.get(k - 1)); } // Driver Code public static void main(String[] args) { int[] arr = { 1, -2, 3 }; int[] brr = { 3, -4, 0 }; int K = 3; // Function Call int val = solve(arr, brr, K); System.out.println(val); }} // This code is contributed by 29AjayKumar",
"e": 2378,
"s": 1515,
"text": null
},
{
"code": "# Python program for above approachdef solve(a, b, k): ans = [] n = len(a) m = len(b) for i in range(n): for j in range(m): # take product prod = a[i]*b[j] ans.append(prod) # Sort array in descending order ans.sort(reverse = True) # Finally return (k-1)th index # as indexing begins from 0. return (ans[k-1]) # Driver Codearr = [1, -2, 3]brr = [3, -4, 0]K = 3 # Function Callval = solve(arr, brr, K) print(val)",
"e": 2861,
"s": 2378,
"text": null
},
{
"code": "// C# code for the above approachusing System;using System.Collections.Generic; public class GFG { static int solve(int[] a, int[] b, int k) { List<int> ans = new List<int>(); int n = a.Length; int m = b.Length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // take product int prod = a[i] * b[j]; ans.Add(prod); } } // Sort array in descending order ans.Sort((x, y) => y - x); // Finally return (k - 1)th index // as indexing begins from 0. return (ans[k - 1]); } // Driver Code public static void Main(String[] args) { int[] arr = { 1, -2, 3 }; int[] brr = { 3, -4, 0 }; int K = 3; // Function Call int val = solve(arr, brr, K); Console.WriteLine(val); }} // This code is contributed by 29AjayKumar",
"e": 3671,
"s": 2861,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach function solve(a, b, k) { ans = [] n = a.length m = b.length for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // take product prod = a[i] * b[j] ans.push(prod) } } // Sort array in descending order ans.sort(function (a, b) { return b - a }) // Finally return (k - 1)th index // as indexing begins from 0. return (ans[k - 1]) } // Driver Code arr = [1, -2, 3] brr = [3, -4, 0] K = 3 // Function Call val = solve(arr, brr, K) document.write(val) // This code is contributed by Potta Lokesh </script>",
"e": 4499,
"s": 3671,
"text": null
},
{
"code": null,
"e": 4501,
"s": 4499,
"text": "3"
},
{
"code": null,
"e": 4570,
"s": 4503,
"text": "Time Complexity: O(N*M + (N+M) * Log(N+M)) Auxiliary Space: O(N+M)"
},
{
"code": null,
"e": 4709,
"s": 4570,
"text": "Efficient Approach: This problem can be solved by using the Greedy Approach and Heaps. Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 4731,
"s": 4709,
"text": "Sort the brr[] array."
},
{
"code": null,
"e": 4774,
"s": 4731,
"text": "Keep larger size array in the array arr[]."
},
{
"code": null,
"e": 4845,
"s": 4774,
"text": "Create a max heap to store the elements with their respective indices."
},
{
"code": null,
"e": 4933,
"s": 4845,
"text": "Traverse each element from array arr[]. The element can be either positive or negative."
},
{
"code": null,
"e": 5071,
"s": 4933,
"text": "Positive: Multiply current element from arr[] with the largest element of sorted array brr[]. To ensure that maximum element is obtained."
},
{
"code": null,
"e": 5287,
"s": 5071,
"text": "Negative: In this case multiply with the smallest value, i.e. with the first element from array brr[]. This is due to the property of negation, as a larger value can be obtained by multiplying with the smallest one."
},
{
"code": null,
"e": 5402,
"s": 5287,
"text": "Insert three values into heap such that : ( product, i, j ) where i & j are the indices of arrays arr[] and brr[]."
},
{
"code": null,
"e": 5461,
"s": 5402,
"text": "Now run a for loop K times and pop elements from the heap."
},
{
"code": null,
"e": 5526,
"s": 5461,
"text": "Now check if the value present at arr[i] is positive or negative"
},
{
"code": null,
"e": 5668,
"s": 5526,
"text": "Positive: So next_j = ( current_j – 1) because as max heap is been used, all the higher indices might have been already popped from the heap."
},
{
"code": null,
"e": 5805,
"s": 5668,
"text": "Negative: next_j = (current_j +1) because all the smaller values yielding larger elements might have been already popped from the heap."
},
{
"code": null,
"e": 5832,
"s": 5805,
"text": "Finally, return the answer"
},
{
"code": null,
"e": 5972,
"s": 5832,
"text": "Note: Max heap is implemented with the help of min-heap, by negating the signs of the values while inserting them into the heap in Python."
},
{
"code": null,
"e": 6023,
"s": 5972,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 6031,
"s": 6023,
"text": "Python3"
},
{
"code": "# Python program for above approachfrom heap import heappush as push, heappop as pop def solve(a, b, k): # Sorting array b in ascending order b.sort() n, m = len(a), len(b) # Checking if size(a) > size(b) if (n < m): # Otherwise swap the arrays return solve(b, a, k) heap = [] # Traverse all elements in array a for i in range(n): curr = a[i] # curr element is negative if (curr < 0): # Product with smallest value val = curr * b[0] # Pushing negative val due to max heap # and i as well jth index push(heap, (-val, i, 0)) else: # Product with largest value val = curr * b[-1] # Pushing negative val due to max heap # and i as well jth index push(heap, (-val, i, m-1)) # Subtract 1 due to zero indexing k = k-1 # Remove k-1 largest items from heap for _ in range(k): val, i, j = pop(heap) val = -val # if a[i] is negative, increment ith index if (a[i] < 0): next_j = j + 1 # if a[i] is positive, decrement jth index else: next_j = j-1 # if index is valid if (0 <= next_j < m): new_val = a[i] * b[next_j] # Pushing new_val in the heap push(heap, (-new_val, i, next_j)) # Finally return first val in the heap return -(heap[0][0]) # Driver Codearr = [1, -2, 3]brr = [3, -4, 0]K = 3 # Function Callval = solve(arr, brr, K) # Print the resultprint(val)",
"e": 7610,
"s": 6031,
"text": null
},
{
"code": null,
"e": 7612,
"s": 7610,
"text": "3"
},
{
"code": null,
"e": 7676,
"s": 7614,
"text": "Time Complexity: O(M*Log(M) + K*Log(N)) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 7690,
"s": 7676,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 7702,
"s": 7690,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7719,
"s": 7702,
"text": "hrithikgarg03188"
},
{
"code": null,
"e": 7728,
"s": 7719,
"text": "rkbhola5"
},
{
"code": null,
"e": 7741,
"s": 7728,
"text": "simmytarika5"
},
{
"code": null,
"e": 7758,
"s": 7741,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7772,
"s": 7758,
"text": "avtarkumar719"
},
{
"code": null,
"e": 7787,
"s": 7772,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 7797,
"s": 7787,
"text": "Algo Geek"
},
{
"code": null,
"e": 7804,
"s": 7797,
"text": "Arrays"
},
{
"code": null,
"e": 7811,
"s": 7804,
"text": "Greedy"
},
{
"code": null,
"e": 7816,
"s": 7811,
"text": "Heap"
},
{
"code": null,
"e": 7829,
"s": 7816,
"text": "Mathematical"
},
{
"code": null,
"e": 7837,
"s": 7829,
"text": "Sorting"
},
{
"code": null,
"e": 7844,
"s": 7837,
"text": "Arrays"
},
{
"code": null,
"e": 7851,
"s": 7844,
"text": "Greedy"
},
{
"code": null,
"e": 7864,
"s": 7851,
"text": "Mathematical"
},
{
"code": null,
"e": 7872,
"s": 7864,
"text": "Sorting"
},
{
"code": null,
"e": 7877,
"s": 7872,
"text": "Heap"
},
{
"code": null,
"e": 7975,
"s": 7877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8046,
"s": 7975,
"text": "Number of ways to divide a N elements equally into group of at least 2"
},
{
"code": null,
"e": 8122,
"s": 8046,
"text": "Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X"
},
{
"code": null,
"e": 8170,
"s": 8122,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 8267,
"s": 8170,
"text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index"
},
{
"code": null,
"e": 8322,
"s": 8267,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 8337,
"s": 8322,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8383,
"s": 8337,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8451,
"s": 8383,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8495,
"s": 8451,
"text": "Top 50 Array Coding Problems for Interviews"
}
] |
C++ set for user define data type
|
19 Apr, 2018
The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.).
And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the property of the set that value kept in the set must be ascending or descending order. And while doing so the compiler cant compare two structures(as they are user-defined) and that’s the reason to why the compiler shows us the error message.So, in order to store a structure in a set, some comparison function need s to be designed. Implementation of this is given below:
Examples:
Input : 110 102 101 115
Output : 101 102 110 115
Explanation:Here we insert a random list to the set, and when we output the set the list gets sorted in ascending order based on the comparison function we made.
Input : 3 2 34 0 76
Output : 0 2 3 34 76
// CPP implementation to use // user-defined data type in// structures#include<bits/stdc++.h>using namespace std; // Structure definitionstruct Test { int id; // This function is used by set to order // elements of Test. bool operator<(const Test& t) const { return (this->id < t.id); }}; // Driver methodint main(){ // put values in each // structure define below. Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // define a set having // structure as its elements. set<struct Test> s; // insert structure in set s.insert(t1); s.insert(t2); s.insert(t3); s.insert(t4); // define an iterator to iterate the whole set. set<struct Test>::iterator it; for (it = s.begin(); it != s.end(); it++) { // print in ascending order as required. cout << (*it).id << endl; } return 0;}
Output:
101
102
110
115
Application:a) Very useful while printing all distinct structure in sorted order.b) Insert new structure in a sorted list of structures.
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Apr, 2018"
},
{
"code": null,
"e": 258,
"s": 54,
"text": "The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.)."
},
{
"code": null,
"e": 770,
"s": 258,
"text": "And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the property of the set that value kept in the set must be ascending or descending order. And while doing so the compiler cant compare two structures(as they are user-defined) and that’s the reason to why the compiler shows us the error message.So, in order to store a structure in a set, some comparison function need s to be designed. Implementation of this is given below:"
},
{
"code": null,
"e": 780,
"s": 770,
"text": "Examples:"
},
{
"code": null,
"e": 831,
"s": 780,
"text": "Input : 110 102 101 115\nOutput : 101 102 110 115\n"
},
{
"code": null,
"e": 993,
"s": 831,
"text": "Explanation:Here we insert a random list to the set, and when we output the set the list gets sorted in ascending order based on the comparison function we made."
},
{
"code": null,
"e": 1045,
"s": 993,
"text": "Input : 3 2 34 0 76 \nOutput : 0 2 3 34 76\n"
},
{
"code": "// CPP implementation to use // user-defined data type in// structures#include<bits/stdc++.h>using namespace std; // Structure definitionstruct Test { int id; // This function is used by set to order // elements of Test. bool operator<(const Test& t) const { return (this->id < t.id); }}; // Driver methodint main(){ // put values in each // structure define below. Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // define a set having // structure as its elements. set<struct Test> s; // insert structure in set s.insert(t1); s.insert(t2); s.insert(t3); s.insert(t4); // define an iterator to iterate the whole set. set<struct Test>::iterator it; for (it = s.begin(); it != s.end(); it++) { // print in ascending order as required. cout << (*it).id << endl; } return 0;}",
"e": 1970,
"s": 1045,
"text": null
},
{
"code": null,
"e": 1978,
"s": 1970,
"text": "Output:"
},
{
"code": null,
"e": 1995,
"s": 1978,
"text": "101\n102\n110\n115\n"
},
{
"code": null,
"e": 2132,
"s": 1995,
"text": "Application:a) Very useful while printing all distinct structure in sorted order.b) Insert new structure in a sorted list of structures."
},
{
"code": null,
"e": 2140,
"s": 2132,
"text": "cpp-set"
},
{
"code": null,
"e": 2144,
"s": 2140,
"text": "STL"
},
{
"code": null,
"e": 2148,
"s": 2144,
"text": "C++"
},
{
"code": null,
"e": 2152,
"s": 2148,
"text": "STL"
},
{
"code": null,
"e": 2156,
"s": 2152,
"text": "CPP"
},
{
"code": null,
"e": 2254,
"s": 2156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2278,
"s": 2254,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2298,
"s": 2278,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2331,
"s": 2298,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2356,
"s": 2331,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2400,
"s": 2356,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2445,
"s": 2400,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2493,
"s": 2445,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2537,
"s": 2493,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2554,
"s": 2537,
"text": "std::find in C++"
}
] |
Oracle Interview Experience
|
28 Aug, 2020
Round 01: Online assessment test 1hr 47min. There is a timer for each subsection. This test has 4 sections, each section has sub-sections.
Software Engineering Aptitude: 39 Questions and the given time was 47min.
Math reasoning
Data analysis and critical thinking
Persistence
Programming and ability
Logical ability
Coding Skills: 16 Questions and the given time was 25min.
More on trees and tree traversals, language-specific.
Computer Science Knowledge: 17 Questions and the given time was 15min.
OS concepts and data structures
Big o notation and OOAD fundamentals
DBMS and CODD fundamentals
Contextual Communication: 20 Questions and the given time was 20min.
Grammatical usage
Written expression
Learnability
Reading Comprehension
Round 02: Technical Interview around 40min for me it was from 2:00 PM – 2:40 PM.
Tell me about yourself
Detect Loop in a LinkedList [have to write the code]
Reverse Words in a string [have to write the code]
What is inheritance?
What is polymorphism?
What is Paging?
Semaphore and mutex.
What is starvation in CPU scheduling algorithms?
At the end interviewer asked do you have any questions – I asked a few questions.
Round 03: Technical + HR around 1hour for me it was from 4:45 PM – 5:45 PM.
There are two friends, each having their own favourite restaurants, we need to find the restaurants that are common and with the least index sum [print all if multiple answers exist].
E.g: Have to write the code for the actual logic.
L1 = [“R1” , “R2” ,”R3” ,”R4”];
L2 = [“R3” , “R5” , “R7”];
Ans = [“R3”]; // Problem is similar to this.
Add two numbers which are given as linked lists.
E.g: Have to write the code for the actual logic.
L1 = 6->4->8 (num = 648)
L2 = 8->4->9->8 (num = 8498)
Ans = 9->1->2->6 (num = 9126)
Puzzle: You are given 20 bags each with pills of weight 1gr, except one bag which has pills of weight 1.1gr, what is the least number of times you have to weigh to find the faulty bag?[explain the logic]
What are virtual functions?
What is meant by caching? And types of caching?
Why are you interested in Oracle?
Round 04: Technical + HR around 50min for me it was from 5:50 PM – 6:40 PM.
Given a string and asked to print it in the given format S = “It is sunny outside”
E.g:
I i s o
t s u u
n t
n s
y i
d
e
Given a situation where there are students and interviewers, and asked to design the database in such a way that we need to assign the student to the interviewer and maintain the result table and feedback on each student after every round and how many students are moved to the next round[similar to zoom app.]
Would you like to go for higher studies?
Which role are you interested in?
What a person, who is not a friend of you, tells about you?
What a person, who is a friend of you, tells about you?
At the end interviewer asked do you have any questions
Round 05: HR around 10 to 20 min for me it was from 6:45 PM – 7:05 PM.
Tell me about yourself
Do you like your college?
Asked about my projects
Which programming language are you comfortable with
Work location preference
Marketing
Oracle
Interview Experiences
Oracle
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
TCS Digital Interview Questions
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Round 01: Online assessment test 1hr 47min. There is a timer for each subsection. This test has 4 sections, each section has sub-sections."
},
{
"code": null,
"e": 241,
"s": 167,
"text": "Software Engineering Aptitude: 39 Questions and the given time was 47min."
},
{
"code": null,
"e": 256,
"s": 241,
"text": "Math reasoning"
},
{
"code": null,
"e": 292,
"s": 256,
"text": "Data analysis and critical thinking"
},
{
"code": null,
"e": 304,
"s": 292,
"text": "Persistence"
},
{
"code": null,
"e": 328,
"s": 304,
"text": "Programming and ability"
},
{
"code": null,
"e": 344,
"s": 328,
"text": "Logical ability"
},
{
"code": null,
"e": 402,
"s": 344,
"text": "Coding Skills: 16 Questions and the given time was 25min."
},
{
"code": null,
"e": 456,
"s": 402,
"text": "More on trees and tree traversals, language-specific."
},
{
"code": null,
"e": 527,
"s": 456,
"text": "Computer Science Knowledge: 17 Questions and the given time was 15min."
},
{
"code": null,
"e": 559,
"s": 527,
"text": "OS concepts and data structures"
},
{
"code": null,
"e": 596,
"s": 559,
"text": "Big o notation and OOAD fundamentals"
},
{
"code": null,
"e": 623,
"s": 596,
"text": "DBMS and CODD fundamentals"
},
{
"code": null,
"e": 692,
"s": 623,
"text": "Contextual Communication: 20 Questions and the given time was 20min."
},
{
"code": null,
"e": 710,
"s": 692,
"text": "Grammatical usage"
},
{
"code": null,
"e": 729,
"s": 710,
"text": "Written expression"
},
{
"code": null,
"e": 742,
"s": 729,
"text": "Learnability"
},
{
"code": null,
"e": 764,
"s": 742,
"text": "Reading Comprehension"
},
{
"code": null,
"e": 845,
"s": 764,
"text": "Round 02: Technical Interview around 40min for me it was from 2:00 PM – 2:40 PM."
},
{
"code": null,
"e": 868,
"s": 845,
"text": "Tell me about yourself"
},
{
"code": null,
"e": 921,
"s": 868,
"text": "Detect Loop in a LinkedList [have to write the code]"
},
{
"code": null,
"e": 972,
"s": 921,
"text": "Reverse Words in a string [have to write the code]"
},
{
"code": null,
"e": 993,
"s": 972,
"text": "What is inheritance?"
},
{
"code": null,
"e": 1015,
"s": 993,
"text": "What is polymorphism?"
},
{
"code": null,
"e": 1031,
"s": 1015,
"text": "What is Paging?"
},
{
"code": null,
"e": 1052,
"s": 1031,
"text": "Semaphore and mutex."
},
{
"code": null,
"e": 1101,
"s": 1052,
"text": "What is starvation in CPU scheduling algorithms?"
},
{
"code": null,
"e": 1183,
"s": 1101,
"text": "At the end interviewer asked do you have any questions – I asked a few questions."
},
{
"code": null,
"e": 1259,
"s": 1183,
"text": "Round 03: Technical + HR around 1hour for me it was from 4:45 PM – 5:45 PM."
},
{
"code": null,
"e": 1443,
"s": 1259,
"text": "There are two friends, each having their own favourite restaurants, we need to find the restaurants that are common and with the least index sum [print all if multiple answers exist]."
},
{
"code": null,
"e": 1493,
"s": 1443,
"text": "E.g: Have to write the code for the actual logic."
},
{
"code": null,
"e": 1597,
"s": 1493,
"text": "L1 = [“R1” , “R2” ,”R3” ,”R4”];\nL2 = [“R3” , “R5” , “R7”];\nAns = [“R3”]; // Problem is similar to this."
},
{
"code": null,
"e": 1646,
"s": 1597,
"text": "Add two numbers which are given as linked lists."
},
{
"code": null,
"e": 1696,
"s": 1646,
"text": "E.g: Have to write the code for the actual logic."
},
{
"code": null,
"e": 1780,
"s": 1696,
"text": "L1 = 6->4->8 (num = 648)\nL2 = 8->4->9->8 (num = 8498)\nAns = 9->1->2->6 (num = 9126)"
},
{
"code": null,
"e": 1984,
"s": 1780,
"text": "Puzzle: You are given 20 bags each with pills of weight 1gr, except one bag which has pills of weight 1.1gr, what is the least number of times you have to weigh to find the faulty bag?[explain the logic]"
},
{
"code": null,
"e": 2012,
"s": 1984,
"text": "What are virtual functions?"
},
{
"code": null,
"e": 2060,
"s": 2012,
"text": "What is meant by caching? And types of caching?"
},
{
"code": null,
"e": 2094,
"s": 2060,
"text": "Why are you interested in Oracle?"
},
{
"code": null,
"e": 2170,
"s": 2094,
"text": "Round 04: Technical + HR around 50min for me it was from 5:50 PM – 6:40 PM."
},
{
"code": null,
"e": 2253,
"s": 2170,
"text": "Given a string and asked to print it in the given format S = “It is sunny outside”"
},
{
"code": null,
"e": 2258,
"s": 2253,
"text": "E.g:"
},
{
"code": null,
"e": 2314,
"s": 2258,
"text": "I i s o\nt s u u\n n t\n n s\n y i\n d\n e"
},
{
"code": null,
"e": 2625,
"s": 2314,
"text": "Given a situation where there are students and interviewers, and asked to design the database in such a way that we need to assign the student to the interviewer and maintain the result table and feedback on each student after every round and how many students are moved to the next round[similar to zoom app.]"
},
{
"code": null,
"e": 2666,
"s": 2625,
"text": "Would you like to go for higher studies?"
},
{
"code": null,
"e": 2700,
"s": 2666,
"text": "Which role are you interested in?"
},
{
"code": null,
"e": 2760,
"s": 2700,
"text": "What a person, who is not a friend of you, tells about you?"
},
{
"code": null,
"e": 2816,
"s": 2760,
"text": "What a person, who is a friend of you, tells about you?"
},
{
"code": null,
"e": 2871,
"s": 2816,
"text": "At the end interviewer asked do you have any questions"
},
{
"code": null,
"e": 2942,
"s": 2871,
"text": "Round 05: HR around 10 to 20 min for me it was from 6:45 PM – 7:05 PM."
},
{
"code": null,
"e": 2965,
"s": 2942,
"text": "Tell me about yourself"
},
{
"code": null,
"e": 2991,
"s": 2965,
"text": "Do you like your college?"
},
{
"code": null,
"e": 3015,
"s": 2991,
"text": "Asked about my projects"
},
{
"code": null,
"e": 3067,
"s": 3015,
"text": "Which programming language are you comfortable with"
},
{
"code": null,
"e": 3092,
"s": 3067,
"text": "Work location preference"
},
{
"code": null,
"e": 3102,
"s": 3092,
"text": "Marketing"
},
{
"code": null,
"e": 3109,
"s": 3102,
"text": "Oracle"
},
{
"code": null,
"e": 3131,
"s": 3109,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3138,
"s": 3131,
"text": "Oracle"
},
{
"code": null,
"e": 3236,
"s": 3138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3306,
"s": 3236,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 3344,
"s": 3306,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 3417,
"s": 3344,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 3449,
"s": 3417,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 3505,
"s": 3449,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 3549,
"s": 3505,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 3595,
"s": 3549,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 3630,
"s": 3595,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 3668,
"s": 3630,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Two way communication between Client and Server using Win32 Threads
|
26 Jul, 2021
Prerequisite: Socket Programming in C/C++It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from. Here we will discuss the approach using Win32 Threads in C/C++.
Approach:
Use CreateThread function which creates a new thread for a process.The CreateThread method must specify the starting address of the code that the new thread is to execute. Following is the prototype of CreateThread function:HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter, DWORD dwCreationFlags,
LPDWORD lpThreadId
);
Then using WaitForSingleObject function that returns message in form of object received from client, to receive data from client. Following is the prototype of WaitForSingleObject function:DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
Use CreateThread function which creates a new thread for a process.
The CreateThread method must specify the starting address of the code that the new thread is to execute. Following is the prototype of CreateThread function:HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter, DWORD dwCreationFlags,
LPDWORD lpThreadId
);
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter, DWORD dwCreationFlags,
LPDWORD lpThreadId
);
Then using WaitForSingleObject function that returns message in form of object received from client, to receive data from client. Following is the prototype of WaitForSingleObject function:DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
DWORD WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
Creating the Server programIn the Server Program, we will be using two threads, one for Sending data to the client and another for Receiving data from the client. The process of communication stops when both Client and Server type “exit“.
Below is the implementation of the Server Program:
Server
// C++ program to create Server #include <iostream>#include <string.h>#include <winsock2.h>using namespace std; // Function that receive data// from clientDWORD WINAPI serverReceive(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created client socket SOCKET client = *(SOCKET*)lpParam; // Server executes continuously while (true) { // If received buffer gives // error then return -1 if (recv(client, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << "recv function failed with error " << WSAGetLastError() << endl; return -1; } // If Client exits if (strcmp(buffer, "exit") == 0) { cout << "Client Disconnected." << endl; break; } // Print the message // given by client that // was stored in buffer cout << "Client: " << buffer << endl; // Clear buffer message memset(buffer, 0, sizeof(buffer)); } return 1;} // Function that sends data to clientDWORD WINAPI serverSend(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created client socket SOCKET client = *(SOCKET*)lpParam; // Server executes continuously while (true) { // Input message server // wants to send to client gets(buffer); // If sending failed // return -1 if (send(client, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << "send failed with error " << WSAGetLastError() << endl; return -1; } // If server exit if (strcmp(buffer, "exit") == 0) { cout << "Thank you for using the application" << endl; break; } } return 1;} // Driver Codeint main(){ // Data WSADATA WSAData; // Created socket server // and client SOCKET server, client; // Socket address for server // and client SOCKADDR_IN serverAddr, clientAddr; WSAStartup(MAKEWORD(2, 0), &WSAData); // Making server server = socket(AF_INET, SOCK_STREAM, 0); // If invalid socket created, // return -1 if (server == INVALID_SOCKET) { cout << "Socket creation failed with error:" << WSAGetLastError() << endl; return -1; } serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(5555); // If socket error occurred, // return -1 if (bind(server, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) { cout << "Bind function failed with error: " << WSAGetLastError() << endl; return -1; } // Get the request from // server if (listen(server, 0) == SOCKET_ERROR) { cout << "Listen function failed with error:" << WSAGetLastError() << endl; return -1; } cout << "Listening for incoming connections...." << endl; // Create buffer[] char buffer[1024]; // Initialize client address int clientAddrSize = sizeof(clientAddr); // If connection established if ((client = accept(server, (SOCKADDR*)&clientAddr, &clientAddrSize)) != INVALID_SOCKET) { cout << "Client connected!" << endl; cout << "Now you can use our live chat application." << "Enter \"exit\" to disconnect" << endl; // Create variable of // type DWORD DWORD tid; // Create Thread t1 HANDLE t1 = CreateThread(NULL, 0, serverReceive, &client, 0, &tid); // If created thread // is not created if (t1 == NULL) { cout << "Thread Creation Error: " << WSAGetLastError() << endl; } // Create Thread t2 HANDLE t2 = CreateThread(NULL, 0, serverSend, &client, 0, &tid); // If created thread // is not created if (t2 == NULL) { cout << "Thread Creation Error: " << WSAGetLastError() << endl; } // Received Objects // from client WaitForSingleObject(t1, INFINITE); WaitForSingleObject(t2, INFINITE); // Close the socket closesocket(client); // If socket closing // failed. if (closesocket(server) == SOCKET_ERROR) { cout << "Close socket failed with error: " << WSAGetLastError() << endl; return -1; } WSACleanup(); }}
g++ ServerApplication.cpp -lws2_32
Creating the Client ProgramIn the Client Program, we will be using two threads one for Sending data to the server and another for Receiving data from the server. The process of communication stops when both Server and Client type “exit“.
Client
// C++ program to create client #include <iostream>#include <string.h>#include <winsock2.h>using namespace std; // Function that receive data from serverDWORD WINAPI clientReceive(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created server socket SOCKET server = *(SOCKET*)lpParam; // Client executes continuously while (true) { // If received buffer gives // error then return -1 if (recv(server, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << "recv function failed with error: " << WSAGetLastError() << endl; return -1; } // If Server exits if (strcmp(buffer, "exit") == 0) { cout << "Server disconnected." << endl; return 1; } // Print the message // given by server that // was stored in buffer cout << "Server: " << buffer << endl; // Clear buffer message memset(buffer, 0, sizeof(buffer)); } return 1;} // Function that sends data to serverDWORD WINAPI clientSend(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created server socket SOCKET server = *(SOCKET*)lpParam; // Client executes continuously while (true) { // Input message client // wants to send to server gets(buffer); // If sending failed // return -1 if (send(server, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << "send failed with error: " << WSAGetLastError() << endl; return -1; } // If client exit if (strcmp(buffer, "exit") == 0) { cout << "Thank you for using the application" << endl; break; } } return 1;} // Driver Codeint main(){ // Input data WSADATA WSAData; // Created socket server SOCKET server; SOCKADDR_IN addr; WSAStartup(MAKEWORD(2, 0), &WSAData); // If invalid socket created, // return -1 if ((server = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { cout << "Socket creation failed with error: " << WSAGetLastError() << endl; return -1; } addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; addr.sin_port = htons(5555); // If connection failed if (connect(server, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) { cout << "Server connection failed with error: " << WSAGetLastError() << endl; return -1; } // If connection established cout << "Connected to server!" << endl; cout << "Now you can use our live chat application." << " Enter \"exit\" to disconnect" << endl; DWORD tid; // Create Thread t1 HANDLE t1 = CreateThread(NULL, 0, clientReceive, &server, 0, &tid); // If created thread // is not created if (t1 == NULL) cout << "Thread creation error: " << GetLastError(); // Create Thread t2 HANDLE t2 = CreateThread(NULL, 0, clientSend, &server, 0, &tid); // If created thread // is not created if (t2 == NULL) cout << "Thread creation error: " << GetLastError(); // Received Objects // from client WaitForSingleObject(t1, INFINITE); WaitForSingleObject(t2, INFINITE); // Socket closed closesocket(server); WSACleanup();}
Run the ClientApplication.cpp file using the command:
g++ ClientApplication.cpp -lws2_32
Output After communication between Server and ClientThe left side command prompt is the ServerApplication and the right side command prompt is the ClientApplication.
gabaa406
Processes & Threads
Socket-programming
C++ Programs
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Dynamic _Cast in C++
Layers of OSI Model
TCP/IP Model
Basics of Computer Networking
Differences between TCP and UDP
Types of Network Topology
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 307,
"s": 52,
"text": "Prerequisite: Socket Programming in C/C++It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from. Here we will discuss the approach using Win32 Threads in C/C++."
},
{
"code": null,
"e": 317,
"s": 307,
"text": "Approach:"
},
{
"code": null,
"e": 1010,
"s": 317,
"text": "Use CreateThread function which creates a new thread for a process.The CreateThread method must specify the starting address of the code that the new thread is to execute. Following is the prototype of CreateThread function:HANDLE CreateThread( \n LPSECURITY_ATTRIBUTES lpThreadAttributes,\n DWORD dwStackSize, \n LPTHREAD_START_ROUTINE lpStartAddress,\n LPVOID lpParameter, DWORD dwCreationFlags,\n LPDWORD lpThreadId \n);\nThen using WaitForSingleObject function that returns message in form of object received from client, to receive data from client. Following is the prototype of WaitForSingleObject function:DWORD WaitForSingleObject(\n HANDLE hHandle, \n DWORD dwMilliseconds\n);\n"
},
{
"code": null,
"e": 1078,
"s": 1010,
"text": "Use CreateThread function which creates a new thread for a process."
},
{
"code": null,
"e": 1436,
"s": 1078,
"text": "The CreateThread method must specify the starting address of the code that the new thread is to execute. Following is the prototype of CreateThread function:HANDLE CreateThread( \n LPSECURITY_ATTRIBUTES lpThreadAttributes,\n DWORD dwStackSize, \n LPTHREAD_START_ROUTINE lpStartAddress,\n LPVOID lpParameter, DWORD dwCreationFlags,\n LPDWORD lpThreadId \n);\n"
},
{
"code": null,
"e": 1637,
"s": 1436,
"text": "HANDLE CreateThread( \n LPSECURITY_ATTRIBUTES lpThreadAttributes,\n DWORD dwStackSize, \n LPTHREAD_START_ROUTINE lpStartAddress,\n LPVOID lpParameter, DWORD dwCreationFlags,\n LPDWORD lpThreadId \n);\n"
},
{
"code": null,
"e": 1906,
"s": 1637,
"text": "Then using WaitForSingleObject function that returns message in form of object received from client, to receive data from client. Following is the prototype of WaitForSingleObject function:DWORD WaitForSingleObject(\n HANDLE hHandle, \n DWORD dwMilliseconds\n);\n"
},
{
"code": null,
"e": 1986,
"s": 1906,
"text": "DWORD WaitForSingleObject(\n HANDLE hHandle, \n DWORD dwMilliseconds\n);\n"
},
{
"code": null,
"e": 2225,
"s": 1986,
"text": "Creating the Server programIn the Server Program, we will be using two threads, one for Sending data to the client and another for Receiving data from the client. The process of communication stops when both Client and Server type “exit“."
},
{
"code": null,
"e": 2276,
"s": 2225,
"text": "Below is the implementation of the Server Program:"
},
{
"code": null,
"e": 2283,
"s": 2276,
"text": "Server"
},
{
"code": "// C++ program to create Server #include <iostream>#include <string.h>#include <winsock2.h>using namespace std; // Function that receive data// from clientDWORD WINAPI serverReceive(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created client socket SOCKET client = *(SOCKET*)lpParam; // Server executes continuously while (true) { // If received buffer gives // error then return -1 if (recv(client, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << \"recv function failed with error \" << WSAGetLastError() << endl; return -1; } // If Client exits if (strcmp(buffer, \"exit\") == 0) { cout << \"Client Disconnected.\" << endl; break; } // Print the message // given by client that // was stored in buffer cout << \"Client: \" << buffer << endl; // Clear buffer message memset(buffer, 0, sizeof(buffer)); } return 1;} // Function that sends data to clientDWORD WINAPI serverSend(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created client socket SOCKET client = *(SOCKET*)lpParam; // Server executes continuously while (true) { // Input message server // wants to send to client gets(buffer); // If sending failed // return -1 if (send(client, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << \"send failed with error \" << WSAGetLastError() << endl; return -1; } // If server exit if (strcmp(buffer, \"exit\") == 0) { cout << \"Thank you for using the application\" << endl; break; } } return 1;} // Driver Codeint main(){ // Data WSADATA WSAData; // Created socket server // and client SOCKET server, client; // Socket address for server // and client SOCKADDR_IN serverAddr, clientAddr; WSAStartup(MAKEWORD(2, 0), &WSAData); // Making server server = socket(AF_INET, SOCK_STREAM, 0); // If invalid socket created, // return -1 if (server == INVALID_SOCKET) { cout << \"Socket creation failed with error:\" << WSAGetLastError() << endl; return -1; } serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(5555); // If socket error occurred, // return -1 if (bind(server, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) { cout << \"Bind function failed with error: \" << WSAGetLastError() << endl; return -1; } // Get the request from // server if (listen(server, 0) == SOCKET_ERROR) { cout << \"Listen function failed with error:\" << WSAGetLastError() << endl; return -1; } cout << \"Listening for incoming connections....\" << endl; // Create buffer[] char buffer[1024]; // Initialize client address int clientAddrSize = sizeof(clientAddr); // If connection established if ((client = accept(server, (SOCKADDR*)&clientAddr, &clientAddrSize)) != INVALID_SOCKET) { cout << \"Client connected!\" << endl; cout << \"Now you can use our live chat application.\" << \"Enter \\\"exit\\\" to disconnect\" << endl; // Create variable of // type DWORD DWORD tid; // Create Thread t1 HANDLE t1 = CreateThread(NULL, 0, serverReceive, &client, 0, &tid); // If created thread // is not created if (t1 == NULL) { cout << \"Thread Creation Error: \" << WSAGetLastError() << endl; } // Create Thread t2 HANDLE t2 = CreateThread(NULL, 0, serverSend, &client, 0, &tid); // If created thread // is not created if (t2 == NULL) { cout << \"Thread Creation Error: \" << WSAGetLastError() << endl; } // Received Objects // from client WaitForSingleObject(t1, INFINITE); WaitForSingleObject(t2, INFINITE); // Close the socket closesocket(client); // If socket closing // failed. if (closesocket(server) == SOCKET_ERROR) { cout << \"Close socket failed with error: \" << WSAGetLastError() << endl; return -1; } WSACleanup(); }}",
"e": 7411,
"s": 2283,
"text": null
},
{
"code": null,
"e": 7448,
"s": 7411,
"text": "g++ ServerApplication.cpp -lws2_32 \n"
},
{
"code": null,
"e": 7686,
"s": 7448,
"text": "Creating the Client ProgramIn the Client Program, we will be using two threads one for Sending data to the server and another for Receiving data from the server. The process of communication stops when both Server and Client type “exit“."
},
{
"code": null,
"e": 7693,
"s": 7686,
"text": "Client"
},
{
"code": "// C++ program to create client #include <iostream>#include <string.h>#include <winsock2.h>using namespace std; // Function that receive data from serverDWORD WINAPI clientReceive(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created server socket SOCKET server = *(SOCKET*)lpParam; // Client executes continuously while (true) { // If received buffer gives // error then return -1 if (recv(server, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << \"recv function failed with error: \" << WSAGetLastError() << endl; return -1; } // If Server exits if (strcmp(buffer, \"exit\") == 0) { cout << \"Server disconnected.\" << endl; return 1; } // Print the message // given by server that // was stored in buffer cout << \"Server: \" << buffer << endl; // Clear buffer message memset(buffer, 0, sizeof(buffer)); } return 1;} // Function that sends data to serverDWORD WINAPI clientSend(LPVOID lpParam){ // Created buffer[] to // receive message char buffer[1024] = { 0 }; // Created server socket SOCKET server = *(SOCKET*)lpParam; // Client executes continuously while (true) { // Input message client // wants to send to server gets(buffer); // If sending failed // return -1 if (send(server, buffer, sizeof(buffer), 0) == SOCKET_ERROR) { cout << \"send failed with error: \" << WSAGetLastError() << endl; return -1; } // If client exit if (strcmp(buffer, \"exit\") == 0) { cout << \"Thank you for using the application\" << endl; break; } } return 1;} // Driver Codeint main(){ // Input data WSADATA WSAData; // Created socket server SOCKET server; SOCKADDR_IN addr; WSAStartup(MAKEWORD(2, 0), &WSAData); // If invalid socket created, // return -1 if ((server = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { cout << \"Socket creation failed with error: \" << WSAGetLastError() << endl; return -1; } addr.sin_addr.s_addr = inet_addr(\"127.0.0.1\"); addr.sin_family = AF_INET; addr.sin_port = htons(5555); // If connection failed if (connect(server, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) { cout << \"Server connection failed with error: \" << WSAGetLastError() << endl; return -1; } // If connection established cout << \"Connected to server!\" << endl; cout << \"Now you can use our live chat application.\" << \" Enter \\\"exit\\\" to disconnect\" << endl; DWORD tid; // Create Thread t1 HANDLE t1 = CreateThread(NULL, 0, clientReceive, &server, 0, &tid); // If created thread // is not created if (t1 == NULL) cout << \"Thread creation error: \" << GetLastError(); // Create Thread t2 HANDLE t2 = CreateThread(NULL, 0, clientSend, &server, 0, &tid); // If created thread // is not created if (t2 == NULL) cout << \"Thread creation error: \" << GetLastError(); // Received Objects // from client WaitForSingleObject(t1, INFINITE); WaitForSingleObject(t2, INFINITE); // Socket closed closesocket(server); WSACleanup();}",
"e": 11574,
"s": 7693,
"text": null
},
{
"code": null,
"e": 11628,
"s": 11574,
"text": "Run the ClientApplication.cpp file using the command:"
},
{
"code": null,
"e": 11665,
"s": 11628,
"text": "g++ ClientApplication.cpp -lws2_32 \n"
},
{
"code": null,
"e": 11831,
"s": 11665,
"text": "Output After communication between Server and ClientThe left side command prompt is the ServerApplication and the right side command prompt is the ClientApplication."
},
{
"code": null,
"e": 11840,
"s": 11831,
"text": "gabaa406"
},
{
"code": null,
"e": 11860,
"s": 11840,
"text": "Processes & Threads"
},
{
"code": null,
"e": 11879,
"s": 11860,
"text": "Socket-programming"
},
{
"code": null,
"e": 11892,
"s": 11879,
"text": "C++ Programs"
},
{
"code": null,
"e": 11910,
"s": 11892,
"text": "Computer Networks"
},
{
"code": null,
"e": 11928,
"s": 11910,
"text": "Computer Networks"
},
{
"code": null,
"e": 12026,
"s": 11928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12067,
"s": 12026,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 12088,
"s": 12067,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 12100,
"s": 12088,
"text": "cout in C++"
},
{
"code": null,
"e": 12159,
"s": 12100,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 12180,
"s": 12159,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 12200,
"s": 12180,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 12213,
"s": 12200,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 12243,
"s": 12213,
"text": "Basics of Computer Networking"
},
{
"code": null,
"e": 12275,
"s": 12243,
"text": "Differences between TCP and UDP"
}
] |
Generate n-bit Gray Codes | Set 2
|
24 May, 2021
Given a number n, generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit.
Examples:
Input: n=2Output: 00 01 11 10Explanation:Every adjacent element of gray code differs only by one bit. So the n bit grey codes are: 00 01 11 10
Input: n=3Output: 000 001 011 010 110 111 101 100Explanation:Every adjacent element of gray code differs only by one bit. So the n bit gray codes are: 000 001 011 010 110 111 101 100
Another approach of Generate n-bit Gray Codes has already been discussed.
Approach: The idea is to get gray code of binary number using XOR and Right shift operation.
The first bit(MSB) of the gray code is same as the first bit(MSB) of binary numbers.The second bit(from left side) of the gray code equals to XOR of first bit(MSB) and second bit(2nd MSB) of the binary number.The third bit(from left side) of the gray code equals to XOR of the second bit(2nd MSB) and a third bit(3rd MSB) and so on..
The first bit(MSB) of the gray code is same as the first bit(MSB) of binary numbers.
The second bit(from left side) of the gray code equals to XOR of first bit(MSB) and second bit(2nd MSB) of the binary number.
The third bit(from left side) of the gray code equals to XOR of the second bit(2nd MSB) and a third bit(3rd MSB) and so on..
In this way, the gray code can be calculated for the corresponding binary number. So, it can be observed that the ith element can be formed by bitwise XOR of i and floor(i/2) which is equal to the bitwise XOR of i and (i >> 1) i.e., i right-shifted by 1. By performing this the MSB of the binary number is kept intact and all the other bits are performed bitwise XOR with its adjacent higher bit.
C++
Java
Python3
C#
Javascript
// C++ program to generate n-bit// gray codes#include <bits/stdc++.h>using namespace std; // Function to convert decimal to binaryvoid decimalToBinaryNumber(int x, int n){ int* binaryNumber = new int(x); int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are filled with 0 for (int j = 0; j < n - i; j++) cout << '0'; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j];} // Function to generate gray codevoid generateGrayarr(int n){ int N = 1 << n; for (int i = 0; i < N; i++) { // generate gray code of corresponding // binary number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); cout << endl; }} // Drivers codeint main(){ int n = 3; generateGrayarr(n); return 0;}
// Java program to generate// n-bit gray codesimport java.io.*; class GFG { // Function to convert // decimal to binary static void decimalToBinaryNumber(int x, int n) { int[] binaryNumber = new int[x]; int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are // filled with 0 for (int j = 0; j < n - i; j++) System.out.print('0'); for (int j = i - 1; j >= 0; j--) System.out.print(binaryNumber[j]); } // Function to generate // gray code static void generateGrayarr(int n) { int N = 1 << n; for (int i = 0; i < N; i++) { // generate gray code of // corresponding binary // number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); System.out.println(); } } // Driver code public static void main(String[] args) { int n = 3; generateGrayarr(n); }} // This code is contributed// by anuj_67.
# Python program to generate# n-bit gray codes # Function to convert# decimal to binarydef decimalToBinaryNumber(x, n): binaryNumber = [0]*x; i = 0; while (x > 0): binaryNumber[i] = x % 2; x = x // 2; i += 1; # leftmost digits are # filled with 0 for j in range(0, n - i): print('0', end =""); for j in range(i - 1, -1, -1): print(binaryNumber[j], end =""); # Function to generate# gray codedef generateGrayarr(n): N = 1 << n; for i in range(N): # generate gray code of # corresponding binary # number of integer i. x = i ^ (i >> 1); # printing gray code decimalToBinaryNumber(x, n); print(); # Driver codeif __name__ == '__main__': n = 3; generateGrayarr(n); # This code is contributed by 29AjayKumar
// C# program to generate// n-bit gray codesusing System; class GFG { // Function to convert // decimal to binary static void decimalToBinaryNumber(int x, int n) { int[] binaryNumber = new int[x]; int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are // filled with 0 for (int j = 0; j < n - i; j++) Console.Write('0'); for (int j = i - 1; j >= 0; j--) Console.Write(binaryNumber[j]); } // Function to generate // gray code static void generateGrayarr(int n) { int N = 1 << n; for (int i = 0; i < N; i++) { // Generate gray code of // corresponding binary // number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); Console.WriteLine(); } } // Driver code public static void Main() { int n = 3; generateGrayarr(n); }} // This code is contributed// by anuj_67.
<script> // JavaScript program to generate n-bit// gray codes // Function to convert decimal to binaryfunction decimalToBinaryNumber(x, n){ var binaryNumber = Array(x); var i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = parseInt(x / 2); i++; } // leftmost digits are filled with 0 for (var j = 0; j < n - i; j++) document.write('0'); for (var j = i - 1; j >= 0; j--) document.write( binaryNumber[j]);} // Function to generate gray codefunction generateGrayarr(n){ var N = 1 << n; for (var i = 0; i < N; i++) { // generate gray code of corresponding // binary number of integer i. var x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); document.write("<br>"); }} // Drivers codevar n = 3;generateGrayarr(n); </script>
000
001
011
010
110
111
101
100
Complexity Analysis:
Time Complexity: O(2n). Only one traversal from 0 to (2n) is needed.
Auxiliary Space: O(log x). A space of (log x) is required for binary representation of (x)
vt_m
29AjayKumar
andrew1234
AbhishekBarman
deepanshuagg19
itsok
gray-code
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Binary representation of a given number
Divide two integers without using multiplication, division and mod operator
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
C++ bitset and its application
Find the element that appears once
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 159,
"s": 54,
"text": "Given a number n, generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit."
},
{
"code": null,
"e": 170,
"s": 159,
"text": "Examples: "
},
{
"code": null,
"e": 313,
"s": 170,
"text": "Input: n=2Output: 00 01 11 10Explanation:Every adjacent element of gray code differs only by one bit. So the n bit grey codes are: 00 01 11 10"
},
{
"code": null,
"e": 496,
"s": 313,
"text": "Input: n=3Output: 000 001 011 010 110 111 101 100Explanation:Every adjacent element of gray code differs only by one bit. So the n bit gray codes are: 000 001 011 010 110 111 101 100"
},
{
"code": null,
"e": 570,
"s": 496,
"text": "Another approach of Generate n-bit Gray Codes has already been discussed."
},
{
"code": null,
"e": 664,
"s": 570,
"text": "Approach: The idea is to get gray code of binary number using XOR and Right shift operation. "
},
{
"code": null,
"e": 998,
"s": 664,
"text": "The first bit(MSB) of the gray code is same as the first bit(MSB) of binary numbers.The second bit(from left side) of the gray code equals to XOR of first bit(MSB) and second bit(2nd MSB) of the binary number.The third bit(from left side) of the gray code equals to XOR of the second bit(2nd MSB) and a third bit(3rd MSB) and so on.."
},
{
"code": null,
"e": 1083,
"s": 998,
"text": "The first bit(MSB) of the gray code is same as the first bit(MSB) of binary numbers."
},
{
"code": null,
"e": 1209,
"s": 1083,
"text": "The second bit(from left side) of the gray code equals to XOR of first bit(MSB) and second bit(2nd MSB) of the binary number."
},
{
"code": null,
"e": 1334,
"s": 1209,
"text": "The third bit(from left side) of the gray code equals to XOR of the second bit(2nd MSB) and a third bit(3rd MSB) and so on.."
},
{
"code": null,
"e": 1731,
"s": 1334,
"text": "In this way, the gray code can be calculated for the corresponding binary number. So, it can be observed that the ith element can be formed by bitwise XOR of i and floor(i/2) which is equal to the bitwise XOR of i and (i >> 1) i.e., i right-shifted by 1. By performing this the MSB of the binary number is kept intact and all the other bits are performed bitwise XOR with its adjacent higher bit."
},
{
"code": null,
"e": 1735,
"s": 1731,
"text": "C++"
},
{
"code": null,
"e": 1740,
"s": 1735,
"text": "Java"
},
{
"code": null,
"e": 1748,
"s": 1740,
"text": "Python3"
},
{
"code": null,
"e": 1751,
"s": 1748,
"text": "C#"
},
{
"code": null,
"e": 1762,
"s": 1751,
"text": "Javascript"
},
{
"code": "// C++ program to generate n-bit// gray codes#include <bits/stdc++.h>using namespace std; // Function to convert decimal to binaryvoid decimalToBinaryNumber(int x, int n){ int* binaryNumber = new int(x); int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are filled with 0 for (int j = 0; j < n - i; j++) cout << '0'; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j];} // Function to generate gray codevoid generateGrayarr(int n){ int N = 1 << n; for (int i = 0; i < N; i++) { // generate gray code of corresponding // binary number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); cout << endl; }} // Drivers codeint main(){ int n = 3; generateGrayarr(n); return 0;}",
"e": 2635,
"s": 1762,
"text": null
},
{
"code": "// Java program to generate// n-bit gray codesimport java.io.*; class GFG { // Function to convert // decimal to binary static void decimalToBinaryNumber(int x, int n) { int[] binaryNumber = new int[x]; int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are // filled with 0 for (int j = 0; j < n - i; j++) System.out.print('0'); for (int j = i - 1; j >= 0; j--) System.out.print(binaryNumber[j]); } // Function to generate // gray code static void generateGrayarr(int n) { int N = 1 << n; for (int i = 0; i < N; i++) { // generate gray code of // corresponding binary // number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); System.out.println(); } } // Driver code public static void main(String[] args) { int n = 3; generateGrayarr(n); }} // This code is contributed// by anuj_67.",
"e": 3819,
"s": 2635,
"text": null
},
{
"code": "# Python program to generate# n-bit gray codes # Function to convert# decimal to binarydef decimalToBinaryNumber(x, n): binaryNumber = [0]*x; i = 0; while (x > 0): binaryNumber[i] = x % 2; x = x // 2; i += 1; # leftmost digits are # filled with 0 for j in range(0, n - i): print('0', end =\"\"); for j in range(i - 1, -1, -1): print(binaryNumber[j], end =\"\"); # Function to generate# gray codedef generateGrayarr(n): N = 1 << n; for i in range(N): # generate gray code of # corresponding binary # number of integer i. x = i ^ (i >> 1); # printing gray code decimalToBinaryNumber(x, n); print(); # Driver codeif __name__ == '__main__': n = 3; generateGrayarr(n); # This code is contributed by 29AjayKumar",
"e": 4651,
"s": 3819,
"text": null
},
{
"code": "// C# program to generate// n-bit gray codesusing System; class GFG { // Function to convert // decimal to binary static void decimalToBinaryNumber(int x, int n) { int[] binaryNumber = new int[x]; int i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = x / 2; i++; } // leftmost digits are // filled with 0 for (int j = 0; j < n - i; j++) Console.Write('0'); for (int j = i - 1; j >= 0; j--) Console.Write(binaryNumber[j]); } // Function to generate // gray code static void generateGrayarr(int n) { int N = 1 << n; for (int i = 0; i < N; i++) { // Generate gray code of // corresponding binary // number of integer i. int x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); Console.WriteLine(); } } // Driver code public static void Main() { int n = 3; generateGrayarr(n); }} // This code is contributed// by anuj_67.",
"e": 5809,
"s": 4651,
"text": null
},
{
"code": "<script> // JavaScript program to generate n-bit// gray codes // Function to convert decimal to binaryfunction decimalToBinaryNumber(x, n){ var binaryNumber = Array(x); var i = 0; while (x > 0) { binaryNumber[i] = x % 2; x = parseInt(x / 2); i++; } // leftmost digits are filled with 0 for (var j = 0; j < n - i; j++) document.write('0'); for (var j = i - 1; j >= 0; j--) document.write( binaryNumber[j]);} // Function to generate gray codefunction generateGrayarr(n){ var N = 1 << n; for (var i = 0; i < N; i++) { // generate gray code of corresponding // binary number of integer i. var x = i ^ (i >> 1); // printing gray code decimalToBinaryNumber(x, n); document.write(\"<br>\"); }} // Drivers codevar n = 3;generateGrayarr(n); </script>",
"e": 6661,
"s": 5809,
"text": null
},
{
"code": null,
"e": 6693,
"s": 6661,
"text": "000\n001\n011\n010\n110\n111\n101\n100"
},
{
"code": null,
"e": 6715,
"s": 6693,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 6784,
"s": 6715,
"text": "Time Complexity: O(2n). Only one traversal from 0 to (2n) is needed."
},
{
"code": null,
"e": 6876,
"s": 6784,
"text": "Auxiliary Space: O(log x). A space of (log x) is required for binary representation of (x) "
},
{
"code": null,
"e": 6881,
"s": 6876,
"text": "vt_m"
},
{
"code": null,
"e": 6893,
"s": 6881,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6904,
"s": 6893,
"text": "andrew1234"
},
{
"code": null,
"e": 6919,
"s": 6904,
"text": "AbhishekBarman"
},
{
"code": null,
"e": 6934,
"s": 6919,
"text": "deepanshuagg19"
},
{
"code": null,
"e": 6940,
"s": 6934,
"text": "itsok"
},
{
"code": null,
"e": 6950,
"s": 6940,
"text": "gray-code"
},
{
"code": null,
"e": 6960,
"s": 6950,
"text": "Bit Magic"
},
{
"code": null,
"e": 6970,
"s": 6960,
"text": "Bit Magic"
},
{
"code": null,
"e": 7068,
"s": 6970,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7098,
"s": 7068,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 7136,
"s": 7098,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 7176,
"s": 7136,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 7252,
"s": 7176,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 7295,
"s": 7252,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 7311,
"s": 7295,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 7342,
"s": 7311,
"text": "C++ bitset and its application"
},
{
"code": null,
"e": 7377,
"s": 7342,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 7428,
"s": 7377,
"text": "Add two numbers without using arithmetic operators"
}
] |
How to Create Scroll Indicator using ReactJS ?
|
12 Mar, 2021
The following approach covers how to create Scroll Indicator using React JS. It is a simple effect you can add to any ReactJS website.
Prerequisite:
Basic knowledge of npm & create-react-app command.
Basic knowledge of styled-components.
Basic knowledge of useState() hooks.
Basic Setup: You will start a new project using create-react-app command.
npx create-react-app react-scroll-indicator
Now go to your react-scroll-indicator folder by typing the given command in the terminal.
cd react-scroll-indicator
Required module: Install the dependencies required in this project by typing the given command in the terminal:
npm install --save styled-components
Now create the components folder in src then go to the components folder and create two files ScrollIndicator.js and Styles.js.
Project Structure: The file structure in the project will look like this:
Example: In this example, we will design a scroll indicator component, for that we will need to manipulate the App.js file and other created components file.
We create a state with the first element scroll as an initial state having a value of 0 and the second element as function setScroll() for updating the state. Then a function is created by the name onScroll in which we declare the following variables :
Scrolled: It tells us how many pixels the user has scrolled down so far.
MaxHeight: It tells us the difference between the height of the whole webpage and the height of the maximum portion of the browser that the user can see.
ScrollPercent: It tells us the percentage value of the width of the Scroll Indicator element. It is equal to 100 multiplied with the ratio of no of pixels the user has scrolled down so far (from top) to the total no of pixels of the remaining portion of the browser which the user can only see on scrolling down.
When we start scrolling down the page, the function onScroll gets triggered as an event through window.addEventListener property. It sets the state value to ScrollPercent due to which the indicator bar starts filling up with green color when we scroll down the page. When we scroll up the page the quantity of color reduces.
ScrollIndicator.js
import React, { useState, Fragment } from "react";import { Container, ProgressBar, ScrollContent, Heading } from "./Styles";const ScrollIndicator = () => { const [scroll, setScroll] = useState(0); const onScroll = () => { const Scrolled = document.documentElement.scrollTop; const MaxHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; const ScrollPercent = (Scrolled / MaxHeight) * 100; setScroll(ScrollPercent); }; window.addEventListener("scroll", onScroll); return ( <Fragment> <Container> <ProgressBar style={{ width: `${scroll}%` }}> </ProgressBar> </Container> <ScrollContent> <Heading>GeeksForGeeks Scroll Indicator</Heading> </ScrollContent> </Fragment> );}; export default ScrollIndicator;
Styles.js
import styled from 'styled-components'; export const Container = styled.div` background-color: black; height: 30px; position: sticky; top: 0; left: 0; z-index: 1; width: 100%;` export const ProgressBar = styled.div` height: 30px; background-color: green;`export const ScrollContent = styled.div` overflowY: scroll; height:2000px;`; export const Heading = styled.h1` text-align: center; font-size: 3rem;`
App.js
import ScrollIndicator from './components/ScrollIndicator'; function App() { return ( <ScrollIndicator /> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
Styled-components
Technical Scripter 2020
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 187,
"s": 52,
"text": "The following approach covers how to create Scroll Indicator using React JS. It is a simple effect you can add to any ReactJS website."
},
{
"code": null,
"e": 201,
"s": 187,
"text": "Prerequisite:"
},
{
"code": null,
"e": 252,
"s": 201,
"text": "Basic knowledge of npm & create-react-app command."
},
{
"code": null,
"e": 290,
"s": 252,
"text": "Basic knowledge of styled-components."
},
{
"code": null,
"e": 327,
"s": 290,
"text": "Basic knowledge of useState() hooks."
},
{
"code": null,
"e": 401,
"s": 327,
"text": "Basic Setup: You will start a new project using create-react-app command."
},
{
"code": null,
"e": 445,
"s": 401,
"text": "npx create-react-app react-scroll-indicator"
},
{
"code": null,
"e": 535,
"s": 445,
"text": "Now go to your react-scroll-indicator folder by typing the given command in the terminal."
},
{
"code": null,
"e": 561,
"s": 535,
"text": "cd react-scroll-indicator"
},
{
"code": null,
"e": 673,
"s": 561,
"text": "Required module: Install the dependencies required in this project by typing the given command in the terminal:"
},
{
"code": null,
"e": 710,
"s": 673,
"text": "npm install --save styled-components"
},
{
"code": null,
"e": 838,
"s": 710,
"text": "Now create the components folder in src then go to the components folder and create two files ScrollIndicator.js and Styles.js."
},
{
"code": null,
"e": 913,
"s": 838,
"text": "Project Structure: The file structure in the project will look like this: "
},
{
"code": null,
"e": 1071,
"s": 913,
"text": "Example: In this example, we will design a scroll indicator component, for that we will need to manipulate the App.js file and other created components file."
},
{
"code": null,
"e": 1324,
"s": 1071,
"text": "We create a state with the first element scroll as an initial state having a value of 0 and the second element as function setScroll() for updating the state. Then a function is created by the name onScroll in which we declare the following variables :"
},
{
"code": null,
"e": 1397,
"s": 1324,
"text": "Scrolled: It tells us how many pixels the user has scrolled down so far."
},
{
"code": null,
"e": 1551,
"s": 1397,
"text": "MaxHeight: It tells us the difference between the height of the whole webpage and the height of the maximum portion of the browser that the user can see."
},
{
"code": null,
"e": 1864,
"s": 1551,
"text": "ScrollPercent: It tells us the percentage value of the width of the Scroll Indicator element. It is equal to 100 multiplied with the ratio of no of pixels the user has scrolled down so far (from top) to the total no of pixels of the remaining portion of the browser which the user can only see on scrolling down."
},
{
"code": null,
"e": 2189,
"s": 1864,
"text": "When we start scrolling down the page, the function onScroll gets triggered as an event through window.addEventListener property. It sets the state value to ScrollPercent due to which the indicator bar starts filling up with green color when we scroll down the page. When we scroll up the page the quantity of color reduces."
},
{
"code": null,
"e": 2208,
"s": 2189,
"text": "ScrollIndicator.js"
},
{
"code": "import React, { useState, Fragment } from \"react\";import { Container, ProgressBar, ScrollContent, Heading } from \"./Styles\";const ScrollIndicator = () => { const [scroll, setScroll] = useState(0); const onScroll = () => { const Scrolled = document.documentElement.scrollTop; const MaxHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; const ScrollPercent = (Scrolled / MaxHeight) * 100; setScroll(ScrollPercent); }; window.addEventListener(\"scroll\", onScroll); return ( <Fragment> <Container> <ProgressBar style={{ width: `${scroll}%` }}> </ProgressBar> </Container> <ScrollContent> <Heading>GeeksForGeeks Scroll Indicator</Heading> </ScrollContent> </Fragment> );}; export default ScrollIndicator;",
"e": 3026,
"s": 2208,
"text": null
},
{
"code": null,
"e": 3036,
"s": 3026,
"text": "Styles.js"
},
{
"code": "import styled from 'styled-components'; export const Container = styled.div` background-color: black; height: 30px; position: sticky; top: 0; left: 0; z-index: 1; width: 100%;` export const ProgressBar = styled.div` height: 30px; background-color: green;`export const ScrollContent = styled.div` overflowY: scroll; height:2000px;`; export const Heading = styled.h1` text-align: center; font-size: 3rem;`",
"e": 3470,
"s": 3036,
"text": null
},
{
"code": null,
"e": 3477,
"s": 3470,
"text": "App.js"
},
{
"code": "import ScrollIndicator from './components/ScrollIndicator'; function App() { return ( <ScrollIndicator /> );} export default App;",
"e": 3618,
"s": 3477,
"text": null
},
{
"code": null,
"e": 3731,
"s": 3618,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3741,
"s": 3731,
"text": "npm start"
},
{
"code": null,
"e": 3840,
"s": 3741,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3856,
"s": 3840,
"text": "React-Questions"
},
{
"code": null,
"e": 3874,
"s": 3856,
"text": "Styled-components"
},
{
"code": null,
"e": 3898,
"s": 3874,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3906,
"s": 3898,
"text": "ReactJS"
},
{
"code": null,
"e": 3925,
"s": 3906,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3942,
"s": 3925,
"text": "Web Technologies"
}
] |
Python – Pytorch randn() method
|
02 Jun, 2022
PyTorch torch.randn() returns a tensor defined by the variable argument size (sequence of integers defining the shape of the output tensor), containing random numbers from standard normal distribution.
Syntax: torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
Parameters:
size: sequence of integers defining the size of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
out: (optional) output tensor.
dtype: (optional) data type of output tensor.
layout: (optional) the desired layout of returned Tensor. Default value is torch.strided.
device: (optional) the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad: (optional) if set to true, autograd records operation on the output tensor.
Return: tensor filled with values from standard normal distribution.
Let’s see this concept with the help of few examples:
Example 1:
Python
# import pytorch libraryimport torch # create a tensor of size 2 x 4input_var = torch.randn(2,4) print (input_var)
Output:
tensor([[-1.4313, -0.3831, -0.8356, -1.5555],
[-1.2749, -1.1872, -0.4983, 0.1029]])
This returns a tensor of size 2 × 4, filled with values from standard normal distribution, that is mean is 0 and variance is 1.
Example 2:
Python3
# import Pytorch libraryimport torch # create a 3-dimensional tensor# of 4 x 5input_var = torch.randn(3, 4, 5, requires_grad = True)print(input_var)
Output:
tensor([[[-0.1097, 1.6845, 0.9375, -1.0515, 0.5767], [ 0.1924, -0.7736, -0.7102, -0.2654, 0.3118], [-0.5314, 0.1924, -1.1629, 0.2360, 0.8605], [-0.8036, -0.0695, -0.6062, 1.4872, 0.5455]], [[ 1.5699, -0.7190, 1.0925, 0.8463, -0.1906], [-0.0763, -0.6819, -1.0517, -0.5087, -1.4451], [-2.0127, 1.0061, 0.5723, -0.1336, -0.3821], [ 0.0868, 1.1556, 0.3842, -0.4168, -1.4604]], [[ 0.1368, -1.6240, -0.1875, -0.5964, 0.9352], [ 0.4429, 0.2843, -1.2151, 1.3456, -0.4539], [-0.4528, 1.9981, -1.2007, 0.0071, -0.0239], [-0.1003, 0.7938, -0.0977, -1.4097, 0.1679]]], requires_grad=True)
This returns a tensor of size 3 × 4 × 5, filled with random numbers, also recording the gradient values, when performed. Example 3:
Python3
# import Pytorch libraryimport torch # error occurinput_var = torch.randn(3.0, 4.0, 5.0, requires_grad = True)print(input_var)
Output:
TypeError Traceback (most recent call last) in 1 # import Pytorch library 2 import torch —-> 3 input = torch.randn(3.0, 4.0, 5.0,requires_grad=True) 4 print( input )TypeError: randn() received an invalid combination of arguments – got (float, float, float, requires_grad=bool), but expected one of: * (tuple of ints size, *, tuple of names , torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, torch.Generator generator, tuple of names , torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, torch.Generator generator, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
size parameter cannot take floating-point numbers so the error will generate.
sagar0719kumar
sagartomar9927
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "PyTorch torch.randn() returns a tensor defined by the variable argument size (sequence of integers defining the shape of the output tensor), containing random numbers from standard normal distribution."
},
{
"code": null,
"e": 335,
"s": 230,
"text": "Syntax: torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)"
},
{
"code": null,
"e": 347,
"s": 335,
"text": "Parameters:"
},
{
"code": null,
"e": 490,
"s": 347,
"text": "size: sequence of integers defining the size of the output tensor. Can be a variable number of arguments or a collection like a list or tuple."
},
{
"code": null,
"e": 521,
"s": 490,
"text": "out: (optional) output tensor."
},
{
"code": null,
"e": 567,
"s": 521,
"text": "dtype: (optional) data type of output tensor."
},
{
"code": null,
"e": 657,
"s": 567,
"text": "layout: (optional) the desired layout of returned Tensor. Default value is torch.strided."
},
{
"code": null,
"e": 919,
"s": 657,
"text": "device: (optional) the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types."
},
{
"code": null,
"e": 1010,
"s": 919,
"text": "requires_grad: (optional) if set to true, autograd records operation on the output tensor."
},
{
"code": null,
"e": 1079,
"s": 1010,
"text": "Return: tensor filled with values from standard normal distribution."
},
{
"code": null,
"e": 1133,
"s": 1079,
"text": "Let’s see this concept with the help of few examples:"
},
{
"code": null,
"e": 1144,
"s": 1133,
"text": "Example 1:"
},
{
"code": null,
"e": 1151,
"s": 1144,
"text": "Python"
},
{
"code": "# import pytorch libraryimport torch # create a tensor of size 2 x 4input_var = torch.randn(2,4) print (input_var)",
"e": 1266,
"s": 1151,
"text": null
},
{
"code": null,
"e": 1278,
"s": 1269,
"text": " Output:"
},
{
"code": null,
"e": 1373,
"s": 1280,
"text": "tensor([[-1.4313, -0.3831, -0.8356, -1.5555],\n [-1.2749, -1.1872, -0.4983, 0.1029]])"
},
{
"code": null,
"e": 1503,
"s": 1375,
"text": "This returns a tensor of size 2 × 4, filled with values from standard normal distribution, that is mean is 0 and variance is 1."
},
{
"code": null,
"e": 1516,
"s": 1505,
"text": "Example 2:"
},
{
"code": null,
"e": 1526,
"s": 1518,
"text": "Python3"
},
{
"code": "# import Pytorch libraryimport torch # create a 3-dimensional tensor# of 4 x 5input_var = torch.randn(3, 4, 5, requires_grad = True)print(input_var)",
"e": 1696,
"s": 1526,
"text": null
},
{
"code": null,
"e": 1708,
"s": 1699,
"text": " Output:"
},
{
"code": null,
"e": 2397,
"s": 1710,
"text": "tensor([[[-0.1097, 1.6845, 0.9375, -1.0515, 0.5767], [ 0.1924, -0.7736, -0.7102, -0.2654, 0.3118], [-0.5314, 0.1924, -1.1629, 0.2360, 0.8605], [-0.8036, -0.0695, -0.6062, 1.4872, 0.5455]], [[ 1.5699, -0.7190, 1.0925, 0.8463, -0.1906], [-0.0763, -0.6819, -1.0517, -0.5087, -1.4451], [-2.0127, 1.0061, 0.5723, -0.1336, -0.3821], [ 0.0868, 1.1556, 0.3842, -0.4168, -1.4604]], [[ 0.1368, -1.6240, -0.1875, -0.5964, 0.9352], [ 0.4429, 0.2843, -1.2151, 1.3456, -0.4539], [-0.4528, 1.9981, -1.2007, 0.0071, -0.0239], [-0.1003, 0.7938, -0.0977, -1.4097, 0.1679]]], requires_grad=True) "
},
{
"code": null,
"e": 2532,
"s": 2399,
"text": "This returns a tensor of size 3 × 4 × 5, filled with random numbers, also recording the gradient values, when performed. Example 3: "
},
{
"code": null,
"e": 2542,
"s": 2534,
"text": "Python3"
},
{
"code": "# import Pytorch libraryimport torch # error occurinput_var = torch.randn(3.0, 4.0, 5.0, requires_grad = True)print(input_var)",
"e": 2690,
"s": 2542,
"text": null
},
{
"code": null,
"e": 2701,
"s": 2693,
"text": "Output:"
},
{
"code": null,
"e": 3659,
"s": 2703,
"text": "TypeError Traceback (most recent call last) in 1 # import Pytorch library 2 import torch —-> 3 input = torch.randn(3.0, 4.0, 5.0,requires_grad=True) 4 print( input )TypeError: randn() received an invalid combination of arguments – got (float, float, float, requires_grad=bool), but expected one of: * (tuple of ints size, *, tuple of names , torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, torch.Generator generator, tuple of names , torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, torch.Generator generator, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) "
},
{
"code": null,
"e": 3739,
"s": 3661,
"text": "size parameter cannot take floating-point numbers so the error will generate."
},
{
"code": null,
"e": 3756,
"s": 3741,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 3771,
"s": 3756,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3786,
"s": 3771,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 3793,
"s": 3786,
"text": "Python"
}
] |
How to declare and access pointer variable in Golang?
|
10 May, 2020
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).
Before we start there are two important operators which we will use in pointers i.e.
* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address.
& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer.
Declaring a pointer:
var pointer_name *Data_Type
Example: Below is a pointer of type string which can store only the memory addresses of string variables.
var s *string
Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example:
// normal variable declaration
var a = 45
// Initialization of pointer s with
// memory address of variable a
var s *int = &a
Example: In the following example, using pointer we will access the value of the variable whose address is stored in pointer.
// Golang program to show how to declare// and access pointer variable in Golangpackage main import ( "fmt") func main() { // variable declaration var dummyVar string = "Geeks For Geeks" // pointer declaration var pointerVariable *string // assigning variable address to pointer variable pointerVariable = &dummyVar // Prints the address of the dummyVar variable fmt.Printf("\nAddress of the variable: %v", &dummyVar) // Prints the address stored in pointer fmt.Printf("\nAddress stored in the pointer variable: %v", pointerVariable) // Value of variable fmt.Printf("\nValue of the Actual Variable: %s", dummyVar) // Value of variable whose address is stored in pointer fmt.Printf("\nValue of the Pointer variable: %s", *pointerVariable)}
Output:
Address of the variable: 0xc00010a040
Address stored in the pointer variable: 0xc00010a040
Value of the Actual Variable: Geeks For Geeks
Value of the Pointer variable: Geeks For Geeks
Explanation: Here (&) symbol is used to get the address of the variable storing the value as “Geeks for Geeks”. The address owned by this variable is the same which is stored in the pointer. Therefore, the output of &dummyVar and pointerVariable is the same. To access the value stored at the address, which is stored in pointer we user (*) symbol.
Golang-Pointers
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 393,
"s": 28,
"text": "Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.)."
},
{
"code": null,
"e": 478,
"s": 393,
"text": "Before we start there are two important operators which we will use in pointers i.e."
},
{
"code": null,
"e": 608,
"s": 478,
"text": "* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address."
},
{
"code": null,
"e": 741,
"s": 608,
"text": "& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer."
},
{
"code": null,
"e": 762,
"s": 741,
"text": "Declaring a pointer:"
},
{
"code": null,
"e": 790,
"s": 762,
"text": "var pointer_name *Data_Type"
},
{
"code": null,
"e": 896,
"s": 790,
"text": "Example: Below is a pointer of type string which can store only the memory addresses of string variables."
},
{
"code": null,
"e": 910,
"s": 896,
"text": "var s *string"
},
{
"code": null,
"e": 1083,
"s": 910,
"text": "Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example:"
},
{
"code": null,
"e": 1212,
"s": 1083,
"text": "// normal variable declaration\nvar a = 45\n\n// Initialization of pointer s with \n// memory address of variable a\nvar s *int = &a\n"
},
{
"code": null,
"e": 1338,
"s": 1212,
"text": "Example: In the following example, using pointer we will access the value of the variable whose address is stored in pointer."
},
{
"code": "// Golang program to show how to declare// and access pointer variable in Golangpackage main import ( \"fmt\") func main() { // variable declaration var dummyVar string = \"Geeks For Geeks\" // pointer declaration var pointerVariable *string // assigning variable address to pointer variable pointerVariable = &dummyVar // Prints the address of the dummyVar variable fmt.Printf(\"\\nAddress of the variable: %v\", &dummyVar) // Prints the address stored in pointer fmt.Printf(\"\\nAddress stored in the pointer variable: %v\", pointerVariable) // Value of variable fmt.Printf(\"\\nValue of the Actual Variable: %s\", dummyVar) // Value of variable whose address is stored in pointer fmt.Printf(\"\\nValue of the Pointer variable: %s\", *pointerVariable)}",
"e": 2138,
"s": 1338,
"text": null
},
{
"code": null,
"e": 2146,
"s": 2138,
"text": "Output:"
},
{
"code": null,
"e": 2331,
"s": 2146,
"text": "Address of the variable: 0xc00010a040\nAddress stored in the pointer variable: 0xc00010a040\nValue of the Actual Variable: Geeks For Geeks\nValue of the Pointer variable: Geeks For Geeks\n"
},
{
"code": null,
"e": 2680,
"s": 2331,
"text": "Explanation: Here (&) symbol is used to get the address of the variable storing the value as “Geeks for Geeks”. The address owned by this variable is the same which is stored in the pointer. Therefore, the output of &dummyVar and pointerVariable is the same. To access the value stored at the address, which is stored in pointer we user (*) symbol."
},
{
"code": null,
"e": 2696,
"s": 2680,
"text": "Golang-Pointers"
},
{
"code": null,
"e": 2703,
"s": 2696,
"text": "Picked"
},
{
"code": null,
"e": 2715,
"s": 2703,
"text": "Go Language"
},
{
"code": null,
"e": 2731,
"s": 2715,
"text": "Write From Home"
}
] |
Generic Class Hierarchies in Java
|
17 May, 2021
Generic means parameterized types introduced in java5. These help in creating classes, interfaces, methods, etc. A class or method which works on parameterized type known as “generic class ” or “generic method”. Generics is a combination of language properties of the definition and use of Generic types and methods. Collections were used before Generics which holds any type of objects i.e. non-generic. Using Generics, it has become possible to create a single class, interface, or method that automatically works with all types of data(Integer, String, Float, etc). It has expanded the ability to reuse the code safely and easily. Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation).
Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit. It inherits all members defined by super-class and adds its own, unique elements. These uses extends as a keyword to do so.
Sometimes generic class acts like super-class or subclass. In Generic Hierarchy, All sub-classes move up any of the parameter types that are essential by super-class of generic in the hierarchy. This is the same as constructor parameters being moved up in a hierarchy.
Example 1: Generic super-class
Java
// Java Program to illustrate generic class hierarchies // Importing all input output classesimport java.io.*; // Helper class 1// Class 1 - Parent classclass Generic1<T> { // Member variable of parent class T obj; // Constructor of parent class Generic1(T o1) { obj = o1; } // Member function of parent class // that returns an object T getobj1() { return obj; }} // Helper class 2// Class 2 - Child classclass Generic2<T, V> extends Generic1<T> { // Member variable of child class V obj2; Generic2(T o1, V o2) { // Calling super class using super keyword super(o1); obj2 = o2; } // Member function of child class // that returns an object V getobj2() { return obj2; }} // Class 3 - Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating Generic2 (sub class) object // Custom inputs as parameters Generic2<String, Integer> x = new Generic2<String, Integer>("value : ", 100); // Calling method and printing System.out.println(x.getobj1()); System.out.println(x.getobj2()); }}
value :
100
Note: A subclass can freely add its own type parameters, if necessary.
Example 2: Non-generic sub-class of generic sub-class
Java
import java.io.*;// non-generic super-classclass NonGen { int n; NonGen(int i) { n = i; } int getval() { return n; }}// generic class sub-classclass Gen<T> extends NonGen { T obj; Gen(T o1, int i) { super(i); obj = o1; } T getobj() { return obj; }} class GFG { public static void main(String[] args) { Gen<String> w = new Gen<String>("Hello", 2021); System.out.println(w.getobj() + " " + w.getval()); }}
Hello 2021
gabaa406
Java-Generics
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 804,
"s": 28,
"text": "Generic means parameterized types introduced in java5. These help in creating classes, interfaces, methods, etc. A class or method which works on parameterized type known as “generic class ” or “generic method”. Generics is a combination of language properties of the definition and use of Generic types and methods. Collections were used before Generics which holds any type of objects i.e. non-generic. Using Generics, it has become possible to create a single class, interface, or method that automatically works with all types of data(Integer, String, Float, etc). It has expanded the ability to reuse the code safely and easily. Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). "
},
{
"code": null,
"e": 1069,
"s": 804,
"text": "Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit. It inherits all members defined by super-class and adds its own, unique elements. These uses extends as a keyword to do so."
},
{
"code": null,
"e": 1339,
"s": 1069,
"text": "Sometimes generic class acts like super-class or subclass. In Generic Hierarchy, All sub-classes move up any of the parameter types that are essential by super-class of generic in the hierarchy. This is the same as constructor parameters being moved up in a hierarchy."
},
{
"code": null,
"e": 1370,
"s": 1339,
"text": "Example 1: Generic super-class"
},
{
"code": null,
"e": 1375,
"s": 1370,
"text": "Java"
},
{
"code": "// Java Program to illustrate generic class hierarchies // Importing all input output classesimport java.io.*; // Helper class 1// Class 1 - Parent classclass Generic1<T> { // Member variable of parent class T obj; // Constructor of parent class Generic1(T o1) { obj = o1; } // Member function of parent class // that returns an object T getobj1() { return obj; }} // Helper class 2// Class 2 - Child classclass Generic2<T, V> extends Generic1<T> { // Member variable of child class V obj2; Generic2(T o1, V o2) { // Calling super class using super keyword super(o1); obj2 = o2; } // Member function of child class // that returns an object V getobj2() { return obj2; }} // Class 3 - Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating Generic2 (sub class) object // Custom inputs as parameters Generic2<String, Integer> x = new Generic2<String, Integer>(\"value : \", 100); // Calling method and printing System.out.println(x.getobj1()); System.out.println(x.getobj2()); }}",
"e": 2574,
"s": 1375,
"text": null
},
{
"code": null,
"e": 2587,
"s": 2574,
"text": "value : \n100"
},
{
"code": null,
"e": 2659,
"s": 2587,
"text": "Note: A subclass can freely add its own type parameters, if necessary. "
},
{
"code": null,
"e": 2713,
"s": 2659,
"text": "Example 2: Non-generic sub-class of generic sub-class"
},
{
"code": null,
"e": 2718,
"s": 2713,
"text": "Java"
},
{
"code": "import java.io.*;// non-generic super-classclass NonGen { int n; NonGen(int i) { n = i; } int getval() { return n; }}// generic class sub-classclass Gen<T> extends NonGen { T obj; Gen(T o1, int i) { super(i); obj = o1; } T getobj() { return obj; }} class GFG { public static void main(String[] args) { Gen<String> w = new Gen<String>(\"Hello\", 2021); System.out.println(w.getobj() + \" \" + w.getval()); }}",
"e": 3185,
"s": 2718,
"text": null
},
{
"code": null,
"e": 3196,
"s": 3185,
"text": "Hello 2021"
},
{
"code": null,
"e": 3207,
"s": 3198,
"text": "gabaa406"
},
{
"code": null,
"e": 3221,
"s": 3207,
"text": "Java-Generics"
},
{
"code": null,
"e": 3245,
"s": 3221,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3250,
"s": 3245,
"text": "Java"
},
{
"code": null,
"e": 3269,
"s": 3250,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3274,
"s": 3269,
"text": "Java"
}
] |
SVG rotate Attribute
|
31 Mar, 2022
The rotate attribute shows the rotation of an animated element as it travels along a specified path in an <animateMotion> element.
Syntax:
rotate = auto | auto-reverse | number
Attribute Values: The rotate attribute accepts the values mentioned above and described below:
auto: This value allows the animated element’s rotation to change dynamically as it travels along the path. In this, the element aligns itself to its right-hand side in the current direction of motion.
auto-reverse: This value allows the animated element’s rotation to change dynamically as it travels along the path. In this, the element aligns itself to its left-hand side in the current direction of motion.
number: This value shows a constant rotation, that does not change with the animation.
The Below examples illustrate the use of the rotate attribute.
Example 1:
HTML
<!DOCTYPE html><html> <body> <div style="color: green; margin-left: 40px;"> <h1>GeeksforGeeks</h1> <h4 style="color: black;"> When rotate = 0 & auto </h4> <svg width="400" height="120" viewBox="0 0 380 120" xmlns="http://www.w3.org/2000/svg"> <path d="M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110" stroke="green" stroke-width="2" fill="none" id="geek"/> <path fill="red" d="M-5,-5 L10,0 -5,5 0,0 Z"> <animateMotion dur="6s" repeatCount="indefinite" rotate="0"> <mpath href="#geek"/> </animateMotion> </path> <g transform="translate(100, 0)"> <use href="#geek"/> <path fill="green" d="M-5,-5 L10,0 -5,5 0,0 Z"> <animateMotion dur="6s" repeatCount="indefinite" rotate="auto"> <mpath href="#geek"/> </animateMotion> </path> </g> </svg> </div> </body> </html>
Output:
HTML
<!DOCTYPE html><html> <body> <div style="color: green; margin-left: 40px;"> <h1>GeeksforGeeks</h1> <h4 style="color: black;"> When rotate = auto-reverse & 200 </h4> <svg width="600" height="120" viewBox="50 0 480 120" xmlns="http://www.w3.org/2000/svg"> <g> <path d="M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110" stroke="green" stroke-width="2" fill="none" id="geek"/> <path fill="blue" d="M-5,-5 L10,0 -5,5 0,0 Z"> <animateMotion dur="6s" repeatCount="indefinite" rotate="auto-reverse"> <mpath href="#geek"/> </animateMotion> </path> </g> <g transform="translate(100, 0)"> <path d="M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110" stroke="green" stroke-width="2" fill="none" id="geek"/> <path fill="black" d="M-5,-5 L10,0 -5,5 0,0 Z"> <animateMotion dur="6s" repeatCount="indefinite" rotate="200"> <mpath href="#geek"/> </animateMotion> </path> </g> </svg> </div> </body> </html>
Output:
sagar0719kumar
HTML-SVG
SVG-Attribute
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": "\n31 Mar, 2022"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "The rotate attribute shows the rotation of an animated element as it travels along a specified path in an <animateMotion> element."
},
{
"code": null,
"e": 167,
"s": 159,
"text": "Syntax:"
},
{
"code": null,
"e": 205,
"s": 167,
"text": "rotate = auto | auto-reverse | number"
},
{
"code": null,
"e": 300,
"s": 205,
"text": "Attribute Values: The rotate attribute accepts the values mentioned above and described below:"
},
{
"code": null,
"e": 502,
"s": 300,
"text": "auto: This value allows the animated element’s rotation to change dynamically as it travels along the path. In this, the element aligns itself to its right-hand side in the current direction of motion."
},
{
"code": null,
"e": 711,
"s": 502,
"text": "auto-reverse: This value allows the animated element’s rotation to change dynamically as it travels along the path. In this, the element aligns itself to its left-hand side in the current direction of motion."
},
{
"code": null,
"e": 798,
"s": 711,
"text": "number: This value shows a constant rotation, that does not change with the animation."
},
{
"code": null,
"e": 861,
"s": 798,
"text": "The Below examples illustrate the use of the rotate attribute."
},
{
"code": null,
"e": 872,
"s": 861,
"text": "Example 1:"
},
{
"code": null,
"e": 877,
"s": 872,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"color: green; margin-left: 40px;\"> <h1>GeeksforGeeks</h1> <h4 style=\"color: black;\"> When rotate = 0 & auto </h4> <svg width=\"400\" height=\"120\" viewBox=\"0 0 380 120\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110\" stroke=\"green\" stroke-width=\"2\" fill=\"none\" id=\"geek\"/> <path fill=\"red\" d=\"M-5,-5 L10,0 -5,5 0,0 Z\"> <animateMotion dur=\"6s\" repeatCount=\"indefinite\" rotate=\"0\"> <mpath href=\"#geek\"/> </animateMotion> </path> <g transform=\"translate(100, 0)\"> <use href=\"#geek\"/> <path fill=\"green\" d=\"M-5,-5 L10,0 -5,5 0,0 Z\"> <animateMotion dur=\"6s\" repeatCount=\"indefinite\" rotate=\"auto\"> <mpath href=\"#geek\"/> </animateMotion> </path> </g> </svg> </div> </body> </html>",
"e": 2307,
"s": 877,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2307,
"text": "Output:"
},
{
"code": null,
"e": 2320,
"s": 2315,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"color: green; margin-left: 40px;\"> <h1>GeeksforGeeks</h1> <h4 style=\"color: black;\"> When rotate = auto-reverse & 200 </h4> <svg width=\"600\" height=\"120\" viewBox=\"50 0 480 120\" xmlns=\"http://www.w3.org/2000/svg\"> <g> <path d=\"M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110\" stroke=\"green\" stroke-width=\"2\" fill=\"none\" id=\"geek\"/> <path fill=\"blue\" d=\"M-5,-5 L10,0 -5,5 0,0 Z\"> <animateMotion dur=\"6s\" repeatCount=\"indefinite\" rotate=\"auto-reverse\"> <mpath href=\"#geek\"/> </animateMotion> </path> </g> <g transform=\"translate(100, 0)\"> <path d=\"M10,110 A120,120 -45 0, 1 110 10 A120,120 -45 0, 1 10,110\" stroke=\"green\" stroke-width=\"2\" fill=\"none\" id=\"geek\"/> <path fill=\"black\" d=\"M-5,-5 L10,0 -5,5 0,0 Z\"> <animateMotion dur=\"6s\" repeatCount=\"indefinite\" rotate=\"200\"> <mpath href=\"#geek\"/> </animateMotion> </path> </g> </svg> </div> </body> </html>",
"e": 4098,
"s": 2320,
"text": null
},
{
"code": null,
"e": 4106,
"s": 4098,
"text": "Output:"
},
{
"code": null,
"e": 4121,
"s": 4106,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4130,
"s": 4121,
"text": "HTML-SVG"
},
{
"code": null,
"e": 4144,
"s": 4130,
"text": "SVG-Attribute"
},
{
"code": null,
"e": 4149,
"s": 4144,
"text": "HTML"
},
{
"code": null,
"e": 4166,
"s": 4149,
"text": "Web Technologies"
},
{
"code": null,
"e": 4171,
"s": 4166,
"text": "HTML"
}
] |
Remove rows with NA in one column of R DataFrame
|
01 Apr, 2021
Columns of DataFrame in R Programming Language can have empty values represented by NA. In this article, we are going to see how to remove rows with NA in one column. We will see various approaches to remove rows with NA values.
Data in use:
Approach
Create a data frame
Select the column on the basis of which rows are to be removed
Traverse the column searching for na values
Select rows
Delete such rows using a specific method
Method 1: Using drop_na()
drop_na() Drops rows having values equal to NA. To use this approach we need to use “tidyr” library, which can be installed.
install.packages(“tidyverse”)
Syntax:
drop_na(name_of_the_column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul", "Cassie","Jim","Dwight") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) library(tidyr)student %>% drop_na(maths)
Output:
Method 2: Using is.na()
is.na() function first looks for na values in a column and then discards such rows.
Syntax:
is.na(name of the column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul", "Cassie","Jim","Dwight") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) student[!is.na(student$science),]
Output:
Method 3:Using complete.cases()
This function functions similar to the above two methods
Syntax:
complete.cases(name of the column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul", "Cassie","Jim","Dwight") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) student[complete.cases(student$history),]
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
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?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "Columns of DataFrame in R Programming Language can have empty values represented by NA. In this article, we are going to see how to remove rows with NA in one column. We will see various approaches to remove rows with NA values."
},
{
"code": null,
"e": 270,
"s": 257,
"text": "Data in use:"
},
{
"code": null,
"e": 279,
"s": 270,
"text": "Approach"
},
{
"code": null,
"e": 299,
"s": 279,
"text": "Create a data frame"
},
{
"code": null,
"e": 362,
"s": 299,
"text": "Select the column on the basis of which rows are to be removed"
},
{
"code": null,
"e": 406,
"s": 362,
"text": "Traverse the column searching for na values"
},
{
"code": null,
"e": 418,
"s": 406,
"text": "Select rows"
},
{
"code": null,
"e": 459,
"s": 418,
"text": "Delete such rows using a specific method"
},
{
"code": null,
"e": 485,
"s": 459,
"text": "Method 1: Using drop_na()"
},
{
"code": null,
"e": 610,
"s": 485,
"text": "drop_na() Drops rows having values equal to NA. To use this approach we need to use “tidyr” library, which can be installed."
},
{
"code": null,
"e": 640,
"s": 610,
"text": "install.packages(“tidyverse”)"
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Syntax:"
},
{
"code": null,
"e": 676,
"s": 648,
"text": "drop_na(name_of_the_column)"
},
{
"code": null,
"e": 685,
"s": 676,
"text": "Example:"
},
{
"code": null,
"e": 687,
"s": 685,
"text": "R"
},
{
"code": "# Creating dataframestudent=data.frame(name=c(\"Ram\",\"Geeta\",\"John\",\"Paul\", \"Cassie\",\"Jim\",\"Dwight\") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) library(tidyr)student %>% drop_na(maths)",
"e": 1006,
"s": 687,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Output:"
},
{
"code": null,
"e": 1038,
"s": 1014,
"text": "Method 2: Using is.na()"
},
{
"code": null,
"e": 1122,
"s": 1038,
"text": "is.na() function first looks for na values in a column and then discards such rows."
},
{
"code": null,
"e": 1130,
"s": 1122,
"text": "Syntax:"
},
{
"code": null,
"e": 1156,
"s": 1130,
"text": "is.na(name of the column)"
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "Example:"
},
{
"code": null,
"e": 1167,
"s": 1165,
"text": "R"
},
{
"code": "# Creating dataframestudent=data.frame(name=c(\"Ram\",\"Geeta\",\"John\",\"Paul\", \"Cassie\",\"Jim\",\"Dwight\") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) student[!is.na(student$science),]",
"e": 1479,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1479,
"text": "Output:"
},
{
"code": null,
"e": 1520,
"s": 1487,
"text": "Method 3:Using complete.cases() "
},
{
"code": null,
"e": 1577,
"s": 1520,
"text": "This function functions similar to the above two methods"
},
{
"code": null,
"e": 1585,
"s": 1577,
"text": "Syntax:"
},
{
"code": null,
"e": 1620,
"s": 1585,
"text": "complete.cases(name of the column)"
},
{
"code": null,
"e": 1629,
"s": 1620,
"text": "Example:"
},
{
"code": null,
"e": 1631,
"s": 1629,
"text": "R"
},
{
"code": "# Creating dataframestudent=data.frame(name=c(\"Ram\",\"Geeta\",\"John\",\"Paul\", \"Cassie\",\"Jim\",\"Dwight\") ,maths=c(7,8,NA,9,10,8,9) ,science=c(5,7,6,8,NA,7,8) ,history=c(7,NA,7,7,NA,7,7)) print(student) student[complete.cases(student$history),]",
"e": 1951,
"s": 1631,
"text": null
},
{
"code": null,
"e": 1959,
"s": 1951,
"text": "Output:"
},
{
"code": null,
"e": 1966,
"s": 1959,
"text": "Picked"
},
{
"code": null,
"e": 1987,
"s": 1966,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 1999,
"s": 1987,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2010,
"s": 1999,
"text": "R Language"
},
{
"code": null,
"e": 2021,
"s": 2010,
"text": "R Programs"
},
{
"code": null,
"e": 2119,
"s": 2021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2171,
"s": 2119,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2229,
"s": 2171,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2264,
"s": 2229,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2302,
"s": 2264,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2351,
"s": 2302,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2409,
"s": 2351,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2458,
"s": 2409,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2501,
"s": 2458,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2539,
"s": 2501,
"text": "Merge DataFrames by Column Names in R"
}
] |
Find nth Fibonacci number using Golden ratio
|
24 Jun, 2022
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: Examples:
Input : n = 9
Output : 34
Input : n = 7
Output : 13
Approach: Golden ratio may give us incorrect answer. We can get correct result if we round up the result at each point.
nth fibonacci number = round(n-1th Fibonacci number X golden ratio)
fn = round(fn-1 * )
Till 4th term, the ratio is not much close to golden ratio (as 3/2 = 1.5, 2/1 = 2, ...). So, we will consider from 5th term to get next fibonacci number. To find out the 9th fibonacci number f9 (n = 9) :
f6 = round(f5 * ) = 8f7 = round(f6 * ) = 13f8 = round(f7 * ) = 21f9 = round(f8 * ) = 34
Note: This method can calculate first 34 fibonacci numbers correctly. After that there may be difference from the correct value. Below is the implementation of above approach:
CPP
C
Java
Python3
C#
PHP
Javascript
// CPP program to find n-th Fibonacci number#include <bits/stdc++.h>using namespace std; // Approximate value of golden ratiodouble PHI = 1.6180339; // Fibonacci numbers upto n = 5int f[6] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth// Fibonacci numberint fib(int n){ // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5, fn = 5; while (t < n) { fn = round(fn * PHI); t++; } return fn;} // driver codeint main(){ int n = 9; cout << n << "th Fibonacci Number = " << fib(n) << endl; return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)
// C program to find n-th Fibonacci number#include <math.h>#include <stdio.h> // Approximate value of golden ratiodouble PHI = 1.6180339; // Fibonacci numbers upto n = 5int f[6] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth// Fibonacci numberint fib(int n){ // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5, fn = 5; while (t < n) { fn = round(fn * PHI); t++; } return fn;} // driver codeint main(){ int n = 9; printf("%d th Fibonacci Number = %d\n", n, fib(n)); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)
// Java program to find n-th Fibonacci number class GFG{ // Approximate value of golden ratio static double PHI = 1.6180339; // Fibonacci numbers upto n = 5 static int f[] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth // Fibonacci number static int fib (int n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5; int fn = 5; while (t < n) { fn = (int)Math.round(fn * PHI); t++; } return fn; } // Driver code public static void main (String[] args) { int n = 9; System.out.println(n + "th Fibonacci Number = " +fib(n)); }} // This code is contributed by Anant Agarwal.
# Python3 code to find n-th Fibonacci number # Approximate value of golden ratioPHI = 1.6180339 # Fibonacci numbers upto n = 5f = [ 0, 1, 1, 2, 3, 5 ] # Function to find nth# Fibonacci numberdef fib ( n ): # Fibonacci numbers for n < 6 if n < 6: return f[n] # Else start counting from # 5th term t = 5 fn = 5 while t < n: fn = round(fn * PHI) t+=1 return fn # driver coden = 9print(n, "th Fibonacci Number =", fib(n)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to find n-th Fibonacci// numberusing System; class GFG { // Approximate value of golden ratio static double PHI = 1.6180339; // Fibonacci numbers upto n = 5 static int []f = { 0, 1, 1, 2, 3, 5 }; // Function to find nth // Fibonacci number static int fib (int n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5; int fn = 5; while (t < n) { fn = (int)Math.Round(fn * PHI); t++; } return fn; } // Driver code public static void Main () { int n = 9; Console.WriteLine(n + "th Fibonacci" + " Number = " + fib(n)); }} // This code is contributed by vt_m.
<?php// PHP program to find n-th// Fibonacci number Approximate// value of golden ratio$PHI = 1.6180339; // Fibonacci numbers// upto n = 5 // Function to find nth// Fibonacci numberfunction fib ($n){ global $PHI; $f = array(0, 1, 1, 2, 3, 5); // Fibonacci numbers // for n < 6 if ($n < 6) return $f[$n]; // Else start counting // from 5th term $t = 5; $fn = 5; while ($t < $n) { $fn = round($fn * $PHI); $t++; } return $fn;} // Driver Code $n = 9; echo $n, "th Fibonacci Number = ", fib($n), "\n"; // This code is contributed by aj_36?>
<script> // JavaScript program to find n-th Fibonacci number // Approximate value of golden ratio let PHI = 1.6180339; // Fibonacci numbers upto n = 5 let f = [ 0, 1, 1, 2, 3, 5 ]; // Function to find nth // Fibonacci number function fib (n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term let t = 5, fn = 5; while (t < n) { fn = Math.round(fn * PHI); t++; } return fn; } // driver code let n = 9; document.write(n + "th Fibonacci Number = " + fib(n) + "<br>"); // This code is contributed by Mayank Tyagi </script>
Output:
9th Fibonacci Number = 34
We can optimize above solution work in O(Log n) by using efficient method to compute power.The above method may not always produce correct results as floating point computations are involved. This is the reason, this method is not used practically even if it can be optimized to work in O(Log n). Please refer below MIT video for more details.https://www.youtube.com/watch?v=-EQTVuAhSFY
jit_t
mayanktyagi1709
ayondip2001
krisania804
Fibonacci
Mathematical
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 351,
"s": 52,
"text": "Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: Examples: "
},
{
"code": null,
"e": 404,
"s": 351,
"text": "Input : n = 9\nOutput : 34\n\nInput : n = 7\nOutput : 13"
},
{
"code": null,
"e": 528,
"s": 406,
"text": "Approach: Golden ratio may give us incorrect answer. We can get correct result if we round up the result at each point. "
},
{
"code": null,
"e": 634,
"s": 528,
"text": "nth fibonacci number = round(n-1th Fibonacci number X golden ratio)\n fn = round(fn-1 * )"
},
{
"code": null,
"e": 840,
"s": 634,
"text": "Till 4th term, the ratio is not much close to golden ratio (as 3/2 = 1.5, 2/1 = 2, ...). So, we will consider from 5th term to get next fibonacci number. To find out the 9th fibonacci number f9 (n = 9) : "
},
{
"code": null,
"e": 933,
"s": 840,
"text": " f6 = round(f5 * ) = 8f7 = round(f6 * ) = 13f8 = round(f7 * ) = 21f9 = round(f8 * ) = 34"
},
{
"code": null,
"e": 1111,
"s": 933,
"text": "Note: This method can calculate first 34 fibonacci numbers correctly. After that there may be difference from the correct value. Below is the implementation of above approach: "
},
{
"code": null,
"e": 1115,
"s": 1111,
"text": "CPP"
},
{
"code": null,
"e": 1117,
"s": 1115,
"text": "C"
},
{
"code": null,
"e": 1122,
"s": 1117,
"text": "Java"
},
{
"code": null,
"e": 1130,
"s": 1122,
"text": "Python3"
},
{
"code": null,
"e": 1133,
"s": 1130,
"text": "C#"
},
{
"code": null,
"e": 1137,
"s": 1133,
"text": "PHP"
},
{
"code": null,
"e": 1148,
"s": 1137,
"text": "Javascript"
},
{
"code": "// CPP program to find n-th Fibonacci number#include <bits/stdc++.h>using namespace std; // Approximate value of golden ratiodouble PHI = 1.6180339; // Fibonacci numbers upto n = 5int f[6] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth// Fibonacci numberint fib(int n){ // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5, fn = 5; while (t < n) { fn = round(fn * PHI); t++; } return fn;} // driver codeint main(){ int n = 9; cout << n << \"th Fibonacci Number = \" << fib(n) << endl; return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)",
"e": 1816,
"s": 1148,
"text": null
},
{
"code": "// C program to find n-th Fibonacci number#include <math.h>#include <stdio.h> // Approximate value of golden ratiodouble PHI = 1.6180339; // Fibonacci numbers upto n = 5int f[6] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth// Fibonacci numberint fib(int n){ // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5, fn = 5; while (t < n) { fn = round(fn * PHI); t++; } return fn;} // driver codeint main(){ int n = 9; printf(\"%d th Fibonacci Number = %d\\n\", n, fib(n)); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)",
"e": 2470,
"s": 1816,
"text": null
},
{
"code": "// Java program to find n-th Fibonacci number class GFG{ // Approximate value of golden ratio static double PHI = 1.6180339; // Fibonacci numbers upto n = 5 static int f[] = { 0, 1, 1, 2, 3, 5 }; // Function to find nth // Fibonacci number static int fib (int n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5; int fn = 5; while (t < n) { fn = (int)Math.round(fn * PHI); t++; } return fn; } // Driver code public static void main (String[] args) { int n = 9; System.out.println(n + \"th Fibonacci Number = \" +fib(n)); }} // This code is contributed by Anant Agarwal.",
"e": 3322,
"s": 2470,
"text": null
},
{
"code": "# Python3 code to find n-th Fibonacci number # Approximate value of golden ratioPHI = 1.6180339 # Fibonacci numbers upto n = 5f = [ 0, 1, 1, 2, 3, 5 ] # Function to find nth# Fibonacci numberdef fib ( n ): # Fibonacci numbers for n < 6 if n < 6: return f[n] # Else start counting from # 5th term t = 5 fn = 5 while t < n: fn = round(fn * PHI) t+=1 return fn # driver coden = 9print(n, \"th Fibonacci Number =\", fib(n)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3846,
"s": 3322,
"text": null
},
{
"code": "// C# program to find n-th Fibonacci// numberusing System; class GFG { // Approximate value of golden ratio static double PHI = 1.6180339; // Fibonacci numbers upto n = 5 static int []f = { 0, 1, 1, 2, 3, 5 }; // Function to find nth // Fibonacci number static int fib (int n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term int t = 5; int fn = 5; while (t < n) { fn = (int)Math.Round(fn * PHI); t++; } return fn; } // Driver code public static void Main () { int n = 9; Console.WriteLine(n + \"th Fibonacci\" + \" Number = \" + fib(n)); }} // This code is contributed by vt_m.",
"e": 4690,
"s": 3846,
"text": null
},
{
"code": "<?php// PHP program to find n-th// Fibonacci number Approximate// value of golden ratio$PHI = 1.6180339; // Fibonacci numbers// upto n = 5 // Function to find nth// Fibonacci numberfunction fib ($n){ global $PHI; $f = array(0, 1, 1, 2, 3, 5); // Fibonacci numbers // for n < 6 if ($n < 6) return $f[$n]; // Else start counting // from 5th term $t = 5; $fn = 5; while ($t < $n) { $fn = round($fn * $PHI); $t++; } return $fn;} // Driver Code $n = 9; echo $n, \"th Fibonacci Number = \", fib($n), \"\\n\"; // This code is contributed by aj_36?>",
"e": 5312,
"s": 4690,
"text": null
},
{
"code": "<script> // JavaScript program to find n-th Fibonacci number // Approximate value of golden ratio let PHI = 1.6180339; // Fibonacci numbers upto n = 5 let f = [ 0, 1, 1, 2, 3, 5 ]; // Function to find nth // Fibonacci number function fib (n) { // Fibonacci numbers for n < 6 if (n < 6) return f[n]; // Else start counting from // 5th term let t = 5, fn = 5; while (t < n) { fn = Math.round(fn * PHI); t++; } return fn; } // driver code let n = 9; document.write(n + \"th Fibonacci Number = \" + fib(n) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>",
"e": 6029,
"s": 5312,
"text": null
},
{
"code": null,
"e": 6039,
"s": 6029,
"text": "Output: "
},
{
"code": null,
"e": 6065,
"s": 6039,
"text": "9th Fibonacci Number = 34"
},
{
"code": null,
"e": 6453,
"s": 6065,
"text": "We can optimize above solution work in O(Log n) by using efficient method to compute power.The above method may not always produce correct results as floating point computations are involved. This is the reason, this method is not used practically even if it can be optimized to work in O(Log n). Please refer below MIT video for more details.https://www.youtube.com/watch?v=-EQTVuAhSFY "
},
{
"code": null,
"e": 6459,
"s": 6453,
"text": "jit_t"
},
{
"code": null,
"e": 6475,
"s": 6459,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 6487,
"s": 6475,
"text": "ayondip2001"
},
{
"code": null,
"e": 6499,
"s": 6487,
"text": "krisania804"
},
{
"code": null,
"e": 6509,
"s": 6499,
"text": "Fibonacci"
},
{
"code": null,
"e": 6522,
"s": 6509,
"text": "Mathematical"
},
{
"code": null,
"e": 6535,
"s": 6522,
"text": "Mathematical"
},
{
"code": null,
"e": 6545,
"s": 6535,
"text": "Fibonacci"
}
] |
Pair with given product | Set 1 (Find if any pair exists)
|
08 Jul, 2022
Given an array of distinct elements and a number x, find if there is a pair with a product equal to x.
Examples :
Input : arr[] = {10, 20, 9, 40};
int x = 400;
Output : Yes
Input : arr[] = {10, 20, 9, 40};
int x = 190;
Output : No
Input : arr[] = {-10, 20, 9, -40};
int x = 400;
Output : Yes
Input : arr[] = {-10, 20, 9, 40};
int x = -400;
Output : Yes
Input : arr[] = {0, 20, 9, 40};
int x = 0;
Output : Yes
The naive approach ( O(n2) ) is to run two loops to consider all possible pairs. For every pair, check if the product is equal to x or not.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find if there is a pair// with given product.#include<bits/stdc++.h>using namespace std; // Returns true if there is a pair in arr[0..n-1]// with product equal to x.bool isProduct(int arr[], int n, int x){ // Consider all possible pairs and check for // every pair. for (int i=0; i<n-1; i++) for (int j=i+1; i<n; i++) if (arr[i] * arr[j] == x) return true; return false;} // Driver codeint main(){ int arr[] = {10, 20, 9, 40}; int x = 400; int n = sizeof(arr)/sizeof(arr[0]); isProduct(arr, n, x)? cout << "Yesn" : cout << "Non"; x = 190; isProduct(arr, n, x)? cout << "Yesn" : cout << "Non"; return 0;}
// Java program to find if there is a pair// with given product.class GFG{ // Returns true if there is a pair in // arr[0..n-1] with product equal to x. boolean isProduct(int arr[], int n, int x) { for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (arr[i]*arr[j] == x) return true; return false; } // Driver code public static void main(String[] args) { GFG g = new GFG(); int arr[] = {10, 20, 9, 40}; int x = 400; int n = arr.length; if (g.isProduct(arr, n, x)) System.out.println("Yes"); else System.out.println("No"); x = 190; if (g.isProduct(arr, n, x)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Kamal Rawal
# Python3 program to find if there# is a pair with given product. # Returns true if there is a# pair in arr[0..n-1] with# product equal to xdef isProduct(arr, n, x): for i in arr: for j in arr: if i * j == x: return True return False # Driver code arr = [10, 20, 9, 40]x = 400n = len(arr)if(isProduct(arr,n, x) == True): print ("Yes") else: print("No") x = 900if(isProduct(arr, n, x)): print("Yes") else: print("No") # This code is contributed# by prerna saini
// C# program to find// if there is a pair// with given product.using System; class GFG{ // Returns true if there// is a pair in arr[0..n-1]// with product equal to x.static bool isProduct(int []arr, int n, int x){ for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] == x) return true; return false;} // Driver Codestatic void Main(){ int []arr = {10, 20, 9, 40}; int x = 400; int n = arr.Length; if (isProduct(arr, n, x)) Console.WriteLine("Yes"); else Console.WriteLine("No"); x = 190; if (isProduct(arr, n, x)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed// by Sam007
<?php// A simple php program to// find if there is a pair// with given product. // Returns true if there// is a pair in arr[0..n-1]// with product equal to x.function isProduct($arr, $n, $x){ // Consider all possible // pairs and check for // every pair. for ($i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $i < $n; $i++) if ($arr[$i] * $arr[$j] == $x) return true; return false;} // Driver code$arr = array(10, 20, 9, 40);$x = 400;$n = count($arr);if(isProduct($arr, $n, $x))echo "Yes\n";elseecho "No\n"; $x = 190;if(isProduct($arr, $n, $x))echo "Yes\n";elseecho "No\n"; // This code is contributed// by Sam007?>
<script> // A simple Javascript program to find if there is a pair// with given product. // Returns true if there is a pair in arr[0..n-1]// with product equal to x.function isProduct(arr, n, x){ // Consider all possible pairs and check for // every pair. for (var i=0; i<n-1; i++) for (var j=i+1; i<n; i++) if (arr[i] * arr[j] == x) return true; return false;} // Driver codevar arr = [10, 20, 9, 40];var x = 400;var n = arr.length;isProduct(arr, n, x)? document.write("Yes<br>") : document.write("No<br>");x = 190;isProduct(arr, n, x)? document.write("Yes") : document.write("No"); </script>
Output :
Yes
No
Time Complexity: O(n2)
Auxiliary Space: O(1)
Better Solution (O(n Log n) : We sort the given array. After sorting, we traverse the array and for every element arr[i], we do binary search for x/arr[i] in the subarray on the right of arr[i], i.e., in subarray arr[i+1..n-1]
Efficient Solution ( O(n) ): We can improve time complexity to O(n) using hashing. Below are the steps.
Create an empty hash tableTraverse array elements and do the following for every element arr[i]. If arr[i] is 0 and x is also 0, return true, else ignore arr[i].If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.Insert arr[i] into the hash table.Return false
Create an empty hash table
Traverse array elements and do the following for every element arr[i]. If arr[i] is 0 and x is also 0, return true, else ignore arr[i].If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.Insert arr[i] into the hash table.
If arr[i] is 0 and x is also 0, return true, else ignore arr[i].
If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.
Insert arr[i] into the hash table.
Return false
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ program to find if there is a pair// with given product.#include<bits/stdc++.h>using namespace std; // Returns true if there is a pair in arr[0..n-1]// with product equal to x.bool isProduct(int arr[], int n, int x){ if (n < 2) return false; // Create an empty set and insert first // element into it unordered_set<int> s; // Traverse remaining elements for (int i=0; i<n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined behaviour in C++ if (arr[i] == 0) { if (x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if (x%arr[i] == 0) { if (s.find(x/arr[i]) != s.end()) return true; // Insert arr[i] s.insert(arr[i]); } } return false;} // Driver codeint main(){ int arr[] = {10, 20, 9, 40}; int x = 400; int n = sizeof(arr)/sizeof(arr[0]); isProduct(arr, n, x)? cout << "Yes\n" : cout << "Non"; x = 190; isProduct(arr, n, x)? cout << "Yes\n" : cout << "Non"; return 0;}
// Java program if there exists a pair for given productimport java.util.HashSet; class GFG{ // Returns true if there is a pair in arr[0..n-1] // with product equal to x. static boolean isProduct(int arr[], int n, int x) { // Create an empty set and insert first // element into it HashSet<Integer> hset = new HashSet<>(); if(n < 2) return false; // Traverse remaining elements for(int i = 0; i < n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined if(arr[i] == 0) { if(x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if(x % arr[i] == 0) { if(hset.contains(x / arr[i])) return true; // Insert arr[i] hset.add(arr[i]); } } return false; } // driver code public static void main(String[] args) { int arr[] = {10, 20, 9, 40}; int x = 400; int n = arr.length; if(isProduct(arr, arr.length, x)) System.out.println("Yes"); else System.out.println("No"); x = 190; if(isProduct(arr, arr.length, x)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Kamal Rawal
# Python3 program to find if there# is a pair with the given product. # Returns true if there is a pair in# arr[0..n-1] with product equal to x.def isProduct(arr, n, x): if n < 2: return False # Create an empty set and insert # first element into it s = set() # Traverse remaining elements for i in range(0, n): # 0 case must be handles explicitly as # x % 0 is undefined behaviour in C++ if arr[i] == 0: if x == 0: return True else: continue # x/arr[i] exists in hash, then # we found a pair if x % arr[i] == 0: if x // arr[i] in s: return True # Insert arr[i] s.add(arr[i]) return False # Driver codeif __name__ == "__main__": arr = [10, 20, 9, 40] x = 400 n = len(arr) if isProduct(arr, n, x): print("Yes") else: print("No") x = 190 if isProduct(arr, n, x): print("Yes") else: print("No") # This code is contributed by# Rituraj Jain
// C# program if there exists a// pair for given productusing System;using System.Collections.Generic; class GFG{// Returns true if there is a pair// in arr[0..n-1] with product equal to x.public static bool isProduct(int[] arr, int n, int x){ // Create an empty set and insert // first element into it HashSet<int> hset = new HashSet<int>(); if (n < 2) { return false; } // Traverse remaining elements for (int i = 0; i < n; i++) { // 0 case must be handles explicitly // as x % 0 is undefined if (arr[i] == 0) { if (x == 0) { return true; } else { continue; } } // x/arr[i] exists in hash, then // we found a pair if (x % arr[i] == 0) { if (hset.Contains(x / arr[i])) { return true; } // Insert arr[i] hset.Add(arr[i]); } } return false;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {10, 20, 9, 40}; int x = 400; int n = arr.Length; if (isProduct(arr, arr.Length, x)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } x = 190; if (isProduct(arr, arr.Length, x)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); }}} // This code is contributed by Shrikant13
<script> // Javascript program if there exists a pair for given product // Returns true if there is a pair in arr[0..n-1] // with product equal to x. function isProduct(arr, n, x) { // Create an empty set and insert first // element into it let hset = new Set(); if(n < 2) return false; // Traverse remaining elements for(let i = 0; i < n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined if(arr[i] == 0) { if(x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if(x % arr[i] == 0) { if(hset.has(x / arr[i])) return true; // Insert arr[i] hset.add(arr[i]); } } return false; } // Driver program let arr = [10, 20, 9, 40]; let x = 400; let n = arr.length; if(isProduct(arr, arr.length, x)) document.write("Yes" + "<br/>"); else document.write("No" + "<br/>"); x = 190; if(isProduct(arr, arr.length, x)) document.write("Yes" + "<br/>"); else document.write("No" + "<br/>"); </script>
Output :
Yes
No
Time Complexity : O(n)
Auxiliary Space: O(n)
In the next set, we will be discussing approaches to print all pairs with products equal to 0.This article is contributed by Aarti_Rathi and Shubham Goyal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
shrikanth13
rituraj_jain
Akanksha_Rai
rrrtnx
target_2
khushboogoyal499
codewithmini
Amazon
Arrays
Hash
Amazon
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 156,
"s": 52,
"text": "Given an array of distinct elements and a number x, find if there is a pair with a product equal to x. "
},
{
"code": null,
"e": 168,
"s": 156,
"text": "Examples : "
},
{
"code": null,
"e": 507,
"s": 168,
"text": "Input : arr[] = {10, 20, 9, 40};\n int x = 400;\nOutput : Yes\n\nInput : arr[] = {10, 20, 9, 40};\n int x = 190;\nOutput : No\n\nInput : arr[] = {-10, 20, 9, -40};\n int x = 400;\nOutput : Yes\n\nInput : arr[] = {-10, 20, 9, 40};\n int x = -400;\nOutput : Yes\n\nInput : arr[] = {0, 20, 9, 40};\n int x = 0;\nOutput : Yes"
},
{
"code": null,
"e": 649,
"s": 507,
"text": "The naive approach ( O(n2) ) is to run two loops to consider all possible pairs. For every pair, check if the product is equal to x or not. "
},
{
"code": null,
"e": 653,
"s": 649,
"text": "C++"
},
{
"code": null,
"e": 658,
"s": 653,
"text": "Java"
},
{
"code": null,
"e": 666,
"s": 658,
"text": "Python3"
},
{
"code": null,
"e": 669,
"s": 666,
"text": "C#"
},
{
"code": null,
"e": 673,
"s": 669,
"text": "PHP"
},
{
"code": null,
"e": 684,
"s": 673,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find if there is a pair// with given product.#include<bits/stdc++.h>using namespace std; // Returns true if there is a pair in arr[0..n-1]// with product equal to x.bool isProduct(int arr[], int n, int x){ // Consider all possible pairs and check for // every pair. for (int i=0; i<n-1; i++) for (int j=i+1; i<n; i++) if (arr[i] * arr[j] == x) return true; return false;} // Driver codeint main(){ int arr[] = {10, 20, 9, 40}; int x = 400; int n = sizeof(arr)/sizeof(arr[0]); isProduct(arr, n, x)? cout << \"Yesn\" : cout << \"Non\"; x = 190; isProduct(arr, n, x)? cout << \"Yesn\" : cout << \"Non\"; return 0;}",
"e": 1423,
"s": 684,
"text": null
},
{
"code": "// Java program to find if there is a pair// with given product.class GFG{ // Returns true if there is a pair in // arr[0..n-1] with product equal to x. boolean isProduct(int arr[], int n, int x) { for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if (arr[i]*arr[j] == x) return true; return false; } // Driver code public static void main(String[] args) { GFG g = new GFG(); int arr[] = {10, 20, 9, 40}; int x = 400; int n = arr.length; if (g.isProduct(arr, n, x)) System.out.println(\"Yes\"); else System.out.println(\"No\"); x = 190; if (g.isProduct(arr, n, x)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Kamal Rawal",
"e": 2289,
"s": 1423,
"text": null
},
{
"code": "# Python3 program to find if there# is a pair with given product. # Returns true if there is a# pair in arr[0..n-1] with# product equal to xdef isProduct(arr, n, x): for i in arr: for j in arr: if i * j == x: return True return False # Driver code arr = [10, 20, 9, 40]x = 400n = len(arr)if(isProduct(arr,n, x) == True): print (\"Yes\") else: print(\"No\") x = 900if(isProduct(arr, n, x)): print(\"Yes\") else: print(\"No\") # This code is contributed# by prerna saini ",
"e": 2825,
"s": 2289,
"text": null
},
{
"code": "// C# program to find// if there is a pair// with given product.using System; class GFG{ // Returns true if there// is a pair in arr[0..n-1]// with product equal to x.static bool isProduct(int []arr, int n, int x){ for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] == x) return true; return false;} // Driver Codestatic void Main(){ int []arr = {10, 20, 9, 40}; int x = 400; int n = arr.Length; if (isProduct(arr, n, x)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); x = 190; if (isProduct(arr, n, x)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed// by Sam007",
"e": 3582,
"s": 2825,
"text": null
},
{
"code": "<?php// A simple php program to// find if there is a pair// with given product. // Returns true if there// is a pair in arr[0..n-1]// with product equal to x.function isProduct($arr, $n, $x){ // Consider all possible // pairs and check for // every pair. for ($i = 0; $i < $n - 1; $i++) for ($j = $i + 1; $i < $n; $i++) if ($arr[$i] * $arr[$j] == $x) return true; return false;} // Driver code$arr = array(10, 20, 9, 40);$x = 400;$n = count($arr);if(isProduct($arr, $n, $x))echo \"Yes\\n\";elseecho \"No\\n\"; $x = 190;if(isProduct($arr, $n, $x))echo \"Yes\\n\";elseecho \"No\\n\"; // This code is contributed// by Sam007?>",
"e": 4258,
"s": 3582,
"text": null
},
{
"code": "<script> // A simple Javascript program to find if there is a pair// with given product. // Returns true if there is a pair in arr[0..n-1]// with product equal to x.function isProduct(arr, n, x){ // Consider all possible pairs and check for // every pair. for (var i=0; i<n-1; i++) for (var j=i+1; i<n; i++) if (arr[i] * arr[j] == x) return true; return false;} // Driver codevar arr = [10, 20, 9, 40];var x = 400;var n = arr.length;isProduct(arr, n, x)? document.write(\"Yes<br>\") : document.write(\"No<br>\");x = 190;isProduct(arr, n, x)? document.write(\"Yes\") : document.write(\"No\"); </script>",
"e": 4924,
"s": 4258,
"text": null
},
{
"code": null,
"e": 4935,
"s": 4924,
"text": "Output : "
},
{
"code": null,
"e": 4942,
"s": 4935,
"text": "Yes\nNo"
},
{
"code": null,
"e": 4965,
"s": 4942,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 4987,
"s": 4965,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5214,
"s": 4987,
"text": "Better Solution (O(n Log n) : We sort the given array. After sorting, we traverse the array and for every element arr[i], we do binary search for x/arr[i] in the subarray on the right of arr[i], i.e., in subarray arr[i+1..n-1]"
},
{
"code": null,
"e": 5320,
"s": 5214,
"text": "Efficient Solution ( O(n) ): We can improve time complexity to O(n) using hashing. Below are the steps. "
},
{
"code": null,
"e": 5597,
"s": 5320,
"text": "Create an empty hash tableTraverse array elements and do the following for every element arr[i]. If arr[i] is 0 and x is also 0, return true, else ignore arr[i].If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.Insert arr[i] into the hash table.Return false"
},
{
"code": null,
"e": 5624,
"s": 5597,
"text": "Create an empty hash table"
},
{
"code": null,
"e": 5863,
"s": 5624,
"text": "Traverse array elements and do the following for every element arr[i]. If arr[i] is 0 and x is also 0, return true, else ignore arr[i].If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true.Insert arr[i] into the hash table."
},
{
"code": null,
"e": 5928,
"s": 5863,
"text": "If arr[i] is 0 and x is also 0, return true, else ignore arr[i]."
},
{
"code": null,
"e": 5998,
"s": 5928,
"text": "If x % arr[i] is 0 and x/arr[i] exists in the table, it returns true."
},
{
"code": null,
"e": 6033,
"s": 5998,
"text": "Insert arr[i] into the hash table."
},
{
"code": null,
"e": 6046,
"s": 6033,
"text": "Return false"
},
{
"code": null,
"e": 6095,
"s": 6046,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 6099,
"s": 6095,
"text": "C++"
},
{
"code": null,
"e": 6104,
"s": 6099,
"text": "Java"
},
{
"code": null,
"e": 6112,
"s": 6104,
"text": "Python3"
},
{
"code": null,
"e": 6115,
"s": 6112,
"text": "C#"
},
{
"code": null,
"e": 6126,
"s": 6115,
"text": "Javascript"
},
{
"code": "// C++ program to find if there is a pair// with given product.#include<bits/stdc++.h>using namespace std; // Returns true if there is a pair in arr[0..n-1]// with product equal to x.bool isProduct(int arr[], int n, int x){ if (n < 2) return false; // Create an empty set and insert first // element into it unordered_set<int> s; // Traverse remaining elements for (int i=0; i<n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined behaviour in C++ if (arr[i] == 0) { if (x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if (x%arr[i] == 0) { if (s.find(x/arr[i]) != s.end()) return true; // Insert arr[i] s.insert(arr[i]); } } return false;} // Driver codeint main(){ int arr[] = {10, 20, 9, 40}; int x = 400; int n = sizeof(arr)/sizeof(arr[0]); isProduct(arr, n, x)? cout << \"Yes\\n\" : cout << \"Non\"; x = 190; isProduct(arr, n, x)? cout << \"Yes\\n\" : cout << \"Non\"; return 0;}",
"e": 7332,
"s": 6126,
"text": null
},
{
"code": "// Java program if there exists a pair for given productimport java.util.HashSet; class GFG{ // Returns true if there is a pair in arr[0..n-1] // with product equal to x. static boolean isProduct(int arr[], int n, int x) { // Create an empty set and insert first // element into it HashSet<Integer> hset = new HashSet<>(); if(n < 2) return false; // Traverse remaining elements for(int i = 0; i < n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined if(arr[i] == 0) { if(x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if(x % arr[i] == 0) { if(hset.contains(x / arr[i])) return true; // Insert arr[i] hset.add(arr[i]); } } return false; } // driver code public static void main(String[] args) { int arr[] = {10, 20, 9, 40}; int x = 400; int n = arr.length; if(isProduct(arr, arr.length, x)) System.out.println(\"Yes\"); else System.out.println(\"No\"); x = 190; if(isProduct(arr, arr.length, x)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Kamal Rawal",
"e": 8844,
"s": 7332,
"text": null
},
{
"code": "# Python3 program to find if there# is a pair with the given product. # Returns true if there is a pair in# arr[0..n-1] with product equal to x.def isProduct(arr, n, x): if n < 2: return False # Create an empty set and insert # first element into it s = set() # Traverse remaining elements for i in range(0, n): # 0 case must be handles explicitly as # x % 0 is undefined behaviour in C++ if arr[i] == 0: if x == 0: return True else: continue # x/arr[i] exists in hash, then # we found a pair if x % arr[i] == 0: if x // arr[i] in s: return True # Insert arr[i] s.add(arr[i]) return False # Driver codeif __name__ == \"__main__\": arr = [10, 20, 9, 40] x = 400 n = len(arr) if isProduct(arr, n, x): print(\"Yes\") else: print(\"No\") x = 190 if isProduct(arr, n, x): print(\"Yes\") else: print(\"No\") # This code is contributed by# Rituraj Jain",
"e": 9938,
"s": 8844,
"text": null
},
{
"code": "// C# program if there exists a// pair for given productusing System;using System.Collections.Generic; class GFG{// Returns true if there is a pair// in arr[0..n-1] with product equal to x.public static bool isProduct(int[] arr, int n, int x){ // Create an empty set and insert // first element into it HashSet<int> hset = new HashSet<int>(); if (n < 2) { return false; } // Traverse remaining elements for (int i = 0; i < n; i++) { // 0 case must be handles explicitly // as x % 0 is undefined if (arr[i] == 0) { if (x == 0) { return true; } else { continue; } } // x/arr[i] exists in hash, then // we found a pair if (x % arr[i] == 0) { if (hset.Contains(x / arr[i])) { return true; } // Insert arr[i] hset.Add(arr[i]); } } return false;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {10, 20, 9, 40}; int x = 400; int n = arr.Length; if (isProduct(arr, arr.Length, x)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } x = 190; if (isProduct(arr, arr.Length, x)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); }}} // This code is contributed by Shrikant13",
"e": 11435,
"s": 9938,
"text": null
},
{
"code": "<script> // Javascript program if there exists a pair for given product // Returns true if there is a pair in arr[0..n-1] // with product equal to x. function isProduct(arr, n, x) { // Create an empty set and insert first // element into it let hset = new Set(); if(n < 2) return false; // Traverse remaining elements for(let i = 0; i < n; i++) { // 0 case must be handles explicitly as // x % 0 is undefined if(arr[i] == 0) { if(x == 0) return true; else continue; } // x/arr[i] exists in hash, then we // found a pair if(x % arr[i] == 0) { if(hset.has(x / arr[i])) return true; // Insert arr[i] hset.add(arr[i]); } } return false; } // Driver program let arr = [10, 20, 9, 40]; let x = 400; let n = arr.length; if(isProduct(arr, arr.length, x)) document.write(\"Yes\" + \"<br/>\"); else document.write(\"No\" + \"<br/>\"); x = 190; if(isProduct(arr, arr.length, x)) document.write(\"Yes\" + \"<br/>\"); else document.write(\"No\" + \"<br/>\"); </script>",
"e": 12842,
"s": 11435,
"text": null
},
{
"code": null,
"e": 12852,
"s": 12842,
"text": "Output : "
},
{
"code": null,
"e": 12859,
"s": 12852,
"text": "Yes\nNo"
},
{
"code": null,
"e": 12882,
"s": 12859,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 12904,
"s": 12882,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 13185,
"s": 12904,
"text": "In the next set, we will be discussing approaches to print all pairs with products equal to 0.This article is contributed by Aarti_Rathi and Shubham Goyal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 13192,
"s": 13185,
"text": "Sam007"
},
{
"code": null,
"e": 13204,
"s": 13192,
"text": "shrikanth13"
},
{
"code": null,
"e": 13217,
"s": 13204,
"text": "rituraj_jain"
},
{
"code": null,
"e": 13230,
"s": 13217,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 13237,
"s": 13230,
"text": "rrrtnx"
},
{
"code": null,
"e": 13246,
"s": 13237,
"text": "target_2"
},
{
"code": null,
"e": 13263,
"s": 13246,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 13276,
"s": 13263,
"text": "codewithmini"
},
{
"code": null,
"e": 13283,
"s": 13276,
"text": "Amazon"
},
{
"code": null,
"e": 13290,
"s": 13283,
"text": "Arrays"
},
{
"code": null,
"e": 13295,
"s": 13290,
"text": "Hash"
},
{
"code": null,
"e": 13302,
"s": 13295,
"text": "Amazon"
},
{
"code": null,
"e": 13309,
"s": 13302,
"text": "Arrays"
},
{
"code": null,
"e": 13314,
"s": 13309,
"text": "Hash"
},
{
"code": null,
"e": 13412,
"s": 13314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13480,
"s": 13412,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 13524,
"s": 13480,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 13556,
"s": 13524,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 13604,
"s": 13556,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 13618,
"s": 13604,
"text": "Linear Search"
},
{
"code": null,
"e": 13703,
"s": 13618,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 13741,
"s": 13703,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 13777,
"s": 13741,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 13808,
"s": 13777,
"text": "Hashing | Set 1 (Introduction)"
}
] |
Python – Get Random Range Average
|
28 Jul, 2020
Given range and Size of elements, extract random numbers within a range, and perform average of it.
Input : N = 3, strt_num = 10, end_num = 15Output : 13.58Explanation : Random elements extracted between 10 and 15, averaging out to 13.58.
Input : N = 2, strt_num = 13, end_num = 18Output : 15.82Explanation : 2 elements average to 15.82 in this case.
Method #1 : Using loop + uniform()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting numbers using uniform() and loop is used to perform addition of numbers. The average is computed at end by dividing by size.
# Python3 code to demonstrate working of # Random Range Average# Using loop + uniform()import random # initializing Nnum = 4 # Initialize strt_numstrt_num = 15 # Initialize end_numend_num = 60 # Using loop + uniform()res = 0.0for _ in range(num): # performing summation of range elements res += random.uniform(strt_num, end_num) # performing averageres = res / num # printing result print("The average value : " + str(res))
The average value : 42.980287235196116
Method #2 : Using sum() + uniform() + generator expressionThe combination of above functions can be used to solve this problem. In this, we perform the task of performing average using sum() to compute sum() and whole logic is encapsulated in one-liner using generator expression.
# Python3 code to demonstrate working of # Random Range Average# Using sum() + uniform() + generator expressionimport random # initializing Nnum = 4 # Initialize strt_numstrt_num = 15 # Initialize end_numend_num = 60 # Using sum() + uniform() + generator expression# shorthand, using generator expression to form sum and division by Sizeres = sum(random.uniform(strt_num, end_num) for _ in range(num)) / num # printing result print("The average value : " + str(res))
The average value : 42.980287235196116
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "Given range and Size of elements, extract random numbers within a range, and perform average of it."
},
{
"code": null,
"e": 267,
"s": 128,
"text": "Input : N = 3, strt_num = 10, end_num = 15Output : 13.58Explanation : Random elements extracted between 10 and 15, averaging out to 13.58."
},
{
"code": null,
"e": 379,
"s": 267,
"text": "Input : N = 2, strt_num = 13, end_num = 18Output : 15.82Explanation : 2 elements average to 15.82 in this case."
},
{
"code": null,
"e": 651,
"s": 379,
"text": "Method #1 : Using loop + uniform()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting numbers using uniform() and loop is used to perform addition of numbers. The average is computed at end by dividing by size."
},
{
"code": "# Python3 code to demonstrate working of # Random Range Average# Using loop + uniform()import random # initializing Nnum = 4 # Initialize strt_numstrt_num = 15 # Initialize end_numend_num = 60 # Using loop + uniform()res = 0.0for _ in range(num): # performing summation of range elements res += random.uniform(strt_num, end_num) # performing averageres = res / num # printing result print(\"The average value : \" + str(res)) ",
"e": 1099,
"s": 651,
"text": null
},
{
"code": null,
"e": 1139,
"s": 1099,
"text": "The average value : 42.980287235196116\n"
},
{
"code": null,
"e": 1422,
"s": 1141,
"text": "Method #2 : Using sum() + uniform() + generator expressionThe combination of above functions can be used to solve this problem. In this, we perform the task of performing average using sum() to compute sum() and whole logic is encapsulated in one-liner using generator expression."
},
{
"code": "# Python3 code to demonstrate working of # Random Range Average# Using sum() + uniform() + generator expressionimport random # initializing Nnum = 4 # Initialize strt_numstrt_num = 15 # Initialize end_numend_num = 60 # Using sum() + uniform() + generator expression# shorthand, using generator expression to form sum and division by Sizeres = sum(random.uniform(strt_num, end_num) for _ in range(num)) / num # printing result print(\"The average value : \" + str(res))",
"e": 1894,
"s": 1422,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1894,
"text": "The average value : 42.980287235196116\n"
},
{
"code": null,
"e": 1941,
"s": 1934,
"text": "Python"
},
{
"code": null,
"e": 1957,
"s": 1941,
"text": "Python Programs"
}
] |
Java Program to Convert Object to String
|
08 Dec, 2020
The first byte needs to be converted into an object byte which can easily be dealt with to convert to strings. Convert Object to String in java using toString() method of Object class or String.valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.
Approaches:
Converting User-defined class object to StringConverting StringBuilder(Predefined class) object to String
Converting User-defined class object to String
Converting StringBuilder(Predefined class) object to String
Method 1: Using toString() method or String.valueOf(object_name) method.
Java
// Java Program to convert pre defined class object// (Helper class) to string using value() method class GFG { // Main driver method public static void main(String[] args) { // Object of helper class Helper help = new Helper(); // converting object to string // using toString() method String s1 = help.toString(); // converting object to string // using valueOf() method String s2 = String.valueOf(help); // Printing the converted string System.out.println( "Converted string object || using toString() Method: " + s1); // Printing the converted string System.out.println( "Converted string object || using valueOf() Method: " + s2); }} class Helper { // To make class object in main}
Converted string object || using toString() Method: Helper@214c265e
Converted string object || using valueOf() Method: Helper@214c265e
Method 2: Converting StringBuilder(Predefined class) object to String.
The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.
Class Hierarchy:
java.lang.Object
↳ java.lang
↳ Class StringBuilder
Example:
Java
// Java Program to convert StringBuilder object to string class GFG { // Main driver method public static void main(String[] args) { /* String taken for consideration */ String s = "Geeks For Geeks"; // Passing string s to StringBuilder class object StringBuilder sb = new StringBuilder(s); // Converting the object to string // Converting StringBuilder to string String objToString = sb.toString(); // Printing the strings to verify System.out.println("String: " + s); System.out.println("Converted String: " + objToString); }}
String: Geeks For Geeks
Converted String: Geeks For Geeks
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "The first byte needs to be converted into an object byte which can easily be dealt with to convert to strings. Convert Object to String in java using toString() method of Object class or String.valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string."
},
{
"code": null,
"e": 443,
"s": 431,
"text": "Approaches:"
},
{
"code": null,
"e": 549,
"s": 443,
"text": "Converting User-defined class object to StringConverting StringBuilder(Predefined class) object to String"
},
{
"code": null,
"e": 596,
"s": 549,
"text": "Converting User-defined class object to String"
},
{
"code": null,
"e": 656,
"s": 596,
"text": "Converting StringBuilder(Predefined class) object to String"
},
{
"code": null,
"e": 729,
"s": 656,
"text": "Method 1: Using toString() method or String.valueOf(object_name) method."
},
{
"code": null,
"e": 734,
"s": 729,
"text": "Java"
},
{
"code": "// Java Program to convert pre defined class object// (Helper class) to string using value() method class GFG { // Main driver method public static void main(String[] args) { // Object of helper class Helper help = new Helper(); // converting object to string // using toString() method String s1 = help.toString(); // converting object to string // using valueOf() method String s2 = String.valueOf(help); // Printing the converted string System.out.println( \"Converted string object || using toString() Method: \" + s1); // Printing the converted string System.out.println( \"Converted string object || using valueOf() Method: \" + s2); }} class Helper { // To make class object in main}",
"e": 1554,
"s": 734,
"text": null
},
{
"code": null,
"e": 1689,
"s": 1554,
"text": "Converted string object || using toString() Method: Helper@214c265e\nConverted string object || using valueOf() Method: Helper@214c265e"
},
{
"code": null,
"e": 1760,
"s": 1689,
"text": "Method 2: Converting StringBuilder(Predefined class) object to String."
},
{
"code": null,
"e": 2020,
"s": 1760,
"text": "The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters."
},
{
"code": null,
"e": 2037,
"s": 2020,
"text": "Class Hierarchy:"
},
{
"code": null,
"e": 2093,
"s": 2037,
"text": "java.lang.Object\n ↳ java.lang\n ↳ Class StringBuilder"
},
{
"code": null,
"e": 2103,
"s": 2093,
"text": "Example: "
},
{
"code": null,
"e": 2108,
"s": 2103,
"text": "Java"
},
{
"code": "// Java Program to convert StringBuilder object to string class GFG { // Main driver method public static void main(String[] args) { /* String taken for consideration */ String s = \"Geeks For Geeks\"; // Passing string s to StringBuilder class object StringBuilder sb = new StringBuilder(s); // Converting the object to string // Converting StringBuilder to string String objToString = sb.toString(); // Printing the strings to verify System.out.println(\"String: \" + s); System.out.println(\"Converted String: \" + objToString); }}",
"e": 2754,
"s": 2108,
"text": null
},
{
"code": null,
"e": 2812,
"s": 2754,
"text": "String: Geeks For Geeks\nConverted String: Geeks For Geeks"
},
{
"code": null,
"e": 2819,
"s": 2812,
"text": "Picked"
},
{
"code": null,
"e": 2843,
"s": 2819,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2848,
"s": 2843,
"text": "Java"
},
{
"code": null,
"e": 2862,
"s": 2848,
"text": "Java Programs"
},
{
"code": null,
"e": 2881,
"s": 2862,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2886,
"s": 2881,
"text": "Java"
},
{
"code": null,
"e": 2984,
"s": 2886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3003,
"s": 2984,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3033,
"s": 3003,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3051,
"s": 3033,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3066,
"s": 3051,
"text": "Stream In Java"
},
{
"code": null,
"e": 3086,
"s": 3066,
"text": "Collections in Java"
},
{
"code": null,
"e": 3114,
"s": 3086,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 3140,
"s": 3114,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3184,
"s": 3140,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 3218,
"s": 3184,
"text": "Convert Double to Integer in Java"
}
] |
Tcl - Error Handling
|
Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below.
error message info code
In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode.
catch script resultVarName
In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error.
An example for simple error handling is shown below −
#!/usr/bin/tclsh
proc Div {a b} {
if {$b == 0} {
error "Error generated by error" "Info String for error" 401
} else {
return [expr $a/$b]
}
}
if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
When the above code is executed, it produces the following result −
ErrorMsg: Error generated by error
ErrorCode: 401
ErrorInfo:
Info String for error
(procedure "Div" line 1)
invoked from within
"Div 10 0"
Result = 5
As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −
#!/usr/bin/tclsh
catch {set file [open myNonexistingfile.txt]} result
puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
When the above code is executed, it produces the following result −
ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or directory
ErrorCode: POSIX ENOENT {no such file or directory}
ErrorInfo:
couldn't open "myNonexistingfile.txt": no such file or directory
|
[
{
"code": null,
"e": 2466,
"s": 2335,
"text": "Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below."
},
{
"code": null,
"e": 2491,
"s": 2466,
"text": "error message info code\n"
},
{
"code": null,
"e": 2651,
"s": 2491,
"text": "In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode."
},
{
"code": null,
"e": 2679,
"s": 2651,
"text": "catch script resultVarName\n"
},
{
"code": null,
"e": 2889,
"s": 2679,
"text": "In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error."
},
{
"code": null,
"e": 2943,
"s": 2889,
"text": "An example for simple error handling is shown below −"
},
{
"code": null,
"e": 3406,
"s": 2943,
"text": "#!/usr/bin/tclsh\n\nproc Div {a b} {\n if {$b == 0} {\n error \"Error generated by error\" \"Info String for error\" 401\n } else {\n return [expr $a/$b]\n }\n}\n\nif {[catch {puts \"Result = [Div 10 0]\"} errmsg]} {\n puts \"ErrorMsg: $errmsg\"\n puts \"ErrorCode: $errorCode\"\n puts \"ErrorInfo:\\n$errorInfo\\n\"\n}\n\nif {[catch {puts \"Result = [Div 10 2]\"} errmsg]} {\n puts \"ErrorMsg: $errmsg\"\n puts \"ErrorCode: $errorCode\"\n puts \"ErrorInfo:\\n$errorInfo\\n\"\n}"
},
{
"code": null,
"e": 3474,
"s": 3406,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3632,
"s": 3474,
"text": "ErrorMsg: Error generated by error\nErrorCode: 401\nErrorInfo:\nInfo String for error\n (procedure \"Div\" line 1)\n invoked from within\n\"Div 10 0\"\n\nResult = 5\n"
},
{
"code": null,
"e": 3805,
"s": 3632,
"text": "As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −"
},
{
"code": null,
"e": 3962,
"s": 3805,
"text": "#!/usr/bin/tclsh\n\ncatch {set file [open myNonexistingfile.txt]} result\nputs \"ErrorMsg: $result\"\nputs \"ErrorCode: $errorCode\"\nputs \"ErrorInfo:\\n$errorInfo\\n\""
},
{
"code": null,
"e": 4030,
"s": 3962,
"text": "When the above code is executed, it produces the following result −"
}
] |
Get the relative timestamp difference between dates in JavaScript
|
28 Jan, 2020
Given the 2 JavaScript dates and the job is to get the relative time difference between them(eg.. 2 hours ago, 2.5 days ago, etc.) Here 2 approaches are discussed with the help of javaScript.
Approach 1:
Get the prevDate and currDate in a variable.
Calculate the milliseconds in Minute, Hour, Day, Month and in an Year.
Calculate the milliseconds difference between the prevDate and currDate.
Compare these milliseconds with the milliseconds in Minute, Hour, Day, Month and in an year in this order.
If the milliseconds are less than any of them, then calculate the respective Minutes, Hours, Days, Months and Years.
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Get the relative timestamp difference between dates in JavaScript. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var prevDate = new Date(); prevDate.setDate(prevDate.getDate() - 6); up.innerHTML = "Click on the button to get relative time difference between dates." + "<br><br>Older Date : " + prevDate; function timeDiff(curr, prev) { var ms_Min = 60 * 1000; // milliseconds in Minute var ms_Hour = ms_Min * 60; // milliseconds in Hour var ms_Day = ms_Hour * 24; // milliseconds in day var ms_Mon = ms_Day * 30; // milliseconds in Month var ms_Yr = ms_Day * 365; // milliseconds in Year var diff = curr - prev; //difference between dates. // If the diff is less then milliseconds in a minute if (diff < ms_Min) { return Math.round(diff / 1000) + ' seconds ago'; // If the diff is less then milliseconds in a Hour } else if (diff < ms_Hour) { return Math.round(diff / ms_Min) + ' minutes ago'; // If the diff is less then milliseconds in a day } else if (diff < ms_Day) { return Math.round(diff / ms_Hour) + ' hours ago'; // If the diff is less then milliseconds in a Month } else if (diff < ms_Mon) { return 'Around ' + Math.round(diff / ms_Day) + ' days ago'; // If the diff is less then milliseconds in a year } else if (diff < ms_Yr) { return 'Around ' + Math.round(diff / ms_Mon) + ' months ago'; } else { return 'Around ' + Math.round(diff / ms_Yr) + ' years ago'; } } function GFG_Fun() { $('#GFG_DOWN').html(timeDiff(new Date(), prevDate)); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Get the prevDate and currDate in a variable.
Calculate the seconds, Minutes, Hours and Days difference between the dates.
Compare these parameters with the 60 seconds, 60 Minutes, 24 Hours, Day in this order.
If any of those condition satisfies then return the respective parameter.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Get the relative timestamp difference between dates in JavaScript. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var prevDate = new Date(); prevDate.setDate(prevDate.getDate() - 6); prevDate.setHours(prevDate.getHours() - 6); up.innerHTML = "Click on the button to get relative time " + "difference between dates.<br><br>Older Date : " + prevDate; function conversion(ms) { // Calculating Seconds var sec = (ms / 1000).toFixed(1); // Calculating Minutes var min = (ms / (1000 * 60)).toFixed(1); // Calculating hours var hrs = (ms / (1000 * 60 * 60)).toFixed(1); // Calculating days var days = (ms / (1000 * 60 * 60 * 24)).toFixed(1); if (sec < 60) { return sec + " Sec"; } else if (min < 60) { return min + " Min"; } else if (hrs < 24) { return hrs + " Hrs"; } else { return days + " Days" } } function GFG_Fun() { var date = new Date();$('#GFG_DOWN').html(conversion(date.getTime() - prevDate.getTime())); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-date
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n28 Jan, 2020"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "Given the 2 JavaScript dates and the job is to get the relative time difference between them(eg.. 2 hours ago, 2.5 days ago, etc.) Here 2 approaches are discussed with the help of javaScript."
},
{
"code": null,
"e": 232,
"s": 220,
"text": "Approach 1:"
},
{
"code": null,
"e": 277,
"s": 232,
"text": "Get the prevDate and currDate in a variable."
},
{
"code": null,
"e": 348,
"s": 277,
"text": "Calculate the milliseconds in Minute, Hour, Day, Month and in an Year."
},
{
"code": null,
"e": 421,
"s": 348,
"text": "Calculate the milliseconds difference between the prevDate and currDate."
},
{
"code": null,
"e": 528,
"s": 421,
"text": "Compare these milliseconds with the milliseconds in Minute, Hour, Day, Month and in an year in this order."
},
{
"code": null,
"e": 645,
"s": 528,
"text": "If the milliseconds are less than any of them, then calculate the respective Minutes, Hours, Days, Months and Years."
},
{
"code": null,
"e": 700,
"s": 645,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Get the relative timestamp difference between dates in JavaScript. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var prevDate = new Date(); prevDate.setDate(prevDate.getDate() - 6); up.innerHTML = \"Click on the button to get relative time difference between dates.\" + \"<br><br>Older Date : \" + prevDate; function timeDiff(curr, prev) { var ms_Min = 60 * 1000; // milliseconds in Minute var ms_Hour = ms_Min * 60; // milliseconds in Hour var ms_Day = ms_Hour * 24; // milliseconds in day var ms_Mon = ms_Day * 30; // milliseconds in Month var ms_Yr = ms_Day * 365; // milliseconds in Year var diff = curr - prev; //difference between dates. // If the diff is less then milliseconds in a minute if (diff < ms_Min) { return Math.round(diff / 1000) + ' seconds ago'; // If the diff is less then milliseconds in a Hour } else if (diff < ms_Hour) { return Math.round(diff / ms_Min) + ' minutes ago'; // If the diff is less then milliseconds in a day } else if (diff < ms_Day) { return Math.round(diff / ms_Hour) + ' hours ago'; // If the diff is less then milliseconds in a Month } else if (diff < ms_Mon) { return 'Around ' + Math.round(diff / ms_Day) + ' days ago'; // If the diff is less then milliseconds in a year } else if (diff < ms_Yr) { return 'Around ' + Math.round(diff / ms_Mon) + ' months ago'; } else { return 'Around ' + Math.round(diff / ms_Yr) + ' years ago'; } } function GFG_Fun() { $('#GFG_DOWN').html(timeDiff(new Date(), prevDate)); } </script></body> </html>",
"e": 3039,
"s": 700,
"text": null
},
{
"code": null,
"e": 3047,
"s": 3039,
"text": "Output:"
},
{
"code": null,
"e": 3078,
"s": 3047,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3108,
"s": 3078,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3120,
"s": 3108,
"text": "Approach 2:"
},
{
"code": null,
"e": 3165,
"s": 3120,
"text": "Get the prevDate and currDate in a variable."
},
{
"code": null,
"e": 3242,
"s": 3165,
"text": "Calculate the seconds, Minutes, Hours and Days difference between the dates."
},
{
"code": null,
"e": 3329,
"s": 3242,
"text": "Compare these parameters with the 60 seconds, 60 Minutes, 24 Hours, Day in this order."
},
{
"code": null,
"e": 3403,
"s": 3329,
"text": "If any of those condition satisfies then return the respective parameter."
},
{
"code": null,
"e": 3458,
"s": 3403,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Get the relative timestamp difference between dates in JavaScript. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var prevDate = new Date(); prevDate.setDate(prevDate.getDate() - 6); prevDate.setHours(prevDate.getHours() - 6); up.innerHTML = \"Click on the button to get relative time \" + \"difference between dates.<br><br>Older Date : \" + prevDate; function conversion(ms) { // Calculating Seconds var sec = (ms / 1000).toFixed(1); // Calculating Minutes var min = (ms / (1000 * 60)).toFixed(1); // Calculating hours var hrs = (ms / (1000 * 60 * 60)).toFixed(1); // Calculating days var days = (ms / (1000 * 60 * 60 * 24)).toFixed(1); if (sec < 60) { return sec + \" Sec\"; } else if (min < 60) { return min + \" Min\"; } else if (hrs < 24) { return hrs + \" Hrs\"; } else { return days + \" Days\" } } function GFG_Fun() { var date = new Date();$('#GFG_DOWN').html(conversion(date.getTime() - prevDate.getTime())); } </script></body> </html>",
"e": 5167,
"s": 3458,
"text": null
},
{
"code": null,
"e": 5175,
"s": 5167,
"text": "Output:"
},
{
"code": null,
"e": 5206,
"s": 5175,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 5236,
"s": 5206,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 5252,
"s": 5236,
"text": "javascript-date"
},
{
"code": null,
"e": 5268,
"s": 5252,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5279,
"s": 5268,
"text": "JavaScript"
},
{
"code": null,
"e": 5296,
"s": 5279,
"text": "Web Technologies"
},
{
"code": null,
"e": 5394,
"s": 5296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5455,
"s": 5394,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5527,
"s": 5455,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5567,
"s": 5527,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5620,
"s": 5567,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5672,
"s": 5620,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5734,
"s": 5672,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5767,
"s": 5734,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5828,
"s": 5767,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5878,
"s": 5828,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Resize image proportionally with CSS
|
10 May, 2022
The resize image property is used in responsive web where image is resizing automatically to fit the div container. The max-width property in CSS is used to create resize image property. The resize property will not work if width and height of image defined in the HTML.
Syntax:
img {
max-width:100%;
height:auto;
}
Width can also be used instead of max-width if desired. The key is to use height:auto to override any height=”...” attribute already present on the image. The CSS properties max-width and max-height work great, but aren’t supported many browsers. Example 1:
html
<!DOCTYPE html><html> <head> <title>cell padding</title> <style> .gfg { width:auto; text-align:center; padding:20px; } img { max-width:100%; height:auto; } </style> </head> <body> <div class = "gfg"> <p id="my-image"><img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png"> </p> </div> </body></html>
Output:
A common use is to set max-width: 100%; height: auto; so large images don’t exceed their containers width. Another way is the use of object-fit property, this will fit image, without changing the proportionally.
Example 2:
html
<!DOCTYPE html><html> <head> <title>cell padding</title> <style> .gfg { width:auto; text-align:center; padding:20px; } img { width: 100%; height: 100%; object-fit: contain; } </style> </head> <body> <div class = "gfg"> <p id="my-image"><img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png"> </p> </div> </body></html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
hardikkoriintern
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 325,
"s": 53,
"text": "The resize image property is used in responsive web where image is resizing automatically to fit the div container. The max-width property in CSS is used to create resize image property. The resize property will not work if width and height of image defined in the HTML. "
},
{
"code": null,
"e": 333,
"s": 325,
"text": "Syntax:"
},
{
"code": null,
"e": 378,
"s": 333,
"text": "img {\n max-width:100%;\n height:auto;\n}"
},
{
"code": null,
"e": 637,
"s": 378,
"text": "Width can also be used instead of max-width if desired. The key is to use height:auto to override any height=”...” attribute already present on the image. The CSS properties max-width and max-height work great, but aren’t supported many browsers. Example 1: "
},
{
"code": null,
"e": 642,
"s": 637,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>cell padding</title> <style> .gfg { width:auto; text-align:center; padding:20px; } img { max-width:100%; height:auto; } </style> </head> <body> <div class = \"gfg\"> <p id=\"my-image\"><img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png\"> </p> </div> </body></html>",
"e": 1166,
"s": 642,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1166,
"text": "Output: "
},
{
"code": null,
"e": 1388,
"s": 1175,
"text": "A common use is to set max-width: 100%; height: auto; so large images don’t exceed their containers width. Another way is the use of object-fit property, this will fit image, without changing the proportionally. "
},
{
"code": null,
"e": 1400,
"s": 1388,
"text": "Example 2: "
},
{
"code": null,
"e": 1405,
"s": 1400,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>cell padding</title> <style> .gfg { width:auto; text-align:center; padding:20px; } img { width: 100%; height: 100%; object-fit: contain; } </style> </head> <body> <div class = \"gfg\"> <p id=\"my-image\"><img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png\"> </p> </div> </body></html> ",
"e": 1978,
"s": 1405,
"text": null
},
{
"code": null,
"e": 1987,
"s": 1978,
"text": "Output: "
},
{
"code": null,
"e": 2174,
"s": 1987,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 2191,
"s": 2174,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 2198,
"s": 2191,
"text": "Picked"
},
{
"code": null,
"e": 2202,
"s": 2198,
"text": "CSS"
},
{
"code": null,
"e": 2207,
"s": 2202,
"text": "HTML"
},
{
"code": null,
"e": 2224,
"s": 2207,
"text": "Web Technologies"
},
{
"code": null,
"e": 2251,
"s": 2224,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2256,
"s": 2251,
"text": "HTML"
}
] |
Program to find average of all nodes in a Linked List
|
29 Oct, 2021
Given a singly linked list. The task is to find the average of all nodes of the given singly linked list.Examples:
Input: 7->6->8->4->1
Output: 26
Average of nodes:
(7 + 6 + 8 + 4 + 1 ) / 5 = 5.2
Input: 1->7->3->9->11->5
Output: 6
Iterative Solution:
Initialise a pointer ptr with the head of the linked list and a sum variable with 0.Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .Divide sum by total number of node and Return the average.
Initialise a pointer ptr with the head of the linked list and a sum variable with 0.
Start traversing the linked list using a loop until all the nodes get traversed.
Add the value of current node to the sum i.e. sum += ptr -> data .
Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .
Divide sum by total number of node and Return the average.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the average of// nodes of the Linked List #include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to iteratively find the avg of// nodes of the given linked listfloat avgOfNodes(struct Node* head){ // if head = NULL if (!head) return -1; int count = 0; // Initialize count int sum = 0; float avg = 0.0; struct Node* current = head; // Initialize current while (current != NULL) { count++; sum += current->data; current = current->next; } // calculate average avg = (double)sum / count; return avg;} // Driver Codeint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << "Average of nodes = " << avgOfNodes(head); return 0;}
// Java implementation to find the average of// nodes of the Linked Listclass GFG{ /* A Linked list node */static class Node { int data; Node next;}; // function to insert a node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref;} // Function to iteratively find the avg of// nodes of the given linked liststatic double avgOfNodes(Node head){ // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg;} // Driver Codepublic static void main(String args[]){ Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); System.out.println("Average of nodes = " + avgOfNodes(head));}}// This code is contributed by Arnab Kundu
# Python3 implementation to find the average of # nodes of the Linked List class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert a node at the # beginning of the linked list def push(node,data): ''' allocate node ''' if (node == None): return (newNode(data)) else: node.next = push(node.next, data) return node # Function to iteratively find the avg of # nodes of the given linked list def avgOfNodes(head): # if head = NULL if (head == None): return -1 count = 0 # Initialize count sum = 0 avg = 0.0 while (head != None): count += 1 sum += head.data head = head.next # calculate average avg = sum / count return avg # Driver Code # create linked list 7.6.8.4.1 head = newNode(7) push(head, 6) push(head, 8) push(head, 4) push(head, 1) print("Average of nodes = ",avgOfNodes(head)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# implementation to find the average // of nodes of the Linked List using System; class GFG { /* A Linked list node */public class Node { public int data; public Node next; }; // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list static double avgOfNodes(Node head) { // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg; } // Driver Code public static void Main(String []args) { Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); Console.WriteLine("Average of nodes = " + avgOfNodes(head)); } } // This code is contributed by Rajput-Ji
<script>// javascript implementation to find the average of// nodes of the Linked List /* A Linked list node */class Node { constructor(val) { this.data = val; this.next = null; }} // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list function avgOfNodes(head) { // if head = null if (head == null) return -1; var count = 0; // Initialize count var sum = 0; var avg = 0.0; var current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = sum / count; return avg; } // Driver Code var head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); document.write("Average of nodes = " + avgOfNodes(head)); // This code contributed by aashish1995</script>
Average of nodes = 5.2
Time complexity : O(n) Where n is equal to number of nodes.
VishalBachchas
andrew1234
Rajput-Ji
SHUBHAMSINGH10
aashish1995
simranarora5sos
maths-mean
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.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Types of Linked List
Circular Singly Linked List | Insertion
Find first node of loop in a linked list
Add two numbers represented by linked lists | Set 2
Flattening a Linked List
Real-time application of Data Structures
Insert a node at a specific position in a linked list
Clone a linked list with next and random pointer | Set 1
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 145,
"s": 28,
"text": "Given a singly linked list. The task is to find the average of all nodes of the given singly linked list.Examples: "
},
{
"code": null,
"e": 262,
"s": 145,
"text": "Input: 7->6->8->4->1\nOutput: 26\nAverage of nodes:\n(7 + 6 + 8 + 4 + 1 ) / 5 = 5.2\n\nInput: 1->7->3->9->11->5\nOutput: 6"
},
{
"code": null,
"e": 286,
"s": 264,
"text": "Iterative Solution: "
},
{
"code": null,
"e": 652,
"s": 286,
"text": "Initialise a pointer ptr with the head of the linked list and a sum variable with 0.Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .Divide sum by total number of node and Return the average."
},
{
"code": null,
"e": 737,
"s": 652,
"text": "Initialise a pointer ptr with the head of the linked list and a sum variable with 0."
},
{
"code": null,
"e": 818,
"s": 737,
"text": "Start traversing the linked list using a loop until all the nodes get traversed."
},
{
"code": null,
"e": 885,
"s": 818,
"text": "Add the value of current node to the sum i.e. sum += ptr -> data ."
},
{
"code": null,
"e": 963,
"s": 885,
"text": "Increment the pointer to the next node of linked list i.e. ptr = ptr ->next ."
},
{
"code": null,
"e": 1022,
"s": 963,
"text": "Divide sum by total number of node and Return the average."
},
{
"code": null,
"e": 1074,
"s": 1022,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1078,
"s": 1074,
"text": "C++"
},
{
"code": null,
"e": 1083,
"s": 1078,
"text": "Java"
},
{
"code": null,
"e": 1091,
"s": 1083,
"text": "Python3"
},
{
"code": null,
"e": 1094,
"s": 1091,
"text": "C#"
},
{
"code": null,
"e": 1105,
"s": 1094,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the average of// nodes of the Linked List #include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to iteratively find the avg of// nodes of the given linked listfloat avgOfNodes(struct Node* head){ // if head = NULL if (!head) return -1; int count = 0; // Initialize count int sum = 0; float avg = 0.0; struct Node* current = head; // Initialize current while (current != NULL) { count++; sum += current->data; current = current->next; } // calculate average avg = (double)sum / count; return avg;} // Driver Codeint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << \"Average of nodes = \" << avgOfNodes(head); return 0;}",
"e": 2435,
"s": 1105,
"text": null
},
{
"code": "// Java implementation to find the average of// nodes of the Linked Listclass GFG{ /* A Linked list node */static class Node { int data; Node next;}; // function to insert a node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref;} // Function to iteratively find the avg of// nodes of the given linked liststatic double avgOfNodes(Node head){ // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg;} // Driver Codepublic static void main(String args[]){ Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); System.out.println(\"Average of nodes = \" + avgOfNodes(head));}}// This code is contributed by Arnab Kundu",
"e": 3817,
"s": 2435,
"text": null
},
{
"code": "# Python3 implementation to find the average of # nodes of the Linked List class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert a node at the # beginning of the linked list def push(node,data): ''' allocate node ''' if (node == None): return (newNode(data)) else: node.next = push(node.next, data) return node # Function to iteratively find the avg of # nodes of the given linked list def avgOfNodes(head): # if head = NULL if (head == None): return -1 count = 0 # Initialize count sum = 0 avg = 0.0 while (head != None): count += 1 sum += head.data head = head.next # calculate average avg = sum / count return avg # Driver Code # create linked list 7.6.8.4.1 head = newNode(7) push(head, 6) push(head, 8) push(head, 4) push(head, 1) print(\"Average of nodes = \",avgOfNodes(head)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) ",
"e": 4897,
"s": 3817,
"text": null
},
{
"code": "// C# implementation to find the average // of nodes of the Linked List using System; class GFG { /* A Linked list node */public class Node { public int data; public Node next; }; // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list static double avgOfNodes(Node head) { // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg; } // Driver Code public static void Main(String []args) { Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); Console.WriteLine(\"Average of nodes = \" + avgOfNodes(head)); } } // This code is contributed by Rajput-Ji",
"e": 6400,
"s": 4897,
"text": null
},
{
"code": "<script>// javascript implementation to find the average of// nodes of the Linked List /* A Linked list node */class Node { constructor(val) { this.data = val; this.next = null; }} // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list function avgOfNodes(head) { // if head = null if (head == null) return -1; var count = 0; // Initialize count var sum = 0; var avg = 0.0; var current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = sum / count; return avg; } // Driver Code var head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); document.write(\"Average of nodes = \" + avgOfNodes(head)); // This code contributed by aashish1995</script>",
"e": 7908,
"s": 6400,
"text": null
},
{
"code": null,
"e": 7931,
"s": 7908,
"text": "Average of nodes = 5.2"
},
{
"code": null,
"e": 7994,
"s": 7933,
"text": "Time complexity : O(n) Where n is equal to number of nodes. "
},
{
"code": null,
"e": 8009,
"s": 7994,
"text": "VishalBachchas"
},
{
"code": null,
"e": 8020,
"s": 8009,
"text": "andrew1234"
},
{
"code": null,
"e": 8030,
"s": 8020,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8045,
"s": 8030,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8057,
"s": 8045,
"text": "aashish1995"
},
{
"code": null,
"e": 8073,
"s": 8057,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8084,
"s": 8073,
"text": "maths-mean"
},
{
"code": null,
"e": 8108,
"s": 8084,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8120,
"s": 8108,
"text": "Linked List"
},
{
"code": null,
"e": 8139,
"s": 8120,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8151,
"s": 8139,
"text": "Linked List"
},
{
"code": null,
"e": 8249,
"s": 8151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8281,
"s": 8249,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8345,
"s": 8281,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8366,
"s": 8345,
"text": "Types of Linked List"
},
{
"code": null,
"e": 8406,
"s": 8366,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 8447,
"s": 8406,
"text": "Find first node of loop in a linked list"
},
{
"code": null,
"e": 8499,
"s": 8447,
"text": "Add two numbers represented by linked lists | Set 2"
},
{
"code": null,
"e": 8524,
"s": 8499,
"text": "Flattening a Linked List"
},
{
"code": null,
"e": 8565,
"s": 8524,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 8619,
"s": 8565,
"text": "Insert a node at a specific position in a linked list"
}
] |
Python PIL | putpixel() method
|
19 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The PixelAccess class provides read and write access to PIL.Image data at a pixel level.Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.
putpixel() Modifies the pixel at x, y. The color is given as a single numerical value for single band images, and a tuple for multi-band images
Syntax: putpixel(self, xy, color)
Parameters:
xy :The pixel coordinate, given as (x, y)value: – The pixel value.
Returns: An Image with pixel .
Image Used:
# Importing Image from PIL package from PIL import Image # creating a image objectimage = Image.open(r'C:\Users\System-Pc\Desktop\python.png') width, height = image.size for x in range(height): image.putpixel( (x, x), (0, 0, 0, 255) ) image.show()
Output:
Another example:Here we change the color parameter.Image Used
# Importing Image from PIL package from PIL import Image # creating a image objectimage = Image.open(r'C:\Users\System-Pc\Desktop\ybear.jpg') width, height = image.size for x in range(height): image.putpixel( (x, x), (10, 10, 10, 255) ) image.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 386,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The PixelAccess class provides read and write access to PIL.Image data at a pixel level.Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API."
},
{
"code": null,
"e": 530,
"s": 386,
"text": "putpixel() Modifies the pixel at x, y. The color is given as a single numerical value for single band images, and a tuple for multi-band images"
},
{
"code": null,
"e": 564,
"s": 530,
"text": "Syntax: putpixel(self, xy, color)"
},
{
"code": null,
"e": 576,
"s": 564,
"text": "Parameters:"
},
{
"code": null,
"e": 643,
"s": 576,
"text": "xy :The pixel coordinate, given as (x, y)value: – The pixel value."
},
{
"code": null,
"e": 674,
"s": 643,
"text": "Returns: An Image with pixel ."
},
{
"code": null,
"e": 686,
"s": 674,
"text": "Image Used:"
},
{
"code": " # Importing Image from PIL package from PIL import Image # creating a image objectimage = Image.open(r'C:\\Users\\System-Pc\\Desktop\\python.png') width, height = image.size for x in range(height): image.putpixel( (x, x), (0, 0, 0, 255) ) image.show()",
"e": 949,
"s": 686,
"text": null
},
{
"code": null,
"e": 957,
"s": 949,
"text": "Output:"
},
{
"code": null,
"e": 1019,
"s": 957,
"text": "Another example:Here we change the color parameter.Image Used"
},
{
"code": "# Importing Image from PIL package from PIL import Image # creating a image objectimage = Image.open(r'C:\\Users\\System-Pc\\Desktop\\ybear.jpg') width, height = image.size for x in range(height): image.putpixel( (x, x), (10, 10, 10, 255) ) image.show()",
"e": 1281,
"s": 1019,
"text": null
},
{
"code": null,
"e": 1289,
"s": 1281,
"text": "Output:"
},
{
"code": null,
"e": 1300,
"s": 1289,
"text": "Python-pil"
},
{
"code": null,
"e": 1307,
"s": 1300,
"text": "Python"
},
{
"code": null,
"e": 1405,
"s": 1307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1423,
"s": 1405,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1465,
"s": 1423,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1487,
"s": 1465,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1522,
"s": 1487,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1548,
"s": 1522,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1580,
"s": 1548,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1609,
"s": 1580,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1636,
"s": 1609,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1666,
"s": 1636,
"text": "Iterate over a list in Python"
}
] |
Comparing two strings in C++
|
23 Jun, 2022
Given two strings, how to check if the two strings are equal or not. Examples:
Input : ABCD, XYZ
Output : ABCD is not equal to XYZ
XYZ is greater than ABCD
Input : Geeks, forGeeks
Output : Geeks is not equal to forGeeks
forGeeks is greater than Geeks
This problem can be solved using any of the following two methods
C++ Relational operators
CPP
// CPP code to implement relational// operators on string objects#include <iostream>using namespace std; void relationalOperation(string s1, string s2){ if (s1 != s2) { cout << s1 << " is not equal to " << s2 << endl; if (s1 > s2) cout << s1 << " is greater than " << s2 << endl; else cout << s2 << " is greater than " << s1 << endl; } else cout << s1 << " is equal to " << s2 << endl;} // Driver codeint main(){ string s1("Geeks"); string s2("forGeeks"); relationalOperation(s1, s2); string s3("Geeks"); string s4("Geeks"); relationalOperation(s3, s4); return 0;}
Geeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
std:: Compare()
CPP
// CPP code perform relational// operation using compare function#include <iostream> using namespace std; void compareFunction(string s1, string s2){ // comparing both using inbuilt function int x = s1.compare(s2); if (x != 0) { cout << s1 << " is not equal to " << s2 << endl; if (x > 0) cout << s1 << " is greater than " << s2 << endl; else cout << s2 << " is greater than " << s1 << endl; } else cout << s1 << " is equal to " << s2 << endl;} // Driver Codeint main(){ string s1("Geeks"); string s2("forGeeks"); compareFunction(s1, s2); string s3("Geeks"); string s4("Geeks"); compareFunction(s3, s4); return 0;}
Geeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
Differences between C++ Relational operators and compare() :-
compare() returns an int, while relational operators return boolean value i.e. either true or false.A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed.We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators.
compare() returns an int, while relational operators return boolean value i.e. either true or false.
A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed.
We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators.
Example:-
Using compare()
// Compare 3 characters from 3rd position
// (or index 2) of str1 with 3 characters
// from 4th position of str2.
if (str1.compare(2, 3, str2, 3, 3) == 0)
cout<<"Equal";
else
cout<<"Not equal";
Using Relational operator
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)
{
if (s1[i] != s2[j])
break;
}
if (i == 6 && j == 7)
cout << "Equal";
else
cout << "Not equal";
The above example clearly shows how compare() reduces lots of extra processing, therefore it is advisable to use it while performing substring comparison at some position, otherwise both perform almost in the same manner.
DeepjyotSinghKapoor
kvivek2001
anandkumarshivam2266
cpp-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
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
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Convert string to char array in C++
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
What is Data Structure: Types, Classifications and Applications
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 133,
"s": 53,
"text": "Given two strings, how to check if the two strings are equal or not. Examples: "
},
{
"code": null,
"e": 326,
"s": 133,
"text": "Input : ABCD, XYZ\nOutput : ABCD is not equal to XYZ\n XYZ is greater than ABCD\n\nInput : Geeks, forGeeks\nOutput : Geeks is not equal to forGeeks\n forGeeks is greater than Geeks"
},
{
"code": null,
"e": 394,
"s": 326,
"text": "This problem can be solved using any of the following two methods "
},
{
"code": null,
"e": 419,
"s": 394,
"text": "C++ Relational operators"
},
{
"code": null,
"e": 423,
"s": 419,
"text": "CPP"
},
{
"code": "// CPP code to implement relational// operators on string objects#include <iostream>using namespace std; void relationalOperation(string s1, string s2){ if (s1 != s2) { cout << s1 << \" is not equal to \" << s2 << endl; if (s1 > s2) cout << s1 << \" is greater than \" << s2 << endl; else cout << s2 << \" is greater than \" << s1 << endl; } else cout << s1 << \" is equal to \" << s2 << endl;} // Driver codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); relationalOperation(s1, s2); string s3(\"Geeks\"); string s4(\"Geeks\"); relationalOperation(s3, s4); return 0;}",
"e": 1072,
"s": 423,
"text": null
},
{
"code": null,
"e": 1158,
"s": 1072,
"text": "Geeks is not equal to forGeeks\nforGeeks is greater than Geeks\nGeeks is equal to Geeks"
},
{
"code": null,
"e": 1232,
"s": 1158,
"text": "Time Complexity: O(min(n,m)) where n and m are the length of the strings."
},
{
"code": null,
"e": 1307,
"s": 1232,
"text": "Auxiliary Space: O(max(n,m)) where n and m are the length of the strings."
},
{
"code": null,
"e": 1399,
"s": 1307,
"text": "This is because when string is passed in the function it creates a copy of itself in stack."
},
{
"code": null,
"e": 1415,
"s": 1399,
"text": "std:: Compare()"
},
{
"code": null,
"e": 1419,
"s": 1415,
"text": "CPP"
},
{
"code": "// CPP code perform relational// operation using compare function#include <iostream> using namespace std; void compareFunction(string s1, string s2){ // comparing both using inbuilt function int x = s1.compare(s2); if (x != 0) { cout << s1 << \" is not equal to \" << s2 << endl; if (x > 0) cout << s1 << \" is greater than \" << s2 << endl; else cout << s2 << \" is greater than \" << s1 << endl; } else cout << s1 << \" is equal to \" << s2 << endl;} // Driver Codeint main(){ string s1(\"Geeks\"); string s2(\"forGeeks\"); compareFunction(s1, s2); string s3(\"Geeks\"); string s4(\"Geeks\"); compareFunction(s3, s4); return 0;}",
"e": 2209,
"s": 1419,
"text": null
},
{
"code": null,
"e": 2295,
"s": 2209,
"text": "Geeks is not equal to forGeeks\nforGeeks is greater than Geeks\nGeeks is equal to Geeks"
},
{
"code": null,
"e": 2369,
"s": 2295,
"text": "Time Complexity: O(min(n,m)) where n and m are the length of the strings."
},
{
"code": null,
"e": 2444,
"s": 2369,
"text": "Auxiliary Space: O(max(n,m)) where n and m are the length of the strings."
},
{
"code": null,
"e": 2536,
"s": 2444,
"text": "This is because when string is passed in the function it creates a copy of itself in stack."
},
{
"code": null,
"e": 2600,
"s": 2536,
"text": "Differences between C++ Relational operators and compare() :- "
},
{
"code": null,
"e": 3069,
"s": 2600,
"text": "compare() returns an int, while relational operators return boolean value i.e. either true or false.A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed.We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators."
},
{
"code": null,
"e": 3170,
"s": 3069,
"text": "compare() returns an int, while relational operators return boolean value i.e. either true or false."
},
{
"code": null,
"e": 3336,
"s": 3170,
"text": "A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed."
},
{
"code": null,
"e": 3540,
"s": 3336,
"text": "We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators."
},
{
"code": null,
"e": 3551,
"s": 3540,
"text": "Example:- "
},
{
"code": null,
"e": 3567,
"s": 3551,
"text": "Using compare()"
},
{
"code": null,
"e": 3769,
"s": 3567,
"text": "// Compare 3 characters from 3rd position\n// (or index 2) of str1 with 3 characters \n// from 4th position of str2. \nif (str1.compare(2, 3, str2, 3, 3) == 0)\n cout<<\"Equal\";\nelse\n cout<<\"Not equal\";"
},
{
"code": null,
"e": 3795,
"s": 3769,
"text": "Using Relational operator"
},
{
"code": null,
"e": 3962,
"s": 3795,
"text": "for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++) \n{ \n if (s1[i] != s2[j])\n break;\n}\nif (i == 6 && j == 7)\n cout << \"Equal\";\nelse\n cout << \"Not equal\";"
},
{
"code": null,
"e": 4184,
"s": 3962,
"text": "The above example clearly shows how compare() reduces lots of extra processing, therefore it is advisable to use it while performing substring comparison at some position, otherwise both perform almost in the same manner."
},
{
"code": null,
"e": 4204,
"s": 4184,
"text": "DeepjyotSinghKapoor"
},
{
"code": null,
"e": 4215,
"s": 4204,
"text": "kvivek2001"
},
{
"code": null,
"e": 4236,
"s": 4215,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 4247,
"s": 4236,
"text": "cpp-string"
},
{
"code": null,
"e": 4255,
"s": 4247,
"text": "Strings"
},
{
"code": null,
"e": 4263,
"s": 4255,
"text": "Strings"
},
{
"code": null,
"e": 4361,
"s": 4263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4406,
"s": 4361,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4481,
"s": 4406,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 4538,
"s": 4481,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 4574,
"s": 4538,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 4612,
"s": 4574,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 4673,
"s": 4612,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 4709,
"s": 4673,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 4754,
"s": 4709,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 4806,
"s": 4754,
"text": "Check whether two strings are anagram of each other"
}
] |
The Ultimate Guide to Data Cleaning | by Omar Elgabry | Towards Data Science
|
I spent the last couple of months analyzing data from sensors, surveys, and logs. No matter how many charts I created, how well sophisticated the algorithms are, the results are always misleading.
Throwing a random forest at the data is the same as injecting it with a virus. A virus that has no intention other than hurting your insights as if your data is spewing garbage.
Even worse, when you show your new findings to the CEO, and Oops guess what? He/she found a flaw, something that doesn’t smell right, your discoveries don’t match their understanding about the domain — After all, they are domain experts who know better than you, you as an analyst or a developer.
Right away, the blood rushed into your face, your hands are shaken, a moment of silence, followed by, probably, an apology.
That’s not bad at all. What if your findings were taken as a guarantee, and your company ended up making a decision based on them?.
You ingested a bunch of dirty data, didn’t clean it up, and you told your company to do something with these results that turn out to be wrong. You’re going to be in a lot of trouble!.
Incorrect or inconsistent data leads to false conclusions. And so, how well you clean and understand the data has a high impact on the quality of the results.
Two real examples were given on Wikipedia.
For instance, the government may want to analyze population census figures to decide which regions require further spending and investment on infrastructure and services. In this case, it will be important to have access to reliable data to avoid erroneous fiscal decisions.
In the business world, incorrect data can be costly. Many companies use customer information databases that record data like contact information, addresses, and preferences. For instance, if the addresses are inconsistent, the company will suffer the cost of resending mail or even losing customers.
Garbage in, garbage out.
In fact, a simple algorithm can outweigh a complex one just because it was given enough and high-quality data.
Quality data beats fancy algorithms.
For these reasons, it was important to have a step-by-step guideline, a cheat sheet, that walks through the quality checks to be applied.
But first, what’s the thing we are trying to achieve?. What does it mean quality data?. What are the measures of quality data?. Understanding what are you trying to accomplish, your ultimate goal is critical prior to taking any actions.
Data Quality (validity, accuracy, completeness, consistency, uniformity)
The workflow (inspection, cleaning, verifying, reporting)
Inspection (data profiling, visualizations, software packages)
Cleaning (irrelevant data, duplicates, type conver., syntax errors, 6 more)
Verifying
Reporting
Final words
Frankly speaking, I couldn’t find a better explanation for the quality criteria other than the one on Wikipedia. So, I am going to summarize it here.
The degree to which the data conform to defined business rules or constraints.
Data-Type Constraints: values in a particular column must be of a particular datatype, e.g., boolean, numeric, date, etc.
Range Constraints: typically, numbers or dates should fall within a certain range.
Mandatory Constraints: certain columns cannot be empty.
Unique Constraints: a field, or a combination of fields, must be unique across a dataset.
Set-Membership constraints: values of a column come from a set of discrete values, e.g. enum values. For example, a person’s gender may be male or female.
Foreign-key constraints: as in relational databases, a foreign key column can’t have a value that does not exist in the referenced primary key.
Regular expression patterns: text fields that have to be in a certain pattern. For example, phone numbers may be required to have the pattern (999) 999–9999.
Cross-field validation: certain conditions that span across multiple fields must hold. For example, a patient’s date of discharge from the hospital cannot be earlier than the date of admission.
The degree to which the data is close to the true values.
While defining all possible valid values allows invalid values to be easily spotted, it does not mean that they are accurate.
A valid street address mightn’t actually exist. A valid person’s eye colour, say blue, might be valid, but not true (doesn’t represent the reality).
Another thing to note is the difference between accuracy and precision. Saying that you live on the earth is, actually true. But, not precise. Where on the earth?. Saying that you live at a particular street address is more precise.
The degree to which all required data is known.
Missing data is going to happen for various reasons. One can mitigate this problem by questioning the original source if possible, say re-interviewing the subject.
Chances are, the subject is either going to give a different answer or will be hard to reach again.
The degree to which the data is consistent, within the same data set or across multiple data sets.
Inconsistency occurs when two values in the data set contradict each other.
A valid age, say 10, mightn’t match with the marital status, say divorced. A customer is recorded in two different tables with two different addresses.
Which one is true?.
The degree to which the data is specified using the same unit of measure.
The weight may be recorded either in pounds or kilos. The date might follow the USA format or European format. The currency is sometimes in USD and sometimes in YEN.
And so data must be converted to a single measure unit.
The workflow is a sequence of three steps aiming at producing high-quality data and taking into account all the criteria we’ve talked about.
Inspection: Detect unexpected, incorrect, and inconsistent data.Cleaning: Fix or remove the anomalies discovered.Verifying: After cleaning, the results are inspected to verify correctness.Reporting: A report about the changes made and the quality of the currently stored data is recorded.
Inspection: Detect unexpected, incorrect, and inconsistent data.
Cleaning: Fix or remove the anomalies discovered.
Verifying: After cleaning, the results are inspected to verify correctness.
Reporting: A report about the changes made and the quality of the currently stored data is recorded.
What you see as a sequential process is, in fact, an iterative, endless process. One can go from verifying to inspection when new flaws are detected.
Inspecting the data is time-consuming and requires using many methods for exploring the underlying data for error detection. Here are some of them:
A summary statistics about the data, called data profiling, is really helpful to give a general idea about the quality of the data.
For example, check whether a particular column conforms to particular standards or pattern. Is the data column recorded as a string or number?.
How many values are missing?. How many unique values in a column, and their distribution?. Is this data set is linked to or have a relationship with another?.
By analyzing and visualizing the data using statistical methods such as mean, standard deviation, range, or quantiles, one can find values that are unexpected and thus erroneous.
For example, by visualizing the average income across the countries, one might see there are some outliers (link has an image). Some countries have people who earn much more than anyone else. Those outliers are worth investigating and are not necessarily incorrect data.
Several software packages or libraries available at your language will let you specify constraints and check the data for violation of these constraints.
Moreover, they can not only generate a report of which rules were violated and how many times but also create a graph of which columns are associated with which rules.
The age, for example, can’t be negative, and so the height. Other rules may involve multiple columns in the same row, or across datasets.
Data cleaning involve different techniques based on the problem and the data type. Different methods can be applied with each has its own trade-offs.
Overall, incorrect data is either removed, corrected, or imputed.
Irrelevant data are those that are not actually needed, and don’t fit under the context of the problem we’re trying to solve.
For example, if we were analyzing data about the general health of the population, the phone number wouldn’t be necessary — column-wise.
Similarly, if you were interested in only one particular country, you wouldn’t want to include all other countries. Or, study only those patients who went to the surgery, we wouldn’t include everyone — row-wise.
Only if you are sure that a piece of data is unimportant, you may drop it. Otherwise, explore the correlation matrix between feature variables.
And even though you noticed no correlation, you should ask someone who is domain expert. You never know, a feature that seems irrelevant, could be very relevant from a domain perspective such as a clinical perspective.
Duplicates are data points that are repeated in your dataset.
It often happens when for example
Data are combined from different sources
The user may hit submit button twice thinking the form wasn’t actually submitted.
A request to online booking was submitted twice correcting wrong information that was entered accidentally in the first time.
A common symptom is when two users have the same identity number. Or, the same article was scrapped twice.
And therefore, they simply should be removed.
Make sure numbers are stored as numerical data types. A date should be stored as a date object, or a Unix timestamp (number of seconds), and so on.
Categorical values can be converted into and from numbers if needed.
This is can be spotted quickly by taking a peek over the data types of each column in the summary (we’ve discussed above).
A word of caution is that the values that can’t be converted to the specified type should be converted to NA value (or any), with a warning being displayed. This indicates the value is incorrect and must be fixed.
Remove white spaces: Extra white spaces at the beginning or the end of a string should be removed.
" hello world " => "hello world
Pad strings: Strings can be padded with spaces or other characters to a certain width. For example, some numerical codes are often represented with prepending zeros to ensure they always have the same number of digits.
313 => 000313 (6 digits)
Fix typos: Strings can be entered in many different ways, and no wonder, can have mistakes.
GendermMalefem.FemalEFemle
This categorical variable is considered to have 5 different classes, and not 2 as expected: male and female since each value is different.
A bar plot is useful to visualize all the unique values. One can notice some values are different but do mean the same thing i.e. “information_technology” and “IT”. Or, perhaps, the difference is just in the capitalization i.e. “other” and “Other”.
Therefore, our duty is to recognize from the above data whether each value is male or female. How can we do that?.
The first solution is to manually map each value to either “male” or “female”.
dataframe['gender'].map({'m': 'male', fem.': 'female', ...})
The second solution is to use pattern match. For example, we can look for the occurrence of m or M in the gender at the beginning of the string.
re.sub(r"\^m\$", 'Male', 'male', flags=re.IGNORECASE)
The third solution is to use fuzzy matching: An algorithm that identifies the distance between the expected string(s) and each of the given one. Its basic implementation counts how many operations are needed to turn one string into another.
Gender male femalem 3 5Male 1 3fem. 5 3FemalE 3 2Femle 3 1
Furthermore, if you have a variable like a city name, where you suspect typos or similar strings should be treated the same. For example, “lisbon” can be entered as “lisboa”, “lisbona”, “Lisbon”, etc.
City Distance from "lisbon"lisbon 0lisboa 1Lisbon 1lisbona 2london 3...
If so, then we should replace all values that mean the same thing to one unique value. In this case, replace the first 4 strings with “lisbon”.
Watch out for values like “0”, “Not Applicable”, “NA”, “None”, “Null”, or “INF”, they might mean the same thing: The value is missing.
Our duty is to not only recognize the typos but also put each value in the same standardized format.
For strings, make sure all values are either in lower or upper case.
For numerical values, make sure all values have a certain measurement unit.
The hight, for example, can be in meters and centimetres. The difference of 1 meter is considered the same as the difference of 1 centimetre. So, the task here is to convert the heights to one single unit.
For dates, the USA version is not the same as the European version. Recording the date as a timestamp (a number of milliseconds) is not the same as recording the date as a date object.
Scaling means to transform your data so that it fits within a specific scale, such as 0–100 or 0–1.
For example, exam scores of a student can be re-scaled to be percentages (0–100) instead of GPA (0–5).
It can also help in making certain types of data easier to plot. For example, we might want to reduce skewness to assist in plotting (when having such many outliers). The most commonly used functions are log, square root, and inverse.
Scaling can also take place on data that has different measurement units.
Student scores on different exams say, SAT and ACT, can’t be compared since these two exams are on a different scale. The difference of 1 SAT score is considered the same as the difference of 1 ACT score. In this case, we need re-scale SAT and ACT scores to take numbers, say, between 0–1.
By scaling, we can plot and compare different scores.
While normalization also rescales the values into a range of 0–1, the intention here is to transform the data so that it is normally distributed. Why?
In most cases, we normalize the data if we’re going to be using statistical methods that rely on normally distributed data. How?
One can use the log function, or perhaps, use one of these methods.
Depending on the scaling method used, the shape of the data distribution might change. For example, the “Standard Z score” and “Student’s t-statistic” (given in the link above) preserve the shape, while the log function mighn’t.
Given the fact the missing values are unavoidable leaves us with the question of what to do when we encounter them. Ignoring the missing data is the same as digging holes in a boat; It will sink.
There are three, or perhaps more, ways to deal with them.
If the missing values in a column rarely happen and occur at random, then the easiest and most forward solution is to drop observations (rows) that have missing values.
If most of the column’s values are missing, and occur at random, then a typical decision is to drop the whole column.
This is particularly useful when doing statistical analysis, since filling in the missing values may yield unexpected or biased results.
It means to calculate the missing value based on other observations. There are quite a lot of methods to do that.
— First one is using statistical values like mean, median. However, none of these guarantees unbiased data, especially if there are many missing values.
Mean is most useful when the original data is not skewed, while the median is more robust, not sensitive to outliers, and thus used when data is skewed.
In a normally distributed data, one can get all the values that are within 2 standard deviations from the mean. Next, fill in the missing values by generating random numbers between (mean — 2 * std) & (mean + 2 * std)
rand = np.random.randint(average_age - 2*std_age, average_age + 2*std_age, size = count_nan_age)dataframe["age"][np.isnan(dataframe["age"])] = rand
— Second. Using a linear regression. Based on the existing data, one can calculate the best fit line between two variables, say, house price vs. size m2.
It is worth mentioning that linear regression models are sensitive to outliers.
— Third. Hot-deck: Copying values from other similar records. This is only useful if you have enough available data. And, it can be applied to numerical and categorical data.
One can take the random approach where we fill in the missing value with a random value. Taking this approach one step further, one can first divide the dataset into two groups (strata), based on some characteristic, say gender, and then fill in the missing values for different genders separately, at random.
In sequential hot-deck imputation, the column containing missing values is sorted according to auxiliary variable(s) so that records that have similar auxiliaries occur sequentially. Next, each missing value is filled in with the value of the first following available record.
What is more interesting is that k nearest neighbour imputation, which classifies similar records and put them together, can also be utilized. A missing value is then filled out by finding first the k records closest to the record with missing values. Next, a value is chosen from (or computed out of) the k nearest neighbours. In the case of computing, statistical methods like mean (as discussed before) can be used.
Some argue that filling in the missing values leads to a loss in information, no matter what imputation method we used.
That’s because saying that the data is missing is informative in itself, and the algorithm should know about it. Otherwise, we’re just reinforcing the pattern already exist by other features.
This is particularly important when the missing data doesn’t happen at random. Take for example a conducted survey where most people from a specific race refuse to answer a certain question.
Missing numeric data can be filled in with say, 0, but has these zeros must be ignored when calculating any statistical value or plotting the distribution.
While categorical data can be filled in with say, “Missing”: A new category which tells that this piece of data is missing.
Missing values are not the same as default values. For instance, zero can be interpreted as either missing or default, but not both.
Missing values are not “unknown”. A conducted research where some people didn’t remember whether they have been bullied or not at the school, should be treated and labelled as unknown and not missing.
Every time we drop or impute values we are losing information. So, flagging might come to the rescue.
They are values that are significantly different from all other observations. Any data value that lies more than (1.5 * IQR) away from the Q1 and Q3 quartiles is considered an outlier.
Outliers are innocent until proven guilty. With that being said, they should not be removed unless there is a good reason for that.
For example, one can notice some weird, suspicious values that are unlikely to happen, and so decides to remove them. Though, they worth investigating before removing.
It is also worth mentioning that some models, like linear regression, are very sensitive to outliers. In other words, outliers might throw the model off from where most of the data lie.
These errors result from having two or more values in the same row or across datasets that contradict with each other.
For example, if we have a dataset about the cost of living in cities. The total column must be equivalent to the sum of rent, transport, and food.
city rent transportation food totallibson 500 20 40 560paris 750 40 60 850
Similarly, a child can’t be married. An employee’s salary can’t be less than the calculated taxes.
The same idea applies to related data across different datasets.
When done, one should verify correctness by re-inspecting the data and making sure it rules and constraints do hold.
For example, after filling out the missing data, they might violate any of the rules and constraints.
It might involve some manual correction if not possible otherwise.
Reporting how healthy the data is, is equally important to cleaning.
As mentioned before, software packages or libraries can generate reports of the changes made, which rules were violated, and how many times.
In addition to logging the violations, the causes of these errors should be considered. Why did they happen in the first place?.
If you made it that far, I am happy you were able to hold until the end. But, None of what mentioned is valuable without embracing the quality culture.
No matter how robust and strong the validation and cleaning process is, one will continue to suffer as new data come in.
It is better to guard yourself against a disease instead of spending the time and effort to remedy it.
These questions help to evaluate and improve the data quality:
How the data is collected, and under what conditions?. The environment where the data was collected does matter. The environment includes, but not limited to, the location, timing, weather conditions, etc.
Questioning subjects about their opinion regarding whatever while they are on their way to work is not the same as while they are at home. Patients under a study who have difficulties using the tablets to answer a questionnaire might throw off the results.
What does the data represent?. Does it include everyone? Only the people in the city?. Or, perhaps, only those who opted to answer because they had a strong opinion about the topic.
What are the methods used to clean the data and why?. Different methods can be better in different situations or with different data types.
Do you invest the time and money in improving the process?. Investing in people and the process is as critical as investing in the technology.
And finally, ... it doesn’t go without saying,
Thank you for reading!
Feel free to reach on LinkedIn or Medium.
|
[
{
"code": null,
"e": 369,
"s": 172,
"text": "I spent the last couple of months analyzing data from sensors, surveys, and logs. No matter how many charts I created, how well sophisticated the algorithms are, the results are always misleading."
},
{
"code": null,
"e": 547,
"s": 369,
"text": "Throwing a random forest at the data is the same as injecting it with a virus. A virus that has no intention other than hurting your insights as if your data is spewing garbage."
},
{
"code": null,
"e": 844,
"s": 547,
"text": "Even worse, when you show your new findings to the CEO, and Oops guess what? He/she found a flaw, something that doesn’t smell right, your discoveries don’t match their understanding about the domain — After all, they are domain experts who know better than you, you as an analyst or a developer."
},
{
"code": null,
"e": 968,
"s": 844,
"text": "Right away, the blood rushed into your face, your hands are shaken, a moment of silence, followed by, probably, an apology."
},
{
"code": null,
"e": 1100,
"s": 968,
"text": "That’s not bad at all. What if your findings were taken as a guarantee, and your company ended up making a decision based on them?."
},
{
"code": null,
"e": 1285,
"s": 1100,
"text": "You ingested a bunch of dirty data, didn’t clean it up, and you told your company to do something with these results that turn out to be wrong. You’re going to be in a lot of trouble!."
},
{
"code": null,
"e": 1444,
"s": 1285,
"text": "Incorrect or inconsistent data leads to false conclusions. And so, how well you clean and understand the data has a high impact on the quality of the results."
},
{
"code": null,
"e": 1487,
"s": 1444,
"text": "Two real examples were given on Wikipedia."
},
{
"code": null,
"e": 1762,
"s": 1487,
"text": "For instance, the government may want to analyze population census figures to decide which regions require further spending and investment on infrastructure and services. In this case, it will be important to have access to reliable data to avoid erroneous fiscal decisions."
},
{
"code": null,
"e": 2062,
"s": 1762,
"text": "In the business world, incorrect data can be costly. Many companies use customer information databases that record data like contact information, addresses, and preferences. For instance, if the addresses are inconsistent, the company will suffer the cost of resending mail or even losing customers."
},
{
"code": null,
"e": 2087,
"s": 2062,
"text": "Garbage in, garbage out."
},
{
"code": null,
"e": 2198,
"s": 2087,
"text": "In fact, a simple algorithm can outweigh a complex one just because it was given enough and high-quality data."
},
{
"code": null,
"e": 2235,
"s": 2198,
"text": "Quality data beats fancy algorithms."
},
{
"code": null,
"e": 2373,
"s": 2235,
"text": "For these reasons, it was important to have a step-by-step guideline, a cheat sheet, that walks through the quality checks to be applied."
},
{
"code": null,
"e": 2610,
"s": 2373,
"text": "But first, what’s the thing we are trying to achieve?. What does it mean quality data?. What are the measures of quality data?. Understanding what are you trying to accomplish, your ultimate goal is critical prior to taking any actions."
},
{
"code": null,
"e": 2683,
"s": 2610,
"text": "Data Quality (validity, accuracy, completeness, consistency, uniformity)"
},
{
"code": null,
"e": 2741,
"s": 2683,
"text": "The workflow (inspection, cleaning, verifying, reporting)"
},
{
"code": null,
"e": 2804,
"s": 2741,
"text": "Inspection (data profiling, visualizations, software packages)"
},
{
"code": null,
"e": 2880,
"s": 2804,
"text": "Cleaning (irrelevant data, duplicates, type conver., syntax errors, 6 more)"
},
{
"code": null,
"e": 2890,
"s": 2880,
"text": "Verifying"
},
{
"code": null,
"e": 2900,
"s": 2890,
"text": "Reporting"
},
{
"code": null,
"e": 2912,
"s": 2900,
"text": "Final words"
},
{
"code": null,
"e": 3062,
"s": 2912,
"text": "Frankly speaking, I couldn’t find a better explanation for the quality criteria other than the one on Wikipedia. So, I am going to summarize it here."
},
{
"code": null,
"e": 3141,
"s": 3062,
"text": "The degree to which the data conform to defined business rules or constraints."
},
{
"code": null,
"e": 3263,
"s": 3141,
"text": "Data-Type Constraints: values in a particular column must be of a particular datatype, e.g., boolean, numeric, date, etc."
},
{
"code": null,
"e": 3346,
"s": 3263,
"text": "Range Constraints: typically, numbers or dates should fall within a certain range."
},
{
"code": null,
"e": 3402,
"s": 3346,
"text": "Mandatory Constraints: certain columns cannot be empty."
},
{
"code": null,
"e": 3492,
"s": 3402,
"text": "Unique Constraints: a field, or a combination of fields, must be unique across a dataset."
},
{
"code": null,
"e": 3647,
"s": 3492,
"text": "Set-Membership constraints: values of a column come from a set of discrete values, e.g. enum values. For example, a person’s gender may be male or female."
},
{
"code": null,
"e": 3791,
"s": 3647,
"text": "Foreign-key constraints: as in relational databases, a foreign key column can’t have a value that does not exist in the referenced primary key."
},
{
"code": null,
"e": 3949,
"s": 3791,
"text": "Regular expression patterns: text fields that have to be in a certain pattern. For example, phone numbers may be required to have the pattern (999) 999–9999."
},
{
"code": null,
"e": 4143,
"s": 3949,
"text": "Cross-field validation: certain conditions that span across multiple fields must hold. For example, a patient’s date of discharge from the hospital cannot be earlier than the date of admission."
},
{
"code": null,
"e": 4201,
"s": 4143,
"text": "The degree to which the data is close to the true values."
},
{
"code": null,
"e": 4327,
"s": 4201,
"text": "While defining all possible valid values allows invalid values to be easily spotted, it does not mean that they are accurate."
},
{
"code": null,
"e": 4476,
"s": 4327,
"text": "A valid street address mightn’t actually exist. A valid person’s eye colour, say blue, might be valid, but not true (doesn’t represent the reality)."
},
{
"code": null,
"e": 4709,
"s": 4476,
"text": "Another thing to note is the difference between accuracy and precision. Saying that you live on the earth is, actually true. But, not precise. Where on the earth?. Saying that you live at a particular street address is more precise."
},
{
"code": null,
"e": 4757,
"s": 4709,
"text": "The degree to which all required data is known."
},
{
"code": null,
"e": 4921,
"s": 4757,
"text": "Missing data is going to happen for various reasons. One can mitigate this problem by questioning the original source if possible, say re-interviewing the subject."
},
{
"code": null,
"e": 5021,
"s": 4921,
"text": "Chances are, the subject is either going to give a different answer or will be hard to reach again."
},
{
"code": null,
"e": 5120,
"s": 5021,
"text": "The degree to which the data is consistent, within the same data set or across multiple data sets."
},
{
"code": null,
"e": 5196,
"s": 5120,
"text": "Inconsistency occurs when two values in the data set contradict each other."
},
{
"code": null,
"e": 5348,
"s": 5196,
"text": "A valid age, say 10, mightn’t match with the marital status, say divorced. A customer is recorded in two different tables with two different addresses."
},
{
"code": null,
"e": 5368,
"s": 5348,
"text": "Which one is true?."
},
{
"code": null,
"e": 5442,
"s": 5368,
"text": "The degree to which the data is specified using the same unit of measure."
},
{
"code": null,
"e": 5608,
"s": 5442,
"text": "The weight may be recorded either in pounds or kilos. The date might follow the USA format or European format. The currency is sometimes in USD and sometimes in YEN."
},
{
"code": null,
"e": 5664,
"s": 5608,
"text": "And so data must be converted to a single measure unit."
},
{
"code": null,
"e": 5805,
"s": 5664,
"text": "The workflow is a sequence of three steps aiming at producing high-quality data and taking into account all the criteria we’ve talked about."
},
{
"code": null,
"e": 6094,
"s": 5805,
"text": "Inspection: Detect unexpected, incorrect, and inconsistent data.Cleaning: Fix or remove the anomalies discovered.Verifying: After cleaning, the results are inspected to verify correctness.Reporting: A report about the changes made and the quality of the currently stored data is recorded."
},
{
"code": null,
"e": 6159,
"s": 6094,
"text": "Inspection: Detect unexpected, incorrect, and inconsistent data."
},
{
"code": null,
"e": 6209,
"s": 6159,
"text": "Cleaning: Fix or remove the anomalies discovered."
},
{
"code": null,
"e": 6285,
"s": 6209,
"text": "Verifying: After cleaning, the results are inspected to verify correctness."
},
{
"code": null,
"e": 6386,
"s": 6285,
"text": "Reporting: A report about the changes made and the quality of the currently stored data is recorded."
},
{
"code": null,
"e": 6536,
"s": 6386,
"text": "What you see as a sequential process is, in fact, an iterative, endless process. One can go from verifying to inspection when new flaws are detected."
},
{
"code": null,
"e": 6684,
"s": 6536,
"text": "Inspecting the data is time-consuming and requires using many methods for exploring the underlying data for error detection. Here are some of them:"
},
{
"code": null,
"e": 6816,
"s": 6684,
"text": "A summary statistics about the data, called data profiling, is really helpful to give a general idea about the quality of the data."
},
{
"code": null,
"e": 6960,
"s": 6816,
"text": "For example, check whether a particular column conforms to particular standards or pattern. Is the data column recorded as a string or number?."
},
{
"code": null,
"e": 7119,
"s": 6960,
"text": "How many values are missing?. How many unique values in a column, and their distribution?. Is this data set is linked to or have a relationship with another?."
},
{
"code": null,
"e": 7298,
"s": 7119,
"text": "By analyzing and visualizing the data using statistical methods such as mean, standard deviation, range, or quantiles, one can find values that are unexpected and thus erroneous."
},
{
"code": null,
"e": 7569,
"s": 7298,
"text": "For example, by visualizing the average income across the countries, one might see there are some outliers (link has an image). Some countries have people who earn much more than anyone else. Those outliers are worth investigating and are not necessarily incorrect data."
},
{
"code": null,
"e": 7723,
"s": 7569,
"text": "Several software packages or libraries available at your language will let you specify constraints and check the data for violation of these constraints."
},
{
"code": null,
"e": 7891,
"s": 7723,
"text": "Moreover, they can not only generate a report of which rules were violated and how many times but also create a graph of which columns are associated with which rules."
},
{
"code": null,
"e": 8029,
"s": 7891,
"text": "The age, for example, can’t be negative, and so the height. Other rules may involve multiple columns in the same row, or across datasets."
},
{
"code": null,
"e": 8179,
"s": 8029,
"text": "Data cleaning involve different techniques based on the problem and the data type. Different methods can be applied with each has its own trade-offs."
},
{
"code": null,
"e": 8245,
"s": 8179,
"text": "Overall, incorrect data is either removed, corrected, or imputed."
},
{
"code": null,
"e": 8371,
"s": 8245,
"text": "Irrelevant data are those that are not actually needed, and don’t fit under the context of the problem we’re trying to solve."
},
{
"code": null,
"e": 8508,
"s": 8371,
"text": "For example, if we were analyzing data about the general health of the population, the phone number wouldn’t be necessary — column-wise."
},
{
"code": null,
"e": 8720,
"s": 8508,
"text": "Similarly, if you were interested in only one particular country, you wouldn’t want to include all other countries. Or, study only those patients who went to the surgery, we wouldn’t include everyone — row-wise."
},
{
"code": null,
"e": 8864,
"s": 8720,
"text": "Only if you are sure that a piece of data is unimportant, you may drop it. Otherwise, explore the correlation matrix between feature variables."
},
{
"code": null,
"e": 9083,
"s": 8864,
"text": "And even though you noticed no correlation, you should ask someone who is domain expert. You never know, a feature that seems irrelevant, could be very relevant from a domain perspective such as a clinical perspective."
},
{
"code": null,
"e": 9145,
"s": 9083,
"text": "Duplicates are data points that are repeated in your dataset."
},
{
"code": null,
"e": 9179,
"s": 9145,
"text": "It often happens when for example"
},
{
"code": null,
"e": 9220,
"s": 9179,
"text": "Data are combined from different sources"
},
{
"code": null,
"e": 9302,
"s": 9220,
"text": "The user may hit submit button twice thinking the form wasn’t actually submitted."
},
{
"code": null,
"e": 9428,
"s": 9302,
"text": "A request to online booking was submitted twice correcting wrong information that was entered accidentally in the first time."
},
{
"code": null,
"e": 9535,
"s": 9428,
"text": "A common symptom is when two users have the same identity number. Or, the same article was scrapped twice."
},
{
"code": null,
"e": 9581,
"s": 9535,
"text": "And therefore, they simply should be removed."
},
{
"code": null,
"e": 9729,
"s": 9581,
"text": "Make sure numbers are stored as numerical data types. A date should be stored as a date object, or a Unix timestamp (number of seconds), and so on."
},
{
"code": null,
"e": 9798,
"s": 9729,
"text": "Categorical values can be converted into and from numbers if needed."
},
{
"code": null,
"e": 9921,
"s": 9798,
"text": "This is can be spotted quickly by taking a peek over the data types of each column in the summary (we’ve discussed above)."
},
{
"code": null,
"e": 10135,
"s": 9921,
"text": "A word of caution is that the values that can’t be converted to the specified type should be converted to NA value (or any), with a warning being displayed. This indicates the value is incorrect and must be fixed."
},
{
"code": null,
"e": 10234,
"s": 10135,
"text": "Remove white spaces: Extra white spaces at the beginning or the end of a string should be removed."
},
{
"code": null,
"e": 10269,
"s": 10234,
"text": "\" hello world \" => \"hello world"
},
{
"code": null,
"e": 10488,
"s": 10269,
"text": "Pad strings: Strings can be padded with spaces or other characters to a certain width. For example, some numerical codes are often represented with prepending zeros to ensure they always have the same number of digits."
},
{
"code": null,
"e": 10513,
"s": 10488,
"text": "313 => 000313 (6 digits)"
},
{
"code": null,
"e": 10605,
"s": 10513,
"text": "Fix typos: Strings can be entered in many different ways, and no wonder, can have mistakes."
},
{
"code": null,
"e": 10632,
"s": 10605,
"text": "GendermMalefem.FemalEFemle"
},
{
"code": null,
"e": 10771,
"s": 10632,
"text": "This categorical variable is considered to have 5 different classes, and not 2 as expected: male and female since each value is different."
},
{
"code": null,
"e": 11020,
"s": 10771,
"text": "A bar plot is useful to visualize all the unique values. One can notice some values are different but do mean the same thing i.e. “information_technology” and “IT”. Or, perhaps, the difference is just in the capitalization i.e. “other” and “Other”."
},
{
"code": null,
"e": 11135,
"s": 11020,
"text": "Therefore, our duty is to recognize from the above data whether each value is male or female. How can we do that?."
},
{
"code": null,
"e": 11214,
"s": 11135,
"text": "The first solution is to manually map each value to either “male” or “female”."
},
{
"code": null,
"e": 11275,
"s": 11214,
"text": "dataframe['gender'].map({'m': 'male', fem.': 'female', ...})"
},
{
"code": null,
"e": 11420,
"s": 11275,
"text": "The second solution is to use pattern match. For example, we can look for the occurrence of m or M in the gender at the beginning of the string."
},
{
"code": null,
"e": 11474,
"s": 11420,
"text": "re.sub(r\"\\^m\\$\", 'Male', 'male', flags=re.IGNORECASE)"
},
{
"code": null,
"e": 11715,
"s": 11474,
"text": "The third solution is to use fuzzy matching: An algorithm that identifies the distance between the expected string(s) and each of the given one. Its basic implementation counts how many operations are needed to turn one string into another."
},
{
"code": null,
"e": 11827,
"s": 11715,
"text": "Gender male femalem 3 5Male 1 3fem. 5 3FemalE 3 2Femle 3 1"
},
{
"code": null,
"e": 12028,
"s": 11827,
"text": "Furthermore, if you have a variable like a city name, where you suspect typos or similar strings should be treated the same. For example, “lisbon” can be entered as “lisboa”, “lisbona”, “Lisbon”, etc."
},
{
"code": null,
"e": 12133,
"s": 12028,
"text": "City Distance from \"lisbon\"lisbon 0lisboa 1Lisbon 1lisbona 2london 3..."
},
{
"code": null,
"e": 12277,
"s": 12133,
"text": "If so, then we should replace all values that mean the same thing to one unique value. In this case, replace the first 4 strings with “lisbon”."
},
{
"code": null,
"e": 12412,
"s": 12277,
"text": "Watch out for values like “0”, “Not Applicable”, “NA”, “None”, “Null”, or “INF”, they might mean the same thing: The value is missing."
},
{
"code": null,
"e": 12513,
"s": 12412,
"text": "Our duty is to not only recognize the typos but also put each value in the same standardized format."
},
{
"code": null,
"e": 12582,
"s": 12513,
"text": "For strings, make sure all values are either in lower or upper case."
},
{
"code": null,
"e": 12658,
"s": 12582,
"text": "For numerical values, make sure all values have a certain measurement unit."
},
{
"code": null,
"e": 12864,
"s": 12658,
"text": "The hight, for example, can be in meters and centimetres. The difference of 1 meter is considered the same as the difference of 1 centimetre. So, the task here is to convert the heights to one single unit."
},
{
"code": null,
"e": 13049,
"s": 12864,
"text": "For dates, the USA version is not the same as the European version. Recording the date as a timestamp (a number of milliseconds) is not the same as recording the date as a date object."
},
{
"code": null,
"e": 13149,
"s": 13049,
"text": "Scaling means to transform your data so that it fits within a specific scale, such as 0–100 or 0–1."
},
{
"code": null,
"e": 13252,
"s": 13149,
"text": "For example, exam scores of a student can be re-scaled to be percentages (0–100) instead of GPA (0–5)."
},
{
"code": null,
"e": 13487,
"s": 13252,
"text": "It can also help in making certain types of data easier to plot. For example, we might want to reduce skewness to assist in plotting (when having such many outliers). The most commonly used functions are log, square root, and inverse."
},
{
"code": null,
"e": 13561,
"s": 13487,
"text": "Scaling can also take place on data that has different measurement units."
},
{
"code": null,
"e": 13851,
"s": 13561,
"text": "Student scores on different exams say, SAT and ACT, can’t be compared since these two exams are on a different scale. The difference of 1 SAT score is considered the same as the difference of 1 ACT score. In this case, we need re-scale SAT and ACT scores to take numbers, say, between 0–1."
},
{
"code": null,
"e": 13905,
"s": 13851,
"text": "By scaling, we can plot and compare different scores."
},
{
"code": null,
"e": 14056,
"s": 13905,
"text": "While normalization also rescales the values into a range of 0–1, the intention here is to transform the data so that it is normally distributed. Why?"
},
{
"code": null,
"e": 14185,
"s": 14056,
"text": "In most cases, we normalize the data if we’re going to be using statistical methods that rely on normally distributed data. How?"
},
{
"code": null,
"e": 14253,
"s": 14185,
"text": "One can use the log function, or perhaps, use one of these methods."
},
{
"code": null,
"e": 14482,
"s": 14253,
"text": "Depending on the scaling method used, the shape of the data distribution might change. For example, the “Standard Z score” and “Student’s t-statistic” (given in the link above) preserve the shape, while the log function mighn’t."
},
{
"code": null,
"e": 14678,
"s": 14482,
"text": "Given the fact the missing values are unavoidable leaves us with the question of what to do when we encounter them. Ignoring the missing data is the same as digging holes in a boat; It will sink."
},
{
"code": null,
"e": 14736,
"s": 14678,
"text": "There are three, or perhaps more, ways to deal with them."
},
{
"code": null,
"e": 14905,
"s": 14736,
"text": "If the missing values in a column rarely happen and occur at random, then the easiest and most forward solution is to drop observations (rows) that have missing values."
},
{
"code": null,
"e": 15023,
"s": 14905,
"text": "If most of the column’s values are missing, and occur at random, then a typical decision is to drop the whole column."
},
{
"code": null,
"e": 15160,
"s": 15023,
"text": "This is particularly useful when doing statistical analysis, since filling in the missing values may yield unexpected or biased results."
},
{
"code": null,
"e": 15274,
"s": 15160,
"text": "It means to calculate the missing value based on other observations. There are quite a lot of methods to do that."
},
{
"code": null,
"e": 15427,
"s": 15274,
"text": "— First one is using statistical values like mean, median. However, none of these guarantees unbiased data, especially if there are many missing values."
},
{
"code": null,
"e": 15580,
"s": 15427,
"text": "Mean is most useful when the original data is not skewed, while the median is more robust, not sensitive to outliers, and thus used when data is skewed."
},
{
"code": null,
"e": 15798,
"s": 15580,
"text": "In a normally distributed data, one can get all the values that are within 2 standard deviations from the mean. Next, fill in the missing values by generating random numbers between (mean — 2 * std) & (mean + 2 * std)"
},
{
"code": null,
"e": 15946,
"s": 15798,
"text": "rand = np.random.randint(average_age - 2*std_age, average_age + 2*std_age, size = count_nan_age)dataframe[\"age\"][np.isnan(dataframe[\"age\"])] = rand"
},
{
"code": null,
"e": 16100,
"s": 15946,
"text": "— Second. Using a linear regression. Based on the existing data, one can calculate the best fit line between two variables, say, house price vs. size m2."
},
{
"code": null,
"e": 16180,
"s": 16100,
"text": "It is worth mentioning that linear regression models are sensitive to outliers."
},
{
"code": null,
"e": 16355,
"s": 16180,
"text": "— Third. Hot-deck: Copying values from other similar records. This is only useful if you have enough available data. And, it can be applied to numerical and categorical data."
},
{
"code": null,
"e": 16665,
"s": 16355,
"text": "One can take the random approach where we fill in the missing value with a random value. Taking this approach one step further, one can first divide the dataset into two groups (strata), based on some characteristic, say gender, and then fill in the missing values for different genders separately, at random."
},
{
"code": null,
"e": 16942,
"s": 16665,
"text": "In sequential hot-deck imputation, the column containing missing values is sorted according to auxiliary variable(s) so that records that have similar auxiliaries occur sequentially. Next, each missing value is filled in with the value of the first following available record."
},
{
"code": null,
"e": 17361,
"s": 16942,
"text": "What is more interesting is that k nearest neighbour imputation, which classifies similar records and put them together, can also be utilized. A missing value is then filled out by finding first the k records closest to the record with missing values. Next, a value is chosen from (or computed out of) the k nearest neighbours. In the case of computing, statistical methods like mean (as discussed before) can be used."
},
{
"code": null,
"e": 17481,
"s": 17361,
"text": "Some argue that filling in the missing values leads to a loss in information, no matter what imputation method we used."
},
{
"code": null,
"e": 17673,
"s": 17481,
"text": "That’s because saying that the data is missing is informative in itself, and the algorithm should know about it. Otherwise, we’re just reinforcing the pattern already exist by other features."
},
{
"code": null,
"e": 17864,
"s": 17673,
"text": "This is particularly important when the missing data doesn’t happen at random. Take for example a conducted survey where most people from a specific race refuse to answer a certain question."
},
{
"code": null,
"e": 18020,
"s": 17864,
"text": "Missing numeric data can be filled in with say, 0, but has these zeros must be ignored when calculating any statistical value or plotting the distribution."
},
{
"code": null,
"e": 18144,
"s": 18020,
"text": "While categorical data can be filled in with say, “Missing”: A new category which tells that this piece of data is missing."
},
{
"code": null,
"e": 18277,
"s": 18144,
"text": "Missing values are not the same as default values. For instance, zero can be interpreted as either missing or default, but not both."
},
{
"code": null,
"e": 18478,
"s": 18277,
"text": "Missing values are not “unknown”. A conducted research where some people didn’t remember whether they have been bullied or not at the school, should be treated and labelled as unknown and not missing."
},
{
"code": null,
"e": 18580,
"s": 18478,
"text": "Every time we drop or impute values we are losing information. So, flagging might come to the rescue."
},
{
"code": null,
"e": 18765,
"s": 18580,
"text": "They are values that are significantly different from all other observations. Any data value that lies more than (1.5 * IQR) away from the Q1 and Q3 quartiles is considered an outlier."
},
{
"code": null,
"e": 18897,
"s": 18765,
"text": "Outliers are innocent until proven guilty. With that being said, they should not be removed unless there is a good reason for that."
},
{
"code": null,
"e": 19065,
"s": 18897,
"text": "For example, one can notice some weird, suspicious values that are unlikely to happen, and so decides to remove them. Though, they worth investigating before removing."
},
{
"code": null,
"e": 19251,
"s": 19065,
"text": "It is also worth mentioning that some models, like linear regression, are very sensitive to outliers. In other words, outliers might throw the model off from where most of the data lie."
},
{
"code": null,
"e": 19370,
"s": 19251,
"text": "These errors result from having two or more values in the same row or across datasets that contradict with each other."
},
{
"code": null,
"e": 19517,
"s": 19370,
"text": "For example, if we have a dataset about the cost of living in cities. The total column must be equivalent to the sum of rent, transport, and food."
},
{
"code": null,
"e": 19645,
"s": 19517,
"text": "city rent transportation food totallibson 500 20 40 560paris 750 40 60 850"
},
{
"code": null,
"e": 19744,
"s": 19645,
"text": "Similarly, a child can’t be married. An employee’s salary can’t be less than the calculated taxes."
},
{
"code": null,
"e": 19809,
"s": 19744,
"text": "The same idea applies to related data across different datasets."
},
{
"code": null,
"e": 19926,
"s": 19809,
"text": "When done, one should verify correctness by re-inspecting the data and making sure it rules and constraints do hold."
},
{
"code": null,
"e": 20028,
"s": 19926,
"text": "For example, after filling out the missing data, they might violate any of the rules and constraints."
},
{
"code": null,
"e": 20095,
"s": 20028,
"text": "It might involve some manual correction if not possible otherwise."
},
{
"code": null,
"e": 20164,
"s": 20095,
"text": "Reporting how healthy the data is, is equally important to cleaning."
},
{
"code": null,
"e": 20305,
"s": 20164,
"text": "As mentioned before, software packages or libraries can generate reports of the changes made, which rules were violated, and how many times."
},
{
"code": null,
"e": 20434,
"s": 20305,
"text": "In addition to logging the violations, the causes of these errors should be considered. Why did they happen in the first place?."
},
{
"code": null,
"e": 20586,
"s": 20434,
"text": "If you made it that far, I am happy you were able to hold until the end. But, None of what mentioned is valuable without embracing the quality culture."
},
{
"code": null,
"e": 20707,
"s": 20586,
"text": "No matter how robust and strong the validation and cleaning process is, one will continue to suffer as new data come in."
},
{
"code": null,
"e": 20810,
"s": 20707,
"text": "It is better to guard yourself against a disease instead of spending the time and effort to remedy it."
},
{
"code": null,
"e": 20873,
"s": 20810,
"text": "These questions help to evaluate and improve the data quality:"
},
{
"code": null,
"e": 21079,
"s": 20873,
"text": "How the data is collected, and under what conditions?. The environment where the data was collected does matter. The environment includes, but not limited to, the location, timing, weather conditions, etc."
},
{
"code": null,
"e": 21336,
"s": 21079,
"text": "Questioning subjects about their opinion regarding whatever while they are on their way to work is not the same as while they are at home. Patients under a study who have difficulties using the tablets to answer a questionnaire might throw off the results."
},
{
"code": null,
"e": 21518,
"s": 21336,
"text": "What does the data represent?. Does it include everyone? Only the people in the city?. Or, perhaps, only those who opted to answer because they had a strong opinion about the topic."
},
{
"code": null,
"e": 21658,
"s": 21518,
"text": "What are the methods used to clean the data and why?. Different methods can be better in different situations or with different data types."
},
{
"code": null,
"e": 21801,
"s": 21658,
"text": "Do you invest the time and money in improving the process?. Investing in people and the process is as critical as investing in the technology."
},
{
"code": null,
"e": 21848,
"s": 21801,
"text": "And finally, ... it doesn’t go without saying,"
},
{
"code": null,
"e": 21871,
"s": 21848,
"text": "Thank you for reading!"
}
] |
C++ Array of Strings
|
In this section we will see how to define an array of strings in C++. As we know that
in C, there was no strings. We have to create strings using character array. So to
make some array of strings, we have to make a 2-dimentional array of characters.
Each rows are holding different strings in that matrix.
In C++ there is a class called string. Using this class object we can store string
type data, and use them very efficiently. We can create array of objects so we can
easily create array of strings.
After that we will also see how to make string type vector object and use
them as an array.
Live Demo
#include<iostream>
using namespace std;
int main() {
string animals[4] = {"Elephant", "Lion", "Deer", "Tiger"}; //The
string type array
for (int i = 0; i < 4; i++)
cout << animals[i] << endl;
}
Elephant
Lion
Deer
Tiger
Now let us see how to create string array using vectors. The vector is available in C++
standard library. It uses dynamically allocated array.
Live Demo
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<string> animal_vec;
animal_vec.push_back("Elephant");
animal_vec.push_back("Lion");
animal_vec.push_back("Deer");
animal_vec.push_back("Tiger");
for(int i = 0; i<animal_vec.size(); i++) {
cout << animal_vec[i] << endl;
}
}
Elephant
Lion
Deer
Tiger
|
[
{
"code": null,
"e": 1368,
"s": 1062,
"text": "In this section we will see how to define an array of strings in C++. As we know that\nin C, there was no strings. We have to create strings using character array. So to\nmake some array of strings, we have to make a 2-dimentional array of characters.\nEach rows are holding different strings in that matrix."
},
{
"code": null,
"e": 1566,
"s": 1368,
"text": "In C++ there is a class called string. Using this class object we can store string\ntype data, and use them very efficiently. We can create array of objects so we can\neasily create array of strings."
},
{
"code": null,
"e": 1658,
"s": 1566,
"text": "After that we will also see how to make string type vector object and use\nthem as an array."
},
{
"code": null,
"e": 1669,
"s": 1658,
"text": " Live Demo"
},
{
"code": null,
"e": 1878,
"s": 1669,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n string animals[4] = {\"Elephant\", \"Lion\", \"Deer\", \"Tiger\"}; //The\n string type array\n for (int i = 0; i < 4; i++)\n cout << animals[i] << endl;\n}"
},
{
"code": null,
"e": 1903,
"s": 1878,
"text": "Elephant\nLion\nDeer\nTiger"
},
{
"code": null,
"e": 2046,
"s": 1903,
"text": "Now let us see how to create string array using vectors. The vector is available in C++\nstandard library. It uses dynamically allocated array."
},
{
"code": null,
"e": 2057,
"s": 2046,
"text": " Live Demo"
},
{
"code": null,
"e": 2384,
"s": 2057,
"text": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main() {\n vector<string> animal_vec;\n animal_vec.push_back(\"Elephant\");\n animal_vec.push_back(\"Lion\");\n animal_vec.push_back(\"Deer\");\n animal_vec.push_back(\"Tiger\");\n for(int i = 0; i<animal_vec.size(); i++) {\n cout << animal_vec[i] << endl;\n }\n}"
},
{
"code": null,
"e": 2409,
"s": 2384,
"text": "Elephant\nLion\nDeer\nTiger"
}
] |
JasperReports - Compiling Report Design
|
We have generated the JasperReport template (JRXML file) in the previous chapter. This file cannot be used directly to generate reports. It has to be compiled to JasperReport' native binary format, called Jasper file. On compiling, we transform JasperDesign object into JasperReport object −
Interface net.sf.jasperreports.engine.design.JRCompiler plays a central role during compilation. This interface has several implementations depending on the language used for report expressions, which can be written in Java, Groovy, JavaScript, or any other scripting language as long as compiler implementation can evaluate it at runtime.
We can compile JRXML file in the following two ways −
Programmatic compilation.
Compilation through ANT task.
JasperReports API offers a facade class net.sf.jasperreports.engine.JasperCompileManager for compiling a JasperReport. This class consists of several public static methods for compiling report templates. The source of templates can be files, input streams and/or, memory objects.
The contents of the JRXML file (jasper_report_template.jrxml) are as follows. It is saved at directory C:\tools\jasperreports-5.0.1\test −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" language = "groovy" pageWidth = "595"
pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
topMargin = "20" bottomMargin = "20">
<queryString>
<![CDATA[]]>
</queryString>
<field name = "country" class = "java.lang.String">
<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name = "name" class = "java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<columnHeader>
<band height = "23">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "3"
width = "535" height = "15" backcolor = "#70A9A9" />
<box>
<bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
</box>
<textElement />
<text><![CDATA[]]> </text>
</staticText>
<staticText>
<reportElement x = "414" y = "3" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x = "0" y = "3" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height = "16">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "0"
width = "535" height = "14" backcolor = "#E5ECF9" />
<box>
<bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
</box>
<textElement />
<text><![CDATA[]]> </text>
</staticText>
<textField>
<reportElement x = "414" y = "0" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font size = "9" />
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x = "0" y = "0" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle" />
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
The following code demonstrates compilation of the above jasper_report_template.jrxml file.
package com.tutorialspoint;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
public class JasperReportCompile {
public static void main(String[] args) {
String sourceFileName = "C://tools/jasperreports-5.0.1/test" +
"/jasper_report_template.jrxml";
System.out.println("Compiling Report Design ...");
try {
/**
* Compile the report to a file name same as
* the JRXML file name
*/
JasperCompileManager.compileReportToFile(sourceFileName);
} catch (JRException e) {
e.printStackTrace();
}
System.out.println("Done compiling!!! ...");
}
}
As next step, let's save above content in the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportCompile.java and import the baseBuild.xml in the build.xml file as below. The baseBuild.xml already has the compile and run targets −
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "run" basedir = ".">
<import file = "baseBuild.xml"/>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportCompile as −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class = com.tutorialspoint.JasperReportCompile
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
compile:
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:27:
warning: 'includeantruntime' was not set, defaulting to
build.sysclasspath=last;set to false for repeatable builds
[javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes
run:
[echo] Runnin class : com.tutorialspoint.JasperReportCompile
[java] Compiling Report Design ...
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[java] log4j:WARN Please initialize the log4j system properly.
[java] Done compiling!!! ...
BUILD SUCCESSFUL
Total time: 8 seconds
As a result of above compilation, you will see that template file jasper_report_template.jasper got generated in C:\tools\jasperreports-5.0.1\test directory.
The net.sf.jasperreports.view.JasperDesignViewer can be used to preview compiled report templates and JRXML templates.
To move further, let's add a new target viewDesign to the above build.xml file, which will allow us to preview the compiled report. Below is the revised build.xml −
The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewDesign" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewDesign" description="Design viewer is launched
to preview the compiled report design.">
<java classname = "net.sf.jasperreports.view.JasperDesignViewer" fork = "true">
<arg value = "-F${file.name}.jasper" />
<classpath refid = "classpath" />
</java>
</target>
</project>
Let's execute the command − ant (viewDesign is the default target) at command prompt. JasperDesignViewer window opens up displaying the Jasper file as below −
As report template compilation is more like a design time job than a runtime job, JasperReport library has a custom ANT task. For certain situations, when JRXML file is created at runtime, we can't use this ANT task. The custom ANT task is called JRC and is implemented by the class: net.sf.jasperreports.ant.JRAntCompileTask. Its syntax and behavior are very similar to the built-in <javac> ANT task.
Let's add new target compilereportdesing to our existing build.xml. Here, the source folder is specified using a nested <src> tag with the filesets. The nested source tag allows compiling report templates that are scattered through many different locations and are not grouped under a single root report source folder. Below is the revised build.xml −
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "compilereportdesing" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewDesign" description = "Design viewer is
launched to preview the compiled report design.">
<java classname = "net.sf.jasperreports.view.JasperDesignViewer" fork = "true">
<arg value = "-F${file.name}.jasper" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the
JXML file and produces the .jasper file.">
<taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command prompt and go to the directory where build.xml is placed. Execute the command ant (compilereportdesing is the default target); Output is as follows −
C:\tools\jasperreports-5.0.1\test>ant
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See
http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[jrc] File :
C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
BUILD SUCCESSFUL
Total time: 5 seconds
File jasper_report_template.jasper is generated in the file system (in our case C:\tools\jasperreports-5.0.1\test directory). This file is identical to the file generated programmatically by calling the net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(). We can preview this jasper file, executing ant viewDesign.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2546,
"s": 2254,
"text": "We have generated the JasperReport template (JRXML file) in the previous chapter. This file cannot be used directly to generate reports. It has to be compiled to JasperReport' native binary format, called Jasper file. On compiling, we transform JasperDesign object into JasperReport object −"
},
{
"code": null,
"e": 2886,
"s": 2546,
"text": "Interface net.sf.jasperreports.engine.design.JRCompiler plays a central role during compilation. This interface has several implementations depending on the language used for report expressions, which can be written in Java, Groovy, JavaScript, or any other scripting language as long as compiler implementation can evaluate it at runtime."
},
{
"code": null,
"e": 2940,
"s": 2886,
"text": "We can compile JRXML file in the following two ways −"
},
{
"code": null,
"e": 2966,
"s": 2940,
"text": "Programmatic compilation."
},
{
"code": null,
"e": 2996,
"s": 2966,
"text": "Compilation through ANT task."
},
{
"code": null,
"e": 3276,
"s": 2996,
"text": "JasperReports API offers a facade class net.sf.jasperreports.engine.JasperCompileManager for compiling a JasperReport. This class consists of several public static methods for compiling report templates. The source of templates can be files, input streams and/or, memory objects."
},
{
"code": null,
"e": 3415,
"s": 3276,
"text": "The contents of the JRXML file (jasper_report_template.jrxml) are as follows. It is saved at directory C:\\tools\\jasperreports-5.0.1\\test −"
},
{
"code": null,
"e": 6789,
"s": 3415,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE jasperReport PUBLIC \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" language = \"groovy\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"555\" leftMargin = \"20\" rightMargin = \"20\"\n topMargin = \"20\" bottomMargin = \"20\">\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n \n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n \n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n \n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" \n width = \"535\" height = \"15\" backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n\n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n \n <detail>\n <band height = \"16\">\n\t\t\n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" \n width = \"535\" height = \"14\" backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\t\n</jasperReport>"
},
{
"code": null,
"e": 6881,
"s": 6789,
"text": "The following code demonstrates compilation of the above jasper_report_template.jrxml file."
},
{
"code": null,
"e": 7586,
"s": 6881,
"text": "package com.tutorialspoint;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperCompileManager;\n\npublic class JasperReportCompile {\n\n public static void main(String[] args) {\n String sourceFileName = \"C://tools/jasperreports-5.0.1/test\" + \n \"/jasper_report_template.jrxml\";\n\n System.out.println(\"Compiling Report Design ...\");\n try {\n /**\n * Compile the report to a file name same as\n * the JRXML file name\n */\n JasperCompileManager.compileReportToFile(sourceFileName);\n } catch (JRException e) {\n e.printStackTrace();\n }\n System.out.println(\"Done compiling!!! ...\");\n }\n}"
},
{
"code": null,
"e": 7840,
"s": 7586,
"text": "As next step, let's save above content in the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportCompile.java and import the baseBuild.xml in the build.xml file as below. The baseBuild.xml already has the compile and run targets −"
},
{
"code": null,
"e": 7998,
"s": 7840,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"run\" basedir = \".\">\n\n <import file = \"baseBuild.xml\"/>\n\n</project>"
},
{
"code": null,
"e": 8179,
"s": 7998,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportCompile as −"
},
{
"code": null,
"e": 8965,
"s": 8179,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class = com.tutorialspoint.JasperReportCompile\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\ncompile:\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:27:\n warning: 'includeantruntime' was not set, defaulting to\n build.sysclasspath=last;set to false for repeatable builds\n [javac] Compiling 1 source file to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportCompile\n [java] Compiling Report Design ...\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [java] log4j:WARN Please initialize the log4j system properly.\n [java] Done compiling!!! ...\n\nBUILD SUCCESSFUL\nTotal time: 8 seconds\n"
},
{
"code": null,
"e": 9123,
"s": 8965,
"text": "As a result of above compilation, you will see that template file jasper_report_template.jasper got generated in C:\\tools\\jasperreports-5.0.1\\test directory."
},
{
"code": null,
"e": 9242,
"s": 9123,
"text": "The net.sf.jasperreports.view.JasperDesignViewer can be used to preview compiled report templates and JRXML templates."
},
{
"code": null,
"e": 9407,
"s": 9242,
"text": "To move further, let's add a new target viewDesign to the above build.xml file, which will allow us to preview the compiled report. Below is the revised build.xml −"
},
{
"code": null,
"e": 9541,
"s": 9407,
"text": "The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 10037,
"s": 9541,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewDesign\" basedir = \".\">\n\n <import file = \"baseBuild.xml\" />\n <target name = \"viewDesign\" description=\"Design viewer is launched \n to preview the compiled report design.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperDesignViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.jasper\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n\n</project>"
},
{
"code": null,
"e": 10196,
"s": 10037,
"text": "Let's execute the command − ant (viewDesign is the default target) at command prompt. JasperDesignViewer window opens up displaying the Jasper file as below −"
},
{
"code": null,
"e": 10598,
"s": 10196,
"text": "As report template compilation is more like a design time job than a runtime job, JasperReport library has a custom ANT task. For certain situations, when JRXML file is created at runtime, we can't use this ANT task. The custom ANT task is called JRC and is implemented by the class: net.sf.jasperreports.ant.JRAntCompileTask. Its syntax and behavior are very similar to the built-in <javac> ANT task."
},
{
"code": null,
"e": 10950,
"s": 10598,
"text": "Let's add new target compilereportdesing to our existing build.xml. Here, the source folder is specified using a nested <src> tag with the filesets. The nested source tag allows compiling report templates that are scattered through many different locations and are not grouped under a single root report source folder. Below is the revised build.xml −"
},
{
"code": null,
"e": 11962,
"s": 10950,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"compilereportdesing\" basedir = \".\">\n \n <import file = \"baseBuild.xml\" />\n <target name = \"viewDesign\" description = \"Design viewer is \n launched to preview the compiled report design.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperDesignViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.jasper\" />\n <classpath refid = \"classpath\" />\n </java>\n\t\t\n </target>\n\n <target name = \"compilereportdesing\" description = \"Compiles the \n JXML file and produces the .jasper file.\">\n\t\t\n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n </target>\n\n</project>"
},
{
"code": null,
"e": 12137,
"s": 11962,
"text": "Next, let's open command prompt and go to the directory where build.xml is placed. Execute the command ant (compilereportdesing is the default target); Output is as follows −"
},
{
"code": null,
"e": 12707,
"s": 12137,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See\n http://logging.apache.org/log4j/1.2/faq.html#noconfig\n for more info.\n [jrc] File :\n C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nBUILD SUCCESSFUL\nTotal time: 5 seconds\n"
},
{
"code": null,
"e": 13041,
"s": 12707,
"text": "File jasper_report_template.jasper is generated in the file system (in our case C:\\tools\\jasperreports-5.0.1\\test directory). This file is identical to the file generated programmatically by calling the net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(). We can preview this jasper file, executing ant viewDesign."
},
{
"code": null,
"e": 13048,
"s": 13041,
"text": " Print"
},
{
"code": null,
"e": 13059,
"s": 13048,
"text": " Add Notes"
}
] |
HTML5 - Web SQL Database
|
The Web SQL Database API isn't actually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL.
I'm assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial.
Web SQL Database will work in latest version of Safari, Chrome and Opera.
There are following three core methods defined in the spec that I am going to cover in this tutorial −
openDatabase − This method creates the database object either using existing database or creating new one.
openDatabase − This method creates the database object either using existing database or creating new one.
transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation.
transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation.
executeSql − This method is used to execute actual SQL query.
executeSql − This method is used to execute actual SQL query.
The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist.
To create and open a database, use the following code −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
The above method took the following five parameters −
Database name
Version number
Text description
Size of database
Creation callback
The last and 5th argument, creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned.
To execute a query you use the database.transaction() function. This function needs a single argument, which is a function that takes care of actually executing the query as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});
The above query will create a table called LOGS in 'mydb' database.
To create enteries into the table we add simple SQL query in the above example as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
We can pass dynamic values while creating entering as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?'), [e_id, e_log];
});
Here e_id and e_log are external variables, and executeSql maps each item in the array argument to the "?"s.
To read already existing records we use a callback to capture the results as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).log );
}
}, null);
});
So finally, let us keep this example in a full-fledged HTML5 document as follows and try to run it with Safari browser.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
})
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
</script>
</head>
<body>
<div id = "status" name = "status">Status Message</div>
</body>
</html>
This will produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2793,
"s": 2608,
"text": "The Web SQL Database API isn't actually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL."
},
{
"code": null,
"e": 3014,
"s": 2793,
"text": "I'm assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial."
},
{
"code": null,
"e": 3088,
"s": 3014,
"text": "Web SQL Database will work in latest version of Safari, Chrome and Opera."
},
{
"code": null,
"e": 3191,
"s": 3088,
"text": "There are following three core methods defined in the spec that I am going to cover in this tutorial −"
},
{
"code": null,
"e": 3298,
"s": 3191,
"text": "openDatabase − This method creates the database object either using existing database or creating new one."
},
{
"code": null,
"e": 3405,
"s": 3298,
"text": "openDatabase − This method creates the database object either using existing database or creating new one."
},
{
"code": null,
"e": 3542,
"s": 3405,
"text": "transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation."
},
{
"code": null,
"e": 3679,
"s": 3542,
"text": "transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation."
},
{
"code": null,
"e": 3741,
"s": 3679,
"text": "executeSql − This method is used to execute actual SQL query."
},
{
"code": null,
"e": 3803,
"s": 3741,
"text": "executeSql − This method is used to execute actual SQL query."
},
{
"code": null,
"e": 3939,
"s": 3803,
"text": "The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist."
},
{
"code": null,
"e": 3995,
"s": 3939,
"text": "To create and open a database, use the following code −"
},
{
"code": null,
"e": 4062,
"s": 3995,
"text": "var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);\n"
},
{
"code": null,
"e": 4116,
"s": 4062,
"text": "The above method took the following five parameters −"
},
{
"code": null,
"e": 4130,
"s": 4116,
"text": "Database name"
},
{
"code": null,
"e": 4145,
"s": 4130,
"text": "Version number"
},
{
"code": null,
"e": 4162,
"s": 4145,
"text": "Text description"
},
{
"code": null,
"e": 4179,
"s": 4162,
"text": "Size of database"
},
{
"code": null,
"e": 4197,
"s": 4179,
"text": "Creation callback"
},
{
"code": null,
"e": 4396,
"s": 4197,
"text": "The last and 5th argument, creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned."
},
{
"code": null,
"e": 4580,
"s": 4396,
"text": "To execute a query you use the database.transaction() function. This function needs a single argument, which is a function that takes care of actually executing the query as follows −"
},
{
"code": null,
"e": 4757,
"s": 4580,
"text": "var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); \n\ndb.transaction(function (tx) { \n tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); \n});"
},
{
"code": null,
"e": 4825,
"s": 4757,
"text": "The above query will create a table called LOGS in 'mydb' database."
},
{
"code": null,
"e": 4917,
"s": 4825,
"text": "To create enteries into the table we add simple SQL query in the above example as follows −"
},
{
"code": null,
"e": 5233,
"s": 4917,
"text": "var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); \n\ndb.transaction(function (tx) { \n tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); \n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, \"foobar\")'); \n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, \"logmsg\")'); \n}); "
},
{
"code": null,
"e": 5297,
"s": 5233,
"text": "We can pass dynamic values while creating entering as follows −"
},
{
"code": null,
"e": 5551,
"s": 5297,
"text": "var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); \n\ndb.transaction(function (tx) { \n tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); \n tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?'), [e_id, e_log]; \n});"
},
{
"code": null,
"e": 5660,
"s": 5551,
"text": "Here e_id and e_log are external variables, and executeSql maps each item in the array argument to the \"?\"s."
},
{
"code": null,
"e": 5747,
"s": 5660,
"text": "To read already existing records we use a callback to capture the results as follows −"
},
{
"code": null,
"e": 6426,
"s": 5747,
"text": "var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); \n\ndb.transaction(function (tx) { \n tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');\n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, \"foobar\")'); \n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, \"logmsg\")'); \n}); \n\ndb.transaction(function (tx) { \n tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { \n var len = results.rows.length, i; \n msg = \"<p>Found rows: \" + len + \"</p>\"; \n document.querySelector('#status').innerHTML += msg; \n \n for (i = 0; i < len; i++) { \n alert(results.rows.item(i).log ); \n } \n \n }, null); \n});"
},
{
"code": null,
"e": 6546,
"s": 6426,
"text": "So finally, let us keep this example in a full-fledged HTML5 document as follows and try to run it with Safari browser."
},
{
"code": null,
"e": 7825,
"s": 6546,
"text": "<!DOCTYPE HTML> \n\n<html> \n <head> \n \n <script type = \"text/javascript\"> \n var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); \n var msg; \n \n db.transaction(function (tx) { \n tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); \n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, \"foobar\")'); \n tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, \"logmsg\")'); \n msg = '<p>Log message created and row inserted.</p>'; \n document.querySelector('#status').innerHTML = msg; \n })\n\n db.transaction(function (tx) { \n tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { \n var len = results.rows.length, i; \n msg = \"<p>Found rows: \" + len + \"</p>\"; \n document.querySelector('#status').innerHTML += msg; \n \n for (i = 0; i < len; i++) { \n msg = \"<p><b>\" + results.rows.item(i).log + \"</b></p>\"; \n document.querySelector('#status').innerHTML += msg; \n } \n }, null); \n }); \n </script> \n </head> \n \n <body> \n <div id = \"status\" name = \"status\">Status Message</div> \n </body> \n</html>"
},
{
"code": null,
"e": 7866,
"s": 7825,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7899,
"s": 7866,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7913,
"s": 7899,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7948,
"s": 7913,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7962,
"s": 7948,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7997,
"s": 7962,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8014,
"s": 7997,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8049,
"s": 8014,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8080,
"s": 8049,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8113,
"s": 8080,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8144,
"s": 8113,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8179,
"s": 8144,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8210,
"s": 8179,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8217,
"s": 8210,
"text": " Print"
},
{
"code": null,
"e": 8228,
"s": 8217,
"text": " Add Notes"
}
] |
Generate all possible sorted arrays from alternate elements of two given sorted arrays - GeeksforGeeks
|
11 Nov, 2021
Given two sorted arrays A and B, generate all possible arrays such that first element is taken from A then from B then from A and so on in increasing order till the arrays exhausted. The generated arrays should end with an element from B.For Example
A = {10, 15, 25}
B = {1, 5, 20, 30}
The resulting arrays are:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. In the recursive function, a flag is passed to indicate whether current element in output should be taken from ‘A’ or ‘B’. Below is C++ implementation.
C++
Java
Python3
C#
PHP
Javascript
#include<bits/stdc++.h>using namespace std; void printArr(int arr[], int n); /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n, int len, bool flag){ if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len) printArr(C, len+1); // Recur for all elements of A after current index for (int k = i; k < m; k++) { if (!len) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k+1, j, m, n, len, !flag); } else /* include valid element from A and recur */ { if (A[k] > C[len]) { C[len+1] = A[k]; generateUtil(A, B, C, k+1, j, m, n, len+1, !flag); } } } } else /* Include valid element from B and recur */ { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len+1] = B[l]; generateUtil(A, B, C, i, l+1, m, n, len+1, !flag); } } }} /* Wrapper function */void generate(int A[], int B[], int m, int n){ int C[m+n]; /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true);} // A utility function to print an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver programint main(){ int A[] = {10, 15, 25}; int B[] = {5, 20, 30}; int n = sizeof(A)/sizeof(A[0]); int m = sizeof(B)/sizeof(B[0]); generate(A, B, n, m); return 0;}
class GenerateArrays { /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */ void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n, int len, boolean flag) { if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len != 0) printArr(C, len + 1); // Recur for all elements of A after current index for (int k = i; k < m; k++) { if (len == 0) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } /* include valid element from A and recur */ else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } /* Include valid element from B and recur */ else { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } } } /* Wrapper function */ void generate(int A[], int B[], int m, int n) { int C[] = new int[m + n]; /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true); } // A utility function to print an array void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(""); } public static void main(String[] args) { GenerateArrays generate = new GenerateArrays(); int A[] = {10, 15, 25}; int B[] = {5, 20, 30}; int n = A.length; int m = B.length; generate.generate(A, B, n, m); }} // This code has been contributed by Mayank Jaiswal
# A utility function to print an arraydef printArr(arr,n): for i in range(n): print(arr[i] , " ",end="") print() ''' Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations '''def generateUtil(A,B,C,i,j,m,n,len,flag): if (flag): # Include valid element from A # Print output if there is at # least one 'B' in output array 'C' if (len): printArr(C, len+1) # Recur for all elements of # A after current index for k in range(i,m): if ( not len): ''' this block works for the very first call to include the first element in the output array ''' C[len] = A[k] # don't increment lem # as B is included yet generateUtil(A, B, C, k+1, j, m, n, len, not flag) else: # include valid element from A and recur if (A[k] > C[len]): C[len+1] = A[k] generateUtil(A, B, C, k+1, j, m, n, len+1, not flag) else: # Include valid element from B and recur for l in range(j,n): if (B[l] > C[len]): C[len+1] = B[l] generateUtil(A, B, C, i, l+1, m, n, len+1, not flag) # Wrapper functiondef generate(A,B,m,n): C=[] #output array for i in range(m+n+1): C.append(0) generateUtil(A, B, C, 0, 0, m, n, 0, True) # Driver program A = [10, 15, 25]B = [5, 20, 30]n = len(A)m = len(B) generate(A, B, n, m) # This code is contributed# by Anant Agarwal.
// C# Program to generate all possible// sorted arrays from alternate elements// of two given sorted arraysusing System; class GenerateArrays { /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */ public virtual void generateUtil(int[] A, int[] B, int[] C, int i, int j, int m, int n, int len, bool flag) { // Include valid // element from A if (flag) { // Print output if there is // at least one 'B' in // output array 'C' if (len != 0) { printArr(C, len + 1); } // Recur for all elements // of A after current index for (int k = i; k < m; k++) { if (len == 0) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem // as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } // include valid element // from A and recur else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } // Include valid element // from B and recur else { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } }} // Wrapper functionpublic virtual void generate(int[] A, int[] B, int m, int n) { int[] C = new int[m + n]; // output array generateUtil(A, B, C, 0, 0, m, n, 0, true);} // A utility function to print an arraypublic virtual void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine("");} // Driver Codepublic static void Main(string[] args) { GenerateArrays generate = new GenerateArrays(); int[] A = new int[] {10, 15, 25}; int[] B = new int[] {5, 20, 30}; int n = A.Length; int m = B.Length; generate.generate(A, B, n, m);}} // This code is contributed by Shrikant13
<?php /* Function to generates and prints allsorted arrays from alternate elements of'A[i..m-1]' and 'B[j..n-1]'If 'flag' is true, then current elementis to be included from A otherwise from B.'len' is the index in output array C[].We print output array each time beforeincluding a character from A only if lengthof output array is greater than 0. We trythan all possible combinations */function generateUtil(&$A, &$B, &$C, $i, $j, $m, $n, $len, $flag){ if ($flag) // Include valid element from A { // Print output if there is at least // one 'B' in output array 'C' if ($len) printArr($C, $len + 1); // Recur for all elements of A // after current index for ($k = $i; $k < $m; $k++) { if (!$len) { /* this block works for the very first call to include the first element in the output array */ $C[$len] = $A[$k]; // don't increment lem as B // is included yet generateUtil($A, $B, $C, $k + 1, $j, $m, $n, $len, !$flag); } else /* include valid element from A and recur */ { if ($A[$k] > $C[$len]) { $C[$len + 1] = $A[$k]; generateUtil($A, $B, $C, $k + 1, $j, $m, $n, $len + 1, !$flag); } } } } else /* Include valid element from B and recur */ { for ($l = $j; $l < $n; $l++) { if ($B[$l] > $C[$len]) { $C[$len + 1] = $B[$l]; generateUtil($A, $B, $C, $i, $l + 1, $m, $n, $len + 1, !$flag); } } }} /* Wrapper function */function generate(&$A, &$B, $m, $n){ $C = array_fill(0, ($m + $n), NULL); /* output array */ generateUtil($A, $B, $C, 0, 0, $m, $n, 0, true);} // A utility function to print an arrayfunction printArr(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; echo "\n";} // Driver Code$A = array(10, 15, 25);$B = array(5, 20, 30);$n = sizeof($A);$m = sizeof($B);generate($A, $B, $n, $m); // This code is contributed by ChitraNayal?>
<script> /* * Function to generates and prints all sorted arrays from alternate elements of * 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be * included from A otherwise from B. 'len' is the index in output array C. We * print output array each time before including a character from A only if * length of output array is greater than 0. We try than all possible * combinations */ function generateUtil(A , B , C , i , j , m , n , len, flag) { if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len != 0) printArr(C, len + 1); // Recur for all elements of A after current index for (var k = i; k < m; k++) { if (len == 0) { /* * this block works for the very first call to include the first element in the * output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } /* include valid element from A and recur */ else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } /* Include valid element from B and recur */ else { for (var l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } } } /* Wrapper function */ function generate(A , B , m , n) { var C = Array(m + n).fill(0); /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true); } // A utility function to print an array function printArr(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br/>"); } var A = [ 10, 15, 25 ]; var B = [ 5, 20, 30 ]; var n = A.length; var m = B.length; generate(A, B, n, m); // This code contributed by gauravrajput1</script>
Output:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
Time Complexity: O(N2)
Auxiliary Space: O(M+N)This article is contributed by Gaurav Ahirwar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above\
shrikanth13
ukasp
GauravRajput1
Kirti_Mangal
rohitsingh07052
Arrays
Recursion
Arrays
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Linear Search
Queue | Set 1 (Introduction and Array Implementation)
Python | Using 2D arrays/lists the right way
Write a program to print all permutations of a given string
Recursion
Backtracking | Introduction
Program for Tower of Hanoi
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
|
[
{
"code": null,
"e": 25119,
"s": 25091,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 25371,
"s": 25119,
"text": "Given two sorted arrays A and B, generate all possible arrays such that first element is taken from A then from B then from A and so on in increasing order till the arrays exhausted. The generated arrays should end with an element from B.For Example "
},
{
"code": null,
"e": 25504,
"s": 25371,
"text": " \nA = {10, 15, 25}\nB = {1, 5, 20, 30}\n\nThe resulting arrays are:\n 10 20\n 10 20 25 30\n 10 30\n 15 20\n 15 20 25 30\n 15 30\n 25 30"
},
{
"code": null,
"e": 25766,
"s": 25504,
"text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. In the recursive function, a flag is passed to indicate whether current element in output should be taken from ‘A’ or ‘B’. Below is C++ implementation. "
},
{
"code": null,
"e": 25770,
"s": 25766,
"text": "C++"
},
{
"code": null,
"e": 25775,
"s": 25770,
"text": "Java"
},
{
"code": null,
"e": 25783,
"s": 25775,
"text": "Python3"
},
{
"code": null,
"e": 25786,
"s": 25783,
"text": "C#"
},
{
"code": null,
"e": 25790,
"s": 25786,
"text": "PHP"
},
{
"code": null,
"e": 25801,
"s": 25790,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; void printArr(int arr[], int n); /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n, int len, bool flag){ if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len) printArr(C, len+1); // Recur for all elements of A after current index for (int k = i; k < m; k++) { if (!len) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k+1, j, m, n, len, !flag); } else /* include valid element from A and recur */ { if (A[k] > C[len]) { C[len+1] = A[k]; generateUtil(A, B, C, k+1, j, m, n, len+1, !flag); } } } } else /* Include valid element from B and recur */ { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len+1] = B[l]; generateUtil(A, B, C, i, l+1, m, n, len+1, !flag); } } }} /* Wrapper function */void generate(int A[], int B[], int m, int n){ int C[m+n]; /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true);} // A utility function to print an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver programint main(){ int A[] = {10, 15, 25}; int B[] = {5, 20, 30}; int n = sizeof(A)/sizeof(A[0]); int m = sizeof(B)/sizeof(B[0]); generate(A, B, n, m); return 0;}",
"e": 28046,
"s": 25801,
"text": null
},
{
"code": "class GenerateArrays { /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */ void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n, int len, boolean flag) { if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len != 0) printArr(C, len + 1); // Recur for all elements of A after current index for (int k = i; k < m; k++) { if (len == 0) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } /* include valid element from A and recur */ else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } /* Include valid element from B and recur */ else { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } } } /* Wrapper function */ void generate(int A[], int B[], int m, int n) { int C[] = new int[m + n]; /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true); } // A utility function to print an array void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(\"\"); } public static void main(String[] args) { GenerateArrays generate = new GenerateArrays(); int A[] = {10, 15, 25}; int B[] = {5, 20, 30}; int n = A.length; int m = B.length; generate.generate(A, B, n, m); }} // This code has been contributed by Mayank Jaiswal",
"e": 30641,
"s": 28046,
"text": null
},
{
"code": "# A utility function to print an arraydef printArr(arr,n): for i in range(n): print(arr[i] , \" \",end=\"\") print() ''' Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations '''def generateUtil(A,B,C,i,j,m,n,len,flag): if (flag): # Include valid element from A # Print output if there is at # least one 'B' in output array 'C' if (len): printArr(C, len+1) # Recur for all elements of # A after current index for k in range(i,m): if ( not len): ''' this block works for the very first call to include the first element in the output array ''' C[len] = A[k] # don't increment lem # as B is included yet generateUtil(A, B, C, k+1, j, m, n, len, not flag) else: # include valid element from A and recur if (A[k] > C[len]): C[len+1] = A[k] generateUtil(A, B, C, k+1, j, m, n, len+1, not flag) else: # Include valid element from B and recur for l in range(j,n): if (B[l] > C[len]): C[len+1] = B[l] generateUtil(A, B, C, i, l+1, m, n, len+1, not flag) # Wrapper functiondef generate(A,B,m,n): C=[] #output array for i in range(m+n+1): C.append(0) generateUtil(A, B, C, 0, 0, m, n, 0, True) # Driver program A = [10, 15, 25]B = [5, 20, 30]n = len(A)m = len(B) generate(A, B, n, m) # This code is contributed# by Anant Agarwal.",
"e": 32695,
"s": 30641,
"text": null
},
{
"code": "// C# Program to generate all possible// sorted arrays from alternate elements// of two given sorted arraysusing System; class GenerateArrays { /* Function to generates and prints all sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[]. We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations */ public virtual void generateUtil(int[] A, int[] B, int[] C, int i, int j, int m, int n, int len, bool flag) { // Include valid // element from A if (flag) { // Print output if there is // at least one 'B' in // output array 'C' if (len != 0) { printArr(C, len + 1); } // Recur for all elements // of A after current index for (int k = i; k < m; k++) { if (len == 0) { /* this block works for the very first call to include the first element in the output array */ C[len] = A[k]; // don't increment lem // as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } // include valid element // from A and recur else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } // Include valid element // from B and recur else { for (int l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } }} // Wrapper functionpublic virtual void generate(int[] A, int[] B, int m, int n) { int[] C = new int[m + n]; // output array generateUtil(A, B, C, 0, 0, m, n, 0, true);} // A utility function to print an arraypublic virtual void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(\"\");} // Driver Codepublic static void Main(string[] args) { GenerateArrays generate = new GenerateArrays(); int[] A = new int[] {10, 15, 25}; int[] B = new int[] {5, 20, 30}; int n = A.Length; int m = B.Length; generate.generate(A, B, n, m);}} // This code is contributed by Shrikant13",
"e": 35570,
"s": 32695,
"text": null
},
{
"code": "<?php /* Function to generates and prints allsorted arrays from alternate elements of'A[i..m-1]' and 'B[j..n-1]'If 'flag' is true, then current elementis to be included from A otherwise from B.'len' is the index in output array C[].We print output array each time beforeincluding a character from A only if lengthof output array is greater than 0. We trythan all possible combinations */function generateUtil(&$A, &$B, &$C, $i, $j, $m, $n, $len, $flag){ if ($flag) // Include valid element from A { // Print output if there is at least // one 'B' in output array 'C' if ($len) printArr($C, $len + 1); // Recur for all elements of A // after current index for ($k = $i; $k < $m; $k++) { if (!$len) { /* this block works for the very first call to include the first element in the output array */ $C[$len] = $A[$k]; // don't increment lem as B // is included yet generateUtil($A, $B, $C, $k + 1, $j, $m, $n, $len, !$flag); } else /* include valid element from A and recur */ { if ($A[$k] > $C[$len]) { $C[$len + 1] = $A[$k]; generateUtil($A, $B, $C, $k + 1, $j, $m, $n, $len + 1, !$flag); } } } } else /* Include valid element from B and recur */ { for ($l = $j; $l < $n; $l++) { if ($B[$l] > $C[$len]) { $C[$len + 1] = $B[$l]; generateUtil($A, $B, $C, $i, $l + 1, $m, $n, $len + 1, !$flag); } } }} /* Wrapper function */function generate(&$A, &$B, $m, $n){ $C = array_fill(0, ($m + $n), NULL); /* output array */ generateUtil($A, $B, $C, 0, 0, $m, $n, 0, true);} // A utility function to print an arrayfunction printArr(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; echo \"\\n\";} // Driver Code$A = array(10, 15, 25);$B = array(5, 20, 30);$n = sizeof($A);$m = sizeof($B);generate($A, $B, $n, $m); // This code is contributed by ChitraNayal?>",
"e": 37916,
"s": 35570,
"text": null
},
{
"code": "<script> /* * Function to generates and prints all sorted arrays from alternate elements of * 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be * included from A otherwise from B. 'len' is the index in output array C. We * print output array each time before including a character from A only if * length of output array is greater than 0. We try than all possible * combinations */ function generateUtil(A , B , C , i , j , m , n , len, flag) { if (flag) // Include valid element from A { // Print output if there is at least one 'B' in output array 'C' if (len != 0) printArr(C, len + 1); // Recur for all elements of A after current index for (var k = i; k < m; k++) { if (len == 0) { /* * this block works for the very first call to include the first element in the * output array */ C[len] = A[k]; // don't increment lem as B is included yet generateUtil(A, B, C, k + 1, j, m, n, len, !flag); } /* include valid element from A and recur */ else if (A[k] > C[len]) { C[len + 1] = A[k]; generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); } } } /* Include valid element from B and recur */ else { for (var l = j; l < n; l++) { if (B[l] > C[len]) { C[len + 1] = B[l]; generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); } } } } /* Wrapper function */ function generate(A , B , m , n) { var C = Array(m + n).fill(0); /* output array */ generateUtil(A, B, C, 0, 0, m, n, 0, true); } // A utility function to print an array function printArr(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(\"<br/>\"); } var A = [ 10, 15, 25 ]; var B = [ 5, 20, 30 ]; var n = A.length; var m = B.length; generate(A, B, n, m); // This code contributed by gauravrajput1</script>",
"e": 40244,
"s": 37916,
"text": null
},
{
"code": null,
"e": 40254,
"s": 40244,
"text": "Output: "
},
{
"code": null,
"e": 40308,
"s": 40254,
"text": "10 20\n10 20 25 30\n10 30\n15 20\n15 20 25 30\n15 30\n25 30"
},
{
"code": null,
"e": 40331,
"s": 40308,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 40527,
"s": 40331,
"text": "Auxiliary Space: O(M+N)This article is contributed by Gaurav Ahirwar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above\\ "
},
{
"code": null,
"e": 40539,
"s": 40527,
"text": "shrikanth13"
},
{
"code": null,
"e": 40545,
"s": 40539,
"text": "ukasp"
},
{
"code": null,
"e": 40559,
"s": 40545,
"text": "GauravRajput1"
},
{
"code": null,
"e": 40572,
"s": 40559,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 40588,
"s": 40572,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 40595,
"s": 40588,
"text": "Arrays"
},
{
"code": null,
"e": 40605,
"s": 40595,
"text": "Recursion"
},
{
"code": null,
"e": 40612,
"s": 40605,
"text": "Arrays"
},
{
"code": null,
"e": 40622,
"s": 40612,
"text": "Recursion"
},
{
"code": null,
"e": 40720,
"s": 40622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40729,
"s": 40720,
"text": "Comments"
},
{
"code": null,
"e": 40742,
"s": 40729,
"text": "Old Comments"
},
{
"code": null,
"e": 40790,
"s": 40742,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 40822,
"s": 40790,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 40836,
"s": 40822,
"text": "Linear Search"
},
{
"code": null,
"e": 40890,
"s": 40836,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 40935,
"s": 40890,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 40995,
"s": 40935,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41005,
"s": 40995,
"text": "Recursion"
},
{
"code": null,
"e": 41033,
"s": 41005,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 41060,
"s": 41033,
"text": "Program for Tower of Hanoi"
}
] |
Deploy a Public Streamlit Web App for Free — Here’s How | by Yong Cui | Towards Data Science
|
With the growing popularity of Python as the go-to choice for many data scientists, the dissemination of their findings has become an urgent need. Web apps represent a cross-platform solution that provides sufficient interactivity. However, the conventional development requires Python users’ sufficient familiarity with relatively complicated web frameworks, such as Flask and Django. Although it’s not the hardest thing for any experienced Python users to learn these frameworks, it might be an overkill for data scientists to showcase their data science projects.
Fortunately, we data scientists have a better option now — the Streamlit framework. It simply converts simple Python scripts to functional, interactive, and shareable web apps within minutes. Because it’s designed toward showcasing data science products, it natively supports the data models and graphs with major data science libraries, such as pandas and matplotlib. Thus, it requires little learning curve if you already know Python well. If you’ve not tried that, here’s a couple of articles that I published before to get you started with streamlit.
towardsdatascience.com
towardsdatascience.com
In this article, I want to take you guys a step further by showing you how to publish your web app such that others can access your data science projects publicly. More importantly, I’ll show you how to integrate Google Sheets as a free database host for our project. Please note that Google Sheets isn’t an industry-level database, but it’s good enough to host a small dataset. What’s more — it’s free.
Without further ado, let’s get it started.
First, I want to make sure that you’ve installed streamlit on your computer and you’re able to launch a web app locally.
You can install the streamlit framework using the pip tool: pip install streamlit.
You can check if it’s installed by simply viewing the version: streamlit --version. This command should tell you what version the installed streamlit package is. The version information displayed is Streamlit, version 0.89.0 while I’m writing this tutorial.
Create a Python script file and let’s simply call it streamlit_sharing.py. Because the goal of this tutorial is to show you how to publish the web app, we’ll keep the stuff in the app minimum. Suppose that the script includes the following lines of code.
To launch the app locally, in the terminal, you can run the following command: streamlit run streamlit_sharing.py. Please make sure that you need to navigate to the directory where the Python script is saved. Otherwise, you’ll have to specify the full path to the file.
The above screenshot shows you the web app running on your local host. Great! You’ve simply launched your first Streamlit web app.
We should understand that Streamlit supports the connection to many different kinds of database, but online database hosts are not typically free. To provide you with a proof of concept, we’ll use a public Google Sheet as the data source for our web app. Suppose that our sheet has the following data.
Once you create the Google sheet, please turn on sharing publicly such that our web app can access it directly.
IMPORTANT: To keep the app simple, we’ll only consider the set-up that uses a public Google Sheet. If you want to use a private Google Sheet, it requires enabling Google APIs and interested readers can refer to Streamlit’s website for additional instruction.
To access the Google sheet programmatically, we need to install the package gsheetsdb by running pip install gsheetsdb. Once it’s installed, we can update our script to the following version:
The above code involves the following changes:
We use the gsheetsdb for connecting to the Google sheet.
To use the sheet, we use a SQL-like syntax to retrieve the data. Notably, instead of specifying the sheet’s name, we need to specify the URL to the sheet. Don’t forget about the double quotes for the sheet’s URL.
We create a DataFrame object from the retrieved rows.
With all these changes, our web app looks like the following now. As you can see, we’re indeed able to retrieve the data from the created Google sheet.
There are different options to host a Streamlit app, such as Heroku (You can find a tutorial in a Medium article). Here, I want to show you to use Streamlit Share — a free Streamlit web app sharing service provided by Streamlit. You can find more information at its official blog. Here are the general steps.
Because the Streamlit team is still developing the platform, you need to request an invite to be able to deploy the app on Streamlit Share. You can submit a request here: https://streamlit.io/cloudOnce you submit your request, it won’t take too long for them to approve your request. In my case, it took less than one day to receive the invite.You can now login into the Streamlit Share (https://share.streamlit.io/) with your GitHub authentication.
Because the Streamlit team is still developing the platform, you need to request an invite to be able to deploy the app on Streamlit Share. You can submit a request here: https://streamlit.io/cloud
Once you submit your request, it won’t take too long for them to approve your request. In my case, it took less than one day to receive the invite.
You can now login into the Streamlit Share (https://share.streamlit.io/) with your GitHub authentication.
As you’ll see next, we’ll share our app in a public GitHub repository, and thus we don’t want to expose the Google sheet URL, which can be a potential security concern. Certainly, using a private Google Sheet or other databases with authentications is more secure.
Instead of specifying the URL in the script directly, you’ll save the URL in a shared app’s settings, from which you can access using the setting’s name.
# Originalgsheet_url = "the_link"# Updated, when the URL is saved in the settingsgsheet_url = st.secrets["public_gsheets_url"]
Once you update your script, it’s finally the time to make your app public (to some extent). What you’ll do is to create a public GitHub repository. I’m not going to expand how you can do that here. I use PyCharm, and I just need to use the built-in Git tool to create a repository easily.
Go to the Streamlit Share website, you can create a new web app by clicking “New App”, which will pop up the window shown below (left panel).
If you’ve already linked your GitHub account, Streamlit is smart enough to pull out the list of repositories and you can simply choose the one and specify the file path.
Importantly, you click the “Advanced settings” and specify the link there, because as mentioned previously, this is how our streamlit script file accesses the confidential information. When needed, you need to choose a proper Python version for your project, because by default, it’s set to 3.7.
After that, click the “Deploy!” button, and wait for a couple of moments, and you should be able to see your app is up and running!
Because it’s hosted by Streamlit Share as a public website, you can share the link to your teammates or clients and they can access it from anywhere they want.
Streamlit has made web app developments easy for data scientists, because it takes care of the layout of the web elements, and we data scientists are just responsible for the core part of our app — the data.
If you have never tried Streamlit, I strongly recommend you give it a try, and I bet you’ll love it.
Thanks for reading this article. Stay connected by signing up my newsletter. Not a Medium member yet? Support my writing by using my membership link.
|
[
{
"code": null,
"e": 739,
"s": 172,
"text": "With the growing popularity of Python as the go-to choice for many data scientists, the dissemination of their findings has become an urgent need. Web apps represent a cross-platform solution that provides sufficient interactivity. However, the conventional development requires Python users’ sufficient familiarity with relatively complicated web frameworks, such as Flask and Django. Although it’s not the hardest thing for any experienced Python users to learn these frameworks, it might be an overkill for data scientists to showcase their data science projects."
},
{
"code": null,
"e": 1294,
"s": 739,
"text": "Fortunately, we data scientists have a better option now — the Streamlit framework. It simply converts simple Python scripts to functional, interactive, and shareable web apps within minutes. Because it’s designed toward showcasing data science products, it natively supports the data models and graphs with major data science libraries, such as pandas and matplotlib. Thus, it requires little learning curve if you already know Python well. If you’ve not tried that, here’s a couple of articles that I published before to get you started with streamlit."
},
{
"code": null,
"e": 1317,
"s": 1294,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1340,
"s": 1317,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1744,
"s": 1340,
"text": "In this article, I want to take you guys a step further by showing you how to publish your web app such that others can access your data science projects publicly. More importantly, I’ll show you how to integrate Google Sheets as a free database host for our project. Please note that Google Sheets isn’t an industry-level database, but it’s good enough to host a small dataset. What’s more — it’s free."
},
{
"code": null,
"e": 1787,
"s": 1744,
"text": "Without further ado, let’s get it started."
},
{
"code": null,
"e": 1908,
"s": 1787,
"text": "First, I want to make sure that you’ve installed streamlit on your computer and you’re able to launch a web app locally."
},
{
"code": null,
"e": 1991,
"s": 1908,
"text": "You can install the streamlit framework using the pip tool: pip install streamlit."
},
{
"code": null,
"e": 2249,
"s": 1991,
"text": "You can check if it’s installed by simply viewing the version: streamlit --version. This command should tell you what version the installed streamlit package is. The version information displayed is Streamlit, version 0.89.0 while I’m writing this tutorial."
},
{
"code": null,
"e": 2504,
"s": 2249,
"text": "Create a Python script file and let’s simply call it streamlit_sharing.py. Because the goal of this tutorial is to show you how to publish the web app, we’ll keep the stuff in the app minimum. Suppose that the script includes the following lines of code."
},
{
"code": null,
"e": 2774,
"s": 2504,
"text": "To launch the app locally, in the terminal, you can run the following command: streamlit run streamlit_sharing.py. Please make sure that you need to navigate to the directory where the Python script is saved. Otherwise, you’ll have to specify the full path to the file."
},
{
"code": null,
"e": 2905,
"s": 2774,
"text": "The above screenshot shows you the web app running on your local host. Great! You’ve simply launched your first Streamlit web app."
},
{
"code": null,
"e": 3207,
"s": 2905,
"text": "We should understand that Streamlit supports the connection to many different kinds of database, but online database hosts are not typically free. To provide you with a proof of concept, we’ll use a public Google Sheet as the data source for our web app. Suppose that our sheet has the following data."
},
{
"code": null,
"e": 3319,
"s": 3207,
"text": "Once you create the Google sheet, please turn on sharing publicly such that our web app can access it directly."
},
{
"code": null,
"e": 3578,
"s": 3319,
"text": "IMPORTANT: To keep the app simple, we’ll only consider the set-up that uses a public Google Sheet. If you want to use a private Google Sheet, it requires enabling Google APIs and interested readers can refer to Streamlit’s website for additional instruction."
},
{
"code": null,
"e": 3770,
"s": 3578,
"text": "To access the Google sheet programmatically, we need to install the package gsheetsdb by running pip install gsheetsdb. Once it’s installed, we can update our script to the following version:"
},
{
"code": null,
"e": 3817,
"s": 3770,
"text": "The above code involves the following changes:"
},
{
"code": null,
"e": 3874,
"s": 3817,
"text": "We use the gsheetsdb for connecting to the Google sheet."
},
{
"code": null,
"e": 4087,
"s": 3874,
"text": "To use the sheet, we use a SQL-like syntax to retrieve the data. Notably, instead of specifying the sheet’s name, we need to specify the URL to the sheet. Don’t forget about the double quotes for the sheet’s URL."
},
{
"code": null,
"e": 4141,
"s": 4087,
"text": "We create a DataFrame object from the retrieved rows."
},
{
"code": null,
"e": 4293,
"s": 4141,
"text": "With all these changes, our web app looks like the following now. As you can see, we’re indeed able to retrieve the data from the created Google sheet."
},
{
"code": null,
"e": 4602,
"s": 4293,
"text": "There are different options to host a Streamlit app, such as Heroku (You can find a tutorial in a Medium article). Here, I want to show you to use Streamlit Share — a free Streamlit web app sharing service provided by Streamlit. You can find more information at its official blog. Here are the general steps."
},
{
"code": null,
"e": 5052,
"s": 4602,
"text": "Because the Streamlit team is still developing the platform, you need to request an invite to be able to deploy the app on Streamlit Share. You can submit a request here: https://streamlit.io/cloudOnce you submit your request, it won’t take too long for them to approve your request. In my case, it took less than one day to receive the invite.You can now login into the Streamlit Share (https://share.streamlit.io/) with your GitHub authentication."
},
{
"code": null,
"e": 5250,
"s": 5052,
"text": "Because the Streamlit team is still developing the platform, you need to request an invite to be able to deploy the app on Streamlit Share. You can submit a request here: https://streamlit.io/cloud"
},
{
"code": null,
"e": 5398,
"s": 5250,
"text": "Once you submit your request, it won’t take too long for them to approve your request. In my case, it took less than one day to receive the invite."
},
{
"code": null,
"e": 5504,
"s": 5398,
"text": "You can now login into the Streamlit Share (https://share.streamlit.io/) with your GitHub authentication."
},
{
"code": null,
"e": 5769,
"s": 5504,
"text": "As you’ll see next, we’ll share our app in a public GitHub repository, and thus we don’t want to expose the Google sheet URL, which can be a potential security concern. Certainly, using a private Google Sheet or other databases with authentications is more secure."
},
{
"code": null,
"e": 5923,
"s": 5769,
"text": "Instead of specifying the URL in the script directly, you’ll save the URL in a shared app’s settings, from which you can access using the setting’s name."
},
{
"code": null,
"e": 6050,
"s": 5923,
"text": "# Originalgsheet_url = \"the_link\"# Updated, when the URL is saved in the settingsgsheet_url = st.secrets[\"public_gsheets_url\"]"
},
{
"code": null,
"e": 6340,
"s": 6050,
"text": "Once you update your script, it’s finally the time to make your app public (to some extent). What you’ll do is to create a public GitHub repository. I’m not going to expand how you can do that here. I use PyCharm, and I just need to use the built-in Git tool to create a repository easily."
},
{
"code": null,
"e": 6482,
"s": 6340,
"text": "Go to the Streamlit Share website, you can create a new web app by clicking “New App”, which will pop up the window shown below (left panel)."
},
{
"code": null,
"e": 6652,
"s": 6482,
"text": "If you’ve already linked your GitHub account, Streamlit is smart enough to pull out the list of repositories and you can simply choose the one and specify the file path."
},
{
"code": null,
"e": 6948,
"s": 6652,
"text": "Importantly, you click the “Advanced settings” and specify the link there, because as mentioned previously, this is how our streamlit script file accesses the confidential information. When needed, you need to choose a proper Python version for your project, because by default, it’s set to 3.7."
},
{
"code": null,
"e": 7080,
"s": 6948,
"text": "After that, click the “Deploy!” button, and wait for a couple of moments, and you should be able to see your app is up and running!"
},
{
"code": null,
"e": 7240,
"s": 7080,
"text": "Because it’s hosted by Streamlit Share as a public website, you can share the link to your teammates or clients and they can access it from anywhere they want."
},
{
"code": null,
"e": 7448,
"s": 7240,
"text": "Streamlit has made web app developments easy for data scientists, because it takes care of the layout of the web elements, and we data scientists are just responsible for the core part of our app — the data."
},
{
"code": null,
"e": 7549,
"s": 7448,
"text": "If you have never tried Streamlit, I strongly recommend you give it a try, and I bet you’ll love it."
}
] |
How to compare Year, Month and Day in a MySQL query and display matching records
|
For this, you can use DATE(). Let us first create a table −
mysql> create table DemoTable864(DueDateTime timestamp);
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable864 values('2019-01-10 12 −34 −55');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable864 values('2016-12-11 11 −12 −00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable864 values('2015-04-01 10 −00 −00');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable864 values('2017-05-20 04 −40 −10');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable864;
This will produce the following output −
+---------------------+
| DueDateTime |
+---------------------+
|2019-01-10 12 −34 −55|
|2016-12-11 11 −12 −00|
|2015-04-01 10 −00 −00|
|2017-05-20 04 −40 −10|
+---------------------+
4 rows in set (0.00 sec)
Following is the query to compare year, month and day −
mysql> select *from DemoTable864 where date(DueDateTime)='2015-04-01';
This will produce the following output −
+-----------------------+
| DueDateTime |
+-----------------------+
| 2015-04-01 10 −00 −00 |
+-----------------------+
1 row in set (0.04 sec)
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "For this, you can use DATE(). Let us first create a table −"
},
{
"code": null,
"e": 1216,
"s": 1122,
"text": "mysql> create table DemoTable864(DueDateTime timestamp);\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1272,
"s": 1216,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1676,
"s": 1272,
"text": "mysql> insert into DemoTable864 values('2019-01-10 12 −34 −55');\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into DemoTable864 values('2016-12-11 11 −12 −00');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable864 values('2015-04-01 10 −00 −00');\nQuery OK, 1 row affected (0.28 sec)\nmysql> insert into DemoTable864 values('2017-05-20 04 −40 −10');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1736,
"s": 1676,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1770,
"s": 1736,
"text": "mysql> select *from DemoTable864;"
},
{
"code": null,
"e": 1811,
"s": 1770,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2028,
"s": 1811,
"text": "+---------------------+\n| DueDateTime |\n+---------------------+\n|2019-01-10 12 −34 −55|\n|2016-12-11 11 −12 −00|\n|2015-04-01 10 −00 −00|\n|2017-05-20 04 −40 −10|\n+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2084,
"s": 2028,
"text": "Following is the query to compare year, month and day −"
},
{
"code": null,
"e": 2155,
"s": 2084,
"text": "mysql> select *from DemoTable864 where date(DueDateTime)='2015-04-01';"
},
{
"code": null,
"e": 2196,
"s": 2155,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2350,
"s": 2196,
"text": "+-----------------------+\n| DueDateTime |\n+-----------------------+\n| 2015-04-01 10 −00 −00 |\n+-----------------------+\n1 row in set (0.04 sec)"
}
] |
Construct a DataFrame in Pandas using string data - GeeksforGeeks
|
26 Jan, 2019
As we know that data comes in all shapes and sizes. They often come from various different sources having different formats. For an aspiring data scientist, it is very important that they know their way around data i.e. loading and storing data present in various formats.
We have some data present in string format, discuss ways to load that data into pandas dataframe.
Solution #1: One way to achieve this is by using the StringIO() function. It will act as a wrapper and it will help use read the data using the pd.read_csv() function.
# importing pandas as pdimport pandas as pd # import the StrinIO function# from io modulefrom io import StringIO # wrap the string data in StringIO functionStringData = StringIO("""Date;Event;Cost 10/2/2011;Music;10000 11/2/2011;Poetry;12000 12/2/2011;Theatre;5000 13/2/2011;Comedy;8000 """) # let's read the data using the Pandas# read_csv() functiondf = pd.read_csv(StringData, sep =";") # Print the dataframeprint(df)
Output :As we can see in the output, we have successfully read the given data in string format into a Pandas DataFrame. Solution 2 : Another fantastic approach is to use the pandas pd.read_clipboard() function.
# importing pandas as pdimport pandas as pd # This is our string dataStringData ="""Date;Event;Cost 10/2/2011;Music;10000 11/2/2011;Poetry;12000 12/2/2011;Theatre;5000 13/2/2011;Comedy;8000 """ # Now we copy the data to our clipboard.
Output :This is what it looks like after we copy the data to clipboard.
Now we will use pandas pd.read_clipboard() function to read the data into a DataFrame
# Read data df = pd.read_clipboard(sep = ';') # Print the DataFrameprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n26 Jan, 2019"
},
{
"code": null,
"e": 24991,
"s": 24718,
"text": "As we know that data comes in all shapes and sizes. They often come from various different sources having different formats. For an aspiring data scientist, it is very important that they know their way around data i.e. loading and storing data present in various formats."
},
{
"code": null,
"e": 25089,
"s": 24991,
"text": "We have some data present in string format, discuss ways to load that data into pandas dataframe."
},
{
"code": null,
"e": 25257,
"s": 25089,
"text": "Solution #1: One way to achieve this is by using the StringIO() function. It will act as a wrapper and it will help use read the data using the pd.read_csv() function."
},
{
"code": "# importing pandas as pdimport pandas as pd # import the StrinIO function# from io modulefrom io import StringIO # wrap the string data in StringIO functionStringData = StringIO(\"\"\"Date;Event;Cost 10/2/2011;Music;10000 11/2/2011;Poetry;12000 12/2/2011;Theatre;5000 13/2/2011;Comedy;8000 \"\"\") # let's read the data using the Pandas# read_csv() functiondf = pd.read_csv(StringData, sep =\";\") # Print the dataframeprint(df)",
"e": 25697,
"s": 25257,
"text": null
},
{
"code": null,
"e": 25908,
"s": 25697,
"text": "Output :As we can see in the output, we have successfully read the given data in string format into a Pandas DataFrame. Solution 2 : Another fantastic approach is to use the pandas pd.read_clipboard() function."
},
{
"code": "# importing pandas as pdimport pandas as pd # This is our string dataStringData =\"\"\"Date;Event;Cost 10/2/2011;Music;10000 11/2/2011;Poetry;12000 12/2/2011;Theatre;5000 13/2/2011;Comedy;8000 \"\"\" # Now we copy the data to our clipboard.",
"e": 26160,
"s": 25908,
"text": null
},
{
"code": null,
"e": 26232,
"s": 26160,
"text": "Output :This is what it looks like after we copy the data to clipboard."
},
{
"code": null,
"e": 26318,
"s": 26232,
"text": "Now we will use pandas pd.read_clipboard() function to read the data into a DataFrame"
},
{
"code": "# Read data df = pd.read_clipboard(sep = ';') # Print the DataFrameprint(df)",
"e": 26396,
"s": 26318,
"text": null
},
{
"code": null,
"e": 26405,
"s": 26396,
"text": "Output :"
},
{
"code": null,
"e": 26430,
"s": 26405,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 26454,
"s": 26430,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26468,
"s": 26454,
"text": "Python-pandas"
},
{
"code": null,
"e": 26475,
"s": 26468,
"text": "Python"
},
{
"code": null,
"e": 26573,
"s": 26475,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26582,
"s": 26573,
"text": "Comments"
},
{
"code": null,
"e": 26595,
"s": 26582,
"text": "Old Comments"
},
{
"code": null,
"e": 26613,
"s": 26595,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26635,
"s": 26613,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26665,
"s": 26635,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26700,
"s": 26665,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26721,
"s": 26700,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26763,
"s": 26721,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26788,
"s": 26763,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26820,
"s": 26788,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26836,
"s": 26820,
"text": "Stack in Python"
}
] |
Pytorch Training Tricks and Tips. Tricks/Tips for optimizing the training... | by Saketh Kotamraju | Towards Data Science
|
In this article, I will describe and show the code for 4 different Pytorch training tricks that I personally have found to improve the training of my deep learning model.
In a regular training loop, PyTorch stores all float variables in 32-bit precision. For people who are training their models with strict constraints, sometimes, this can cause their model to take up too much memory, forcing them to have a slower training process with a smaller model and a smaller batch size. However, storing all the variables/numbers in the model in 16-bit precision can improve upon and fix most of these problems, like dramatically decreasing the memory consumption of the model and speeding up the training loop while still maintaining the same performance/accuracy of the model.
Converting all calculations to 16-bit precision in Pytorch is very simple to do and only requires a few lines of code. Here is how:
scaler = torch.cuda.amp.GradScaler()
Create a gradient scaler the same way that I have done above. Do this before you write your training loop.
optimizer.zero_grad()with torch.cuda.amp.autocast(): output = model(input).to(device) loss = criterion(output, correct_answer).to(device)scaler.scale(loss).backward()scaler.step(optimizer)scaler.update()
When you are doing backward propagation with loss and the optimizer, instead of doing loss.backward() and optimizer.step(), you need to do scaler.scale(loss).backward and scaler.step(optimizer). This allows your scaler to convert all the gradients and do all the calculations in 16-bit precision.
When you are doing everything with 16-bit precision, there may be some numerical instability that causes some functions that you may use to not work properly. Only certain operations work correctly in 16-bit precision. Here is more information on this.
Having a progress bar that represents what percentage of the training for each epoch has been done can be very useful. To get a progress bar, we will use the tqdm library. Here is how you can download and import it:
pip install tqdmfrom tqdm import tqdm
On your training and validation loops, you have to do this:
for index, batch in tqdm(enumerate(loader), total = len(loader), position = 0, leave = True):
And that’s it. Once you do this for your training and validation loops, you will get a progress bar that represents what percentage of the training your model has completed. It should look something like this:
In the picture, 691 represents how many batches my model had to complete, 7:28 represents the total time that my model took to train/evaluate on the 691 batches, and 1.54 it/s represents the average time it took my model for one batch.
If you run into a CUDA out of memory error, this means that you have exceeded your computational resources. To fix this, there are several things you can do, including converting everything to 16-bit precision as I mentioned above, reducing the batch size of your model, and reducing the num_workers parameter when creating your Dataloaders:
train_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, num_workers=0)
However, sometimes, switching to 16-bit precision and reducing num_workers may not completely fix the problem. The most direct way to fix the problem is to reduce your batch size, but suppose that you don’t want to reduce your batch size. If you don’t want to reduce your batch size, you can use gradient accumulation to stimulate your desired batch size. Note that another solution to the CUDA out of memory issue is simply to use more than one GPU, but this is an option not accessible to many people.
Suppose that your machine/model can only support a batch size of 16 and increasing it results in a CUDA out of memory error, and you want to have a batch size of 32. Gradient accumulation works by running the model with a batch size of 16 twice, accumulating the gradients computed for each batch, and finally doing an optimizer step after those 2 forward passes and accumulation of gradients.
To understand gradient accumulation, it is important to understand what specific functions are done in training a neural network. Suppose you have the following training loop:
model = model.train()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) optimizer.zero_grad() output = model(input).to(device) loss = criterion(output, correct_answer).to(device) loss.backward() optimizer.step()
Looking at the code above, the key thing to remember is that loss.backward() creates and stores the gradients for the model, but optimizer.step() actually updates the weights. Calling loss.backward() twice before calling optimizer accumulates the gradients. Here is how you can implement gradient accumulation in PyTorch:
model = model.train()optimizer.zero_grad()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) output = model(input).to(device) loss = criterion(output, correct_answer).to(device) loss.backward() if (index+1) % 2 == 0: optimizer.step() optimizer.zero_grad()
As you can see, taking the example above where our machine can only support a batch size of 16 and we want a batch size of 32, we essentially compute the gradients for 2 batches and then update the actual weights. This results in an effective batch size of 32.
Doing gradient accumulation with 16-bit precision is very similar.
model = model.train()optimizer.zero_grad()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) with torch.cuda.amp.autocast(): output = model(input).to(device) loss = criterion(output, correct_answer).to(device) scaler.scale(loss).backward() if (index+1) % 2 == 0: scaler.step(optimizer) scaler.update() optimizer.zero_grad()
In most machine learning projects, people tend to manually calculate the metrics that they are using for evaluation, and then report them. Although calculating metrics like accuracy, precision, recall, and F1 is not hard, there are certain instances where you may want to have certain variants of these metrics, like macro/micro precision, recall, and F1, or weighted precision, recall, and F1. Calculating these can be a bit more work, and sometimes, your implementation may be incorrect. To calculate all these metrics, efficiently, fast, and without errors, you can use sklearns classification_report library. This is a specific library that is designed towards calculating these metrics. Here is how you can use it.
from sklearn.metrics import classification_reporty_pred = [0, 1, 0, 0, 1]y_correct = [1, 1, 0, 1, 1]print(classification_report(y_correct, y_pred))
The code above is for binary classification. You can configure/use this function for more purposes. The first list represents the model’s predictions, and the second list represents the correct answers. The code above would output:
In this article, I discussed 4 ways to optimize your training of deep neural networks. 16-bit precision reduces your memory consumption, gradient accumulation allows you to work around any memory constraints you may have by stimulating a larger batch size, and the tqdm progress bar and sklearns classification report libraries are two convenient libraries that allow you to easily track your model’s training and evaluate your model’s performance. Personally, I always train my neural networks with all of the training tricks above, and I use gradient accumulation whenever it is necessary.
I hope you found this content easy to understand and informative. If you have any questions, let me know in the comments.
|
[
{
"code": null,
"e": 343,
"s": 172,
"text": "In this article, I will describe and show the code for 4 different Pytorch training tricks that I personally have found to improve the training of my deep learning model."
},
{
"code": null,
"e": 945,
"s": 343,
"text": "In a regular training loop, PyTorch stores all float variables in 32-bit precision. For people who are training their models with strict constraints, sometimes, this can cause their model to take up too much memory, forcing them to have a slower training process with a smaller model and a smaller batch size. However, storing all the variables/numbers in the model in 16-bit precision can improve upon and fix most of these problems, like dramatically decreasing the memory consumption of the model and speeding up the training loop while still maintaining the same performance/accuracy of the model."
},
{
"code": null,
"e": 1077,
"s": 945,
"text": "Converting all calculations to 16-bit precision in Pytorch is very simple to do and only requires a few lines of code. Here is how:"
},
{
"code": null,
"e": 1114,
"s": 1077,
"text": "scaler = torch.cuda.amp.GradScaler()"
},
{
"code": null,
"e": 1221,
"s": 1114,
"text": "Create a gradient scaler the same way that I have done above. Do this before you write your training loop."
},
{
"code": null,
"e": 1429,
"s": 1221,
"text": "optimizer.zero_grad()with torch.cuda.amp.autocast(): output = model(input).to(device) loss = criterion(output, correct_answer).to(device)scaler.scale(loss).backward()scaler.step(optimizer)scaler.update()"
},
{
"code": null,
"e": 1726,
"s": 1429,
"text": "When you are doing backward propagation with loss and the optimizer, instead of doing loss.backward() and optimizer.step(), you need to do scaler.scale(loss).backward and scaler.step(optimizer). This allows your scaler to convert all the gradients and do all the calculations in 16-bit precision."
},
{
"code": null,
"e": 1979,
"s": 1726,
"text": "When you are doing everything with 16-bit precision, there may be some numerical instability that causes some functions that you may use to not work properly. Only certain operations work correctly in 16-bit precision. Here is more information on this."
},
{
"code": null,
"e": 2195,
"s": 1979,
"text": "Having a progress bar that represents what percentage of the training for each epoch has been done can be very useful. To get a progress bar, we will use the tqdm library. Here is how you can download and import it:"
},
{
"code": null,
"e": 2233,
"s": 2195,
"text": "pip install tqdmfrom tqdm import tqdm"
},
{
"code": null,
"e": 2293,
"s": 2233,
"text": "On your training and validation loops, you have to do this:"
},
{
"code": null,
"e": 2387,
"s": 2293,
"text": "for index, batch in tqdm(enumerate(loader), total = len(loader), position = 0, leave = True):"
},
{
"code": null,
"e": 2597,
"s": 2387,
"text": "And that’s it. Once you do this for your training and validation loops, you will get a progress bar that represents what percentage of the training your model has completed. It should look something like this:"
},
{
"code": null,
"e": 2833,
"s": 2597,
"text": "In the picture, 691 represents how many batches my model had to complete, 7:28 represents the total time that my model took to train/evaluate on the 691 batches, and 1.54 it/s represents the average time it took my model for one batch."
},
{
"code": null,
"e": 3175,
"s": 2833,
"text": "If you run into a CUDA out of memory error, this means that you have exceeded your computational resources. To fix this, there are several things you can do, including converting everything to 16-bit precision as I mentioned above, reducing the batch size of your model, and reducing the num_workers parameter when creating your Dataloaders:"
},
{
"code": null,
"e": 3273,
"s": 3175,
"text": "train_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, num_workers=0)"
},
{
"code": null,
"e": 3777,
"s": 3273,
"text": "However, sometimes, switching to 16-bit precision and reducing num_workers may not completely fix the problem. The most direct way to fix the problem is to reduce your batch size, but suppose that you don’t want to reduce your batch size. If you don’t want to reduce your batch size, you can use gradient accumulation to stimulate your desired batch size. Note that another solution to the CUDA out of memory issue is simply to use more than one GPU, but this is an option not accessible to many people."
},
{
"code": null,
"e": 4171,
"s": 3777,
"text": "Suppose that your machine/model can only support a batch size of 16 and increasing it results in a CUDA out of memory error, and you want to have a batch size of 32. Gradient accumulation works by running the model with a batch size of 16 twice, accumulating the gradients computed for each batch, and finally doing an optimizer step after those 2 forward passes and accumulation of gradients."
},
{
"code": null,
"e": 4347,
"s": 4171,
"text": "To understand gradient accumulation, it is important to understand what specific functions are done in training a neural network. Suppose you have the following training loop:"
},
{
"code": null,
"e": 4639,
"s": 4347,
"text": "model = model.train()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) optimizer.zero_grad() output = model(input).to(device) loss = criterion(output, correct_answer).to(device) loss.backward() optimizer.step()"
},
{
"code": null,
"e": 4961,
"s": 4639,
"text": "Looking at the code above, the key thing to remember is that loss.backward() creates and stores the gradients for the model, but optimizer.step() actually updates the weights. Calling loss.backward() twice before calling optimizer accumulates the gradients. Here is how you can implement gradient accumulation in PyTorch:"
},
{
"code": null,
"e": 5306,
"s": 4961,
"text": "model = model.train()optimizer.zero_grad()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) output = model(input).to(device) loss = criterion(output, correct_answer).to(device) loss.backward() if (index+1) % 2 == 0: optimizer.step() optimizer.zero_grad()"
},
{
"code": null,
"e": 5567,
"s": 5306,
"text": "As you can see, taking the example above where our machine can only support a batch size of 16 and we want a batch size of 32, we essentially compute the gradients for 2 batches and then update the actual weights. This results in an effective batch size of 32."
},
{
"code": null,
"e": 5634,
"s": 5567,
"text": "Doing gradient accumulation with 16-bit precision is very similar."
},
{
"code": null,
"e": 6066,
"s": 5634,
"text": "model = model.train()optimizer.zero_grad()for index, batch in enumerate(train_loader): input = batch[0].to(device) correct_answer = batch[1].to(device) with torch.cuda.amp.autocast(): output = model(input).to(device) loss = criterion(output, correct_answer).to(device) scaler.scale(loss).backward() if (index+1) % 2 == 0: scaler.step(optimizer) scaler.update() optimizer.zero_grad()"
},
{
"code": null,
"e": 6786,
"s": 6066,
"text": "In most machine learning projects, people tend to manually calculate the metrics that they are using for evaluation, and then report them. Although calculating metrics like accuracy, precision, recall, and F1 is not hard, there are certain instances where you may want to have certain variants of these metrics, like macro/micro precision, recall, and F1, or weighted precision, recall, and F1. Calculating these can be a bit more work, and sometimes, your implementation may be incorrect. To calculate all these metrics, efficiently, fast, and without errors, you can use sklearns classification_report library. This is a specific library that is designed towards calculating these metrics. Here is how you can use it."
},
{
"code": null,
"e": 6934,
"s": 6786,
"text": "from sklearn.metrics import classification_reporty_pred = [0, 1, 0, 0, 1]y_correct = [1, 1, 0, 1, 1]print(classification_report(y_correct, y_pred))"
},
{
"code": null,
"e": 7166,
"s": 6934,
"text": "The code above is for binary classification. You can configure/use this function for more purposes. The first list represents the model’s predictions, and the second list represents the correct answers. The code above would output:"
},
{
"code": null,
"e": 7758,
"s": 7166,
"text": "In this article, I discussed 4 ways to optimize your training of deep neural networks. 16-bit precision reduces your memory consumption, gradient accumulation allows you to work around any memory constraints you may have by stimulating a larger batch size, and the tqdm progress bar and sklearns classification report libraries are two convenient libraries that allow you to easily track your model’s training and evaluate your model’s performance. Personally, I always train my neural networks with all of the training tricks above, and I use gradient accumulation whenever it is necessary."
}
] |
Split String with Comma (,) in Java
|
Let’s say the following is our string.
String str = " This is demo text, and demo line!";
To split a string with comma, use the split() method in Java.
str.split("[,]", 0);
The following is the complete example.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "This is demo text, and demo line!";
String[] res = str.split("[,]", 0);
for(String myStr: res) {
System.out.println(myStr);
}
}
}
This is demo text
and demo line!
|
[
{
"code": null,
"e": 1101,
"s": 1062,
"text": "Let’s say the following is our string."
},
{
"code": null,
"e": 1152,
"s": 1101,
"text": "String str = \" This is demo text, and demo line!\";"
},
{
"code": null,
"e": 1214,
"s": 1152,
"text": "To split a string with comma, use the split() method in Java."
},
{
"code": null,
"e": 1235,
"s": 1214,
"text": "str.split(\"[,]\", 0);"
},
{
"code": null,
"e": 1274,
"s": 1235,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1285,
"s": 1274,
"text": " Live Demo"
},
{
"code": null,
"e": 1536,
"s": 1285,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"This is demo text, and demo line!\";\n String[] res = str.split(\"[,]\", 0);\n for(String myStr: res) {\n System.out.println(myStr);\n }\n }\n}"
},
{
"code": null,
"e": 1569,
"s": 1536,
"text": "This is demo text\nand demo line!"
}
] |
How to see if a widget exists in Tkinter?
|
To make a particular Tkinter application fully functional and operational, we can use as many widgets as we want. If we want to check if a widget exists or not, then we can use the winfo_exists() method. The method can be invoked with the particular widget we want to check. It returns a Boolean value where True(1) specifies that the widget exists in the application, and False(0) specifies that the widget doesn't exist in the application.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x250")
# Define a function to check if a widget exists or not
def check_widget():
exists = label.winfo_exists()
if exists == 1:
print("The widget exists.")
else:
print("The widget does not exist.")
# Create a Label widget
label = Label(win, text="Hey There! Howdy?", font=('Helvetica 18 bold'))
label.place(relx=.5, rely=.3, anchor=CENTER)
# We will define a button to check if a widget exists or not
button = ttk.Button(win, text="Check", command=check_widget)
button.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()
Running the above code will display a window with a button and a label widget. In the application, we can check if the label widget is present or not.
If you click the button "Check", it will print whether the label widget exists or not.
The widget exists.
|
[
{
"code": null,
"e": 1504,
"s": 1062,
"text": "To make a particular Tkinter application fully functional and operational, we can use as many widgets as we want. If we want to check if a widget exists or not, then we can use the winfo_exists() method. The method can be invoked with the particular widget we want to check. It returns a Boolean value where True(1) specifies that the widget exists in the application, and False(0) specifies that the widget doesn't exist in the application."
},
{
"code": null,
"e": 2217,
"s": 1504,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of Tkinter Frame\nwin = Tk()\n\n# Set the geometry\nwin.geometry(\"700x250\")\n\n# Define a function to check if a widget exists or not\ndef check_widget():\n exists = label.winfo_exists()\n if exists == 1:\n print(\"The widget exists.\")\n else:\n print(\"The widget does not exist.\")\n\n# Create a Label widget\nlabel = Label(win, text=\"Hey There! Howdy?\", font=('Helvetica 18 bold'))\nlabel.place(relx=.5, rely=.3, anchor=CENTER)\n\n# We will define a button to check if a widget exists or not\nbutton = ttk.Button(win, text=\"Check\", command=check_widget)\nbutton.place(relx=.5, rely=.5, anchor=CENTER)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2368,
"s": 2217,
"text": "Running the above code will display a window with a button and a label widget. In the application, we can check if the label widget is present or not."
},
{
"code": null,
"e": 2455,
"s": 2368,
"text": "If you click the button \"Check\", it will print whether the label widget exists or not."
},
{
"code": null,
"e": 2474,
"s": 2455,
"text": "The widget exists."
}
] |
LPAD() Function in MySQL
|
21 Jun, 2021
LPAD() function in MySQL is used to pad or add a string to the left side of the original string.
Syntax :
LPAD(str, len, padstr)
Parameter : This function accepts three parameter as mentioned above and described below –
str – The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string.
len – This is the length of a final string after the left padding.
padstr – String that to be added to the left side of the Original Str.
Returns : It returns a new string of length len after padding.
Example-1 : Applying LPAD() Function to a string to get a new padded string.
SELECT LPAD("geeksforgeeks", 20, "*") AS LeftPaddedString;
Output :
Example-2 : Applying LPAD() Function to a string when the original string is larger than the len parameter.
SELECT LPAD("geeksforgeeks", 10, "*") AS LeftPaddedString;
Output :
Example-3 : LPAD Function can also be used to add a string for column data. To demonstrate create a table named Student.
CREATE TABLE Student
(
Student_id INT AUTO_INCREMENT,
Student_name VARCHAR(100) NOT NULL,
Student_Class VARCHAR(20) NOT NULL,
PRIMARY KEY(Student_id )
);
Now inserting some data to the Student table :
INSERT INTO Student
(Student_name, Student_Class)
VALUES
('Ananya Majumdar', 'IX'),
('Anushka Samanta', 'X'),
('Aniket Sharma', 'XI'),
('Anik Das', 'X'),
('Riya Jain', 'IX'),
('Tapan Samanta', 'X');
So, the Student Table is as follows.
Now, we are going to add some string to every string presented in the Student_Class column.
SELECT Student_id, Student_name,
LPAD(Student_Class, 10, ' _') AS LeftPaddedString
FROM Student;
Output :
sumitgumber28
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 151,
"s": 53,
"text": "LPAD() function in MySQL is used to pad or add a string to the left side of the original string. "
},
{
"code": null,
"e": 162,
"s": 151,
"text": "Syntax : "
},
{
"code": null,
"e": 185,
"s": 162,
"text": "LPAD(str, len, padstr)"
},
{
"code": null,
"e": 278,
"s": 185,
"text": "Parameter : This function accepts three parameter as mentioned above and described below – "
},
{
"code": null,
"e": 461,
"s": 278,
"text": "str – The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string. "
},
{
"code": null,
"e": 532,
"s": 463,
"text": "len – This is the length of a final string after the left padding. "
},
{
"code": null,
"e": 607,
"s": 534,
"text": "padstr – String that to be added to the left side of the Original Str. "
},
{
"code": null,
"e": 673,
"s": 609,
"text": "Returns : It returns a new string of length len after padding. "
},
{
"code": null,
"e": 752,
"s": 673,
"text": "Example-1 : Applying LPAD() Function to a string to get a new padded string. "
},
{
"code": null,
"e": 811,
"s": 752,
"text": "SELECT LPAD(\"geeksforgeeks\", 20, \"*\") AS LeftPaddedString;"
},
{
"code": null,
"e": 821,
"s": 811,
"text": "Output : "
},
{
"code": null,
"e": 933,
"s": 823,
"text": "Example-2 : Applying LPAD() Function to a string when the original string is larger than the len parameter. "
},
{
"code": null,
"e": 992,
"s": 933,
"text": "SELECT LPAD(\"geeksforgeeks\", 10, \"*\") AS LeftPaddedString;"
},
{
"code": null,
"e": 1002,
"s": 992,
"text": "Output : "
},
{
"code": null,
"e": 1126,
"s": 1004,
"text": "Example-3 : LPAD Function can also be used to add a string for column data. To demonstrate create a table named Student. "
},
{
"code": null,
"e": 1284,
"s": 1128,
"text": "CREATE TABLE Student\n(\nStudent_id INT AUTO_INCREMENT, \nStudent_name VARCHAR(100) NOT NULL,\nStudent_Class VARCHAR(20) NOT NULL,\nPRIMARY KEY(Student_id )\n);"
},
{
"code": null,
"e": 1333,
"s": 1284,
"text": "Now inserting some data to the Student table : "
},
{
"code": null,
"e": 1532,
"s": 1333,
"text": "INSERT INTO Student\n(Student_name, Student_Class)\nVALUES\n('Ananya Majumdar', 'IX'),\n('Anushka Samanta', 'X'),\n('Aniket Sharma', 'XI'),\n('Anik Das', 'X'),\n('Riya Jain', 'IX'),\n('Tapan Samanta', 'X');"
},
{
"code": null,
"e": 1570,
"s": 1532,
"text": "So, the Student Table is as follows. "
},
{
"code": null,
"e": 1665,
"s": 1572,
"text": "Now, we are going to add some string to every string presented in the Student_Class column. "
},
{
"code": null,
"e": 1764,
"s": 1667,
"text": "SELECT Student_id, Student_name,\nLPAD(Student_Class, 10, ' _') AS LeftPaddedString\nFROM Student;"
},
{
"code": null,
"e": 1774,
"s": 1764,
"text": "Output : "
},
{
"code": null,
"e": 1792,
"s": 1778,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1801,
"s": 1792,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1807,
"s": 1801,
"text": "mysql"
},
{
"code": null,
"e": 1811,
"s": 1807,
"text": "SQL"
},
{
"code": null,
"e": 1815,
"s": 1811,
"text": "SQL"
},
{
"code": null,
"e": 1913,
"s": 1815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1979,
"s": 1913,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2003,
"s": 1979,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2035,
"s": 2003,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2068,
"s": 2035,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "SQL using Python"
},
{
"code": null,
"e": 2115,
"s": 2085,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2193,
"s": 2115,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2229,
"s": 2193,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2260,
"s": 2229,
"text": "SQL Query to Compare Two Dates"
}
] |
How to convert a pixel value to a number value using JavaScript ?
|
11 Oct, 2019
The task is to convert the string value containing ‘px’ to the Integer Value with the help of JavaScript. Here, Few approaches are discussed.Approach 1:
Use parseInt() method which takes string as first argument and return the Integer value.
Example 1: This example uses approach as discussed above
<!DOCTYPE HTML><html> <head> <title> Convert a pixel value to a number value using JavaScript. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var n = el_up.style.fontSize; el_up.innerHTML = "Click on the button to get the number value "+ "from pixel value.<br>Pixel Value - '" + n + "'"; function GFG_Fun() { el_down.innerHTML = "Integer value is " + parseInt(n, 10); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Use RegExp which replaces the ‘px’ by empty string and then convert the result to Integer using Number().
Example 2: This example uses approach as discussed above.
<!DOCTYPE HTML><html> <head> <title> Convert a pixel value to a number value using JavaScript. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var n = el_up.style.fontSize; el_up.innerHTML = "Click on the button to get the "+ "number value from pixel value.<br>Pixel Value - '" + n + "'"; function GFG_Fun() { el_down.innerHTML = "Integer value is " + Number(n.replace(/px$/, '')); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "The task is to convert the string value containing ‘px’ to the Integer Value with the help of JavaScript. Here, Few approaches are discussed.Approach 1:"
},
{
"code": null,
"e": 270,
"s": 181,
"text": "Use parseInt() method which takes string as first argument and return the Integer value."
},
{
"code": null,
"e": 327,
"s": 270,
"text": "Example 1: This example uses approach as discussed above"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Convert a pixel value to a number value using JavaScript. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var n = el_up.style.fontSize; el_up.innerHTML = \"Click on the button to get the number value \"+ \"from pixel value.<br>Pixel Value - '\" + n + \"'\"; function GFG_Fun() { el_down.innerHTML = \"Integer value is \" + parseInt(n, 10); } </script></body> </html>",
"e": 1245,
"s": 327,
"text": null
},
{
"code": null,
"e": 1253,
"s": 1245,
"text": "Output:"
},
{
"code": null,
"e": 1284,
"s": 1253,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1314,
"s": 1284,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1326,
"s": 1314,
"text": "Approach 2:"
},
{
"code": null,
"e": 1432,
"s": 1326,
"text": "Use RegExp which replaces the ‘px’ by empty string and then convert the result to Integer using Number()."
},
{
"code": null,
"e": 1490,
"s": 1432,
"text": "Example 2: This example uses approach as discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Convert a pixel value to a number value using JavaScript. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var n = el_up.style.fontSize; el_up.innerHTML = \"Click on the button to get the \"+ \"number value from pixel value.<br>Pixel Value - '\" + n + \"'\"; function GFG_Fun() { el_down.innerHTML = \"Integer value is \" + Number(n.replace(/px$/, '')); } </script></body> </html>",
"e": 2426,
"s": 1490,
"text": null
},
{
"code": null,
"e": 2434,
"s": 2426,
"text": "Output:"
},
{
"code": null,
"e": 2465,
"s": 2434,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2495,
"s": 2465,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2511,
"s": 2495,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2522,
"s": 2511,
"text": "JavaScript"
},
{
"code": null,
"e": 2539,
"s": 2522,
"text": "Web Technologies"
},
{
"code": null,
"e": 2566,
"s": 2539,
"text": "Web technologies Questions"
}
] |
First element occurring k times in an array
|
30 Jun, 2022
Given an array of n integers. The task is to find the first element that occurs k number of times. If no element occurs k times the print -1. The distribution of integer elements could be in any range.Examples:
Input: {1, 7, 4, 3, 4, 8, 7}, k = 2 Output: 7 Explaination: Both 7 and 4 occur 2 times. But 7 is the first that occurs 2 times.
Input: {4, 1, 6, 1, 6, 4}, k = 1 Output: -1
Naive Approach: The idea is to use two nested loops. one for the selection of element and other for counting the number of time the selected element occurs in the given array.
Below is the implementation of the above approach:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // Function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } // Check, if it occurs k times or not if (count == k) return arr[i]; } return -1;} // Driver Codeint main(){ int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0;}
public class GFG { // Java implementation to find first // element occurring k times // Function to find the first element // occurring k number of times public static int firstElement(int[] arr, int n, int k) { // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } // Check, if it occurs k times or not if (count == k) { return arr[i]; } } return -1; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 7, 4, 3, 4, 8, 7 }; int n = arr.length; int k = 2; System.out.print(firstElement(arr, n, k)); }} // This code is contributed by Aarti_Rathi
# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k): # dictionary to count # occurrences of # each element for i in arr: count=0 for j in arr: if i==j: count=count+1 if count == k: return i # no element occurs k times return -1 # Driver Codeif __name__=="__main__": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by Arpit Jain
7
Time complexity: O(n2).
Efficient Approach: Use unordered_map for hashing as the range is not known. Steps:
Traverse the array of elements from left to right.While traversing increment their count in the hash table.Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop.If no element has a count equal to k, print -1.
Traverse the array of elements from left to right.
While traversing increment their count in the hash table.
Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop.
If no element has a count equal to k, print -1.
Below is a dry run of the above approach:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h> using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // unordered_map to count // occurrences of each element unordered_map<int, int> count_map; for (int i=0; i<n; i++) count_map[arr[i]]++; for (int i=0; i<n; i++) // if count of element == k ,then // it is the required first element if (count_map[arr[i]] == k) return arr[i]; // no element occurs k times return -1;} // Driver program to test aboveint main(){ int arr[] = {1, 7, 4, 3, 4, 8, 7}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0;}
import java.util.HashMap; // Java implementation to find first// element occurring k timesclass GFG { // function to find the first element// occurring k number of times static int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element HashMap<Integer, Integer> count_map = new HashMap<>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.get(arr[i])!=null){ a = count_map.get(arr[i]); } count_map.put(arr[i], a+1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.get(arr[i]) == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver program to test above public static void main(String[] args) { int arr[] = {1, 7, 4, 3, 4, 8, 7}; int n = arr.length; int k = 2; System.out.println(firstElement(arr, n, k)); }} //this code contributed by Rajput-Ji
# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k): # dictionary to count # occurrences of # each element count_map = {}; for i in range(0, n): if(arr[i] in count_map.keys()): count_map[arr[i]] += 1 else: count_map[arr[i]] = 1 i += 1 for i in range(0, n): # if count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # no element occurs k times return -1 # Driver Codeif __name__=="__main__": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed# by Abhishek Sharma
// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element Dictionary<int, int> count_map = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.ContainsKey(arr[i])) { a = count_map[arr[i]]; count_map.Remove(arr[i]); count_map.Add(arr[i], a+1); } else count_map.Add(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map[arr[i]] == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void Main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.Length; int k = 2; Console.WriteLine(firstElement(arr, n, k)); }} // This code has been contributed by 29AjayKumar
<script> // JavaScript implementation to find first// element occurring k times // function to find the first element// occurring k number of timesfunction firstElement(arr, n, k){ // unordered_map to count // occurrences of each element count_map = new Map() for (let i=0; i<n; i++) count_map[arr[i]] = 0; for (let i=0; i<n; i++) count_map[arr[i]]++; for (let i=0; i<n; i++) // if count of element == k ,then // it is the required first element if (count_map[arr[i]] == k) return arr[i]; // no element occurs k times return -1;} // Driver program to test above let arr = [1, 7, 4, 3, 4, 8, 7];let n = arr.length;let k = 2;document.write(firstElement(arr, n, k)); <script>
7
Time Complexity: O(n)Auxiliary Space: O(n) because we are using an auxiliary array of size n to store the count
Method 3:Using Built-in Python functions:
Count the frequencies of every element using Counter function
Traverse in frequency dictionary
Checks which element has a count equal to k. Print that element and stop.
If no element has a count equal to k, print -1.
C++
Java
Python3
C#
Javascript
// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // unordered_map to count // occurrences of each element map<int, int> count_map; for (int i = 0; i < n; i++) { count_map[arr[i]]++; } // count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.find(arr[i]) != count_map.end()) { if (count_map[arr[i]] == k) return arr[i]; } } // no element occurs k times return -1;} // Driver codeint main(){ int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << (firstElement(arr, n, k)); return 0;} // This code is contributed by Rajput-Ji
// java implementation to find first// element occurring k timesimport java.util.*;class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element HashMap<Integer,Integer> count_map = new HashMap<>(); for (int i = 0; i < n; i++) { if(count_map.containsKey(arr[i])) { count_map.put(arr[i], count_map.get(arr[i])+1); } else count_map.put(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.containsKey(arr[i]) ) { if(count_map.get(arr[i]) == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.length; int k = 2; System.out.print(firstElement(arr, n, k)); }} // This code contributed by Rajput-Ji
# importing counter from collectionsfrom collections import Counter # Python3 implementation to find# first element occurring k times# function to find the first element# occurring k number of timesdef firstElement(arr, n, k): # calculating frequencies using Counter count_map = Counter(arr) for i in range(0, n): # If count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # No element occurs k times return -1 # Driver Codeif __name__ == "__main__": arr = [1, 7, 4, 3, 4, 8, 7] n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by vikkycirus
// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element Dictionary<int, int> count_map = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.ContainsKey(arr[i])) { a = count_map[arr[i]]; count_map.Remove(arr[i]); count_map.Add(arr[i], a+1); } else count_map.Add(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map[arr[i]] == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void Main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.Length; int k = 2; Console.WriteLine(firstElement(arr, n, k)); }} // This code is contributed by avijitmondal1998.
<script>// javascript implementation to find first// element occurring k times // function to find the first element // occurring k number of times function firstElement(arr , n , k) { // unordered_map to count // occurrences of each element var count_map = new Map(); for (i = 0; i < n; i++) { if (count_map.has(arr[i])) { count_map.set(arr[i], count_map.get(arr[i]) + 1); } else count_map.set(arr[i], 1); } // count_map[arr[i]]++; for (i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.has(arr[i])) { if (count_map.get(arr[i]) == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code var arr = [ 1, 7, 4, 3, 4, 8, 7 ]; var n = arr.length; var k = 2; document.write(firstElement(arr, n, k)); // This code is contributed by Rajput-Ji</script>
7
Time Complexity: O(n*log(n))Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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 if you want to share more information about the topic discussed above.
Abhishekk781
Rajput-Ji
29AjayKumar
vikkycirus
rohitsingh07052
simranarora5sos
prachisoda1234
avijitmondal1998
kumargaurav97520
111arpit1
codewithmini
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Count pairs with given sum
Sort string of characters
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 265,
"s": 53,
"text": "Given an array of n integers. The task is to find the first element that occurs k number of times. If no element occurs k times the print -1. The distribution of integer elements could be in any range.Examples: "
},
{
"code": null,
"e": 394,
"s": 265,
"text": "Input: {1, 7, 4, 3, 4, 8, 7}, k = 2 Output: 7 Explaination: Both 7 and 4 occur 2 times. But 7 is the first that occurs 2 times. "
},
{
"code": null,
"e": 438,
"s": 394,
"text": "Input: {4, 1, 6, 1, 6, 4}, k = 1 Output: -1"
},
{
"code": null,
"e": 614,
"s": 438,
"text": "Naive Approach: The idea is to use two nested loops. one for the selection of element and other for counting the number of time the selected element occurs in the given array."
},
{
"code": null,
"e": 665,
"s": 614,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 674,
"s": 665,
"text": "Chapters"
},
{
"code": null,
"e": 701,
"s": 674,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 751,
"s": 701,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 774,
"s": 751,
"text": "captions off, selected"
},
{
"code": null,
"e": 782,
"s": 774,
"text": "English"
},
{
"code": null,
"e": 800,
"s": 782,
"text": "default, selected"
},
{
"code": null,
"e": 824,
"s": 800,
"text": "This is a modal window."
},
{
"code": null,
"e": 893,
"s": 824,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 915,
"s": 893,
"text": "End of dialog window."
},
{
"code": null,
"e": 919,
"s": 915,
"text": "C++"
},
{
"code": null,
"e": 924,
"s": 919,
"text": "Java"
},
{
"code": null,
"e": 932,
"s": 924,
"text": "Python3"
},
{
"code": "// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // Function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } // Check, if it occurs k times or not if (count == k) return arr[i]; } return -1;} // Driver Codeint main(){ int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0;}",
"e": 1716,
"s": 932,
"text": null
},
{
"code": "public class GFG { // Java implementation to find first // element occurring k times // Function to find the first element // occurring k number of times public static int firstElement(int[] arr, int n, int k) { // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { count++; } } // Check, if it occurs k times or not if (count == k) { return arr[i]; } } return -1; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 7, 4, 3, 4, 8, 7 }; int n = arr.length; int k = 2; System.out.print(firstElement(arr, n, k)); }} // This code is contributed by Aarti_Rathi",
"e": 2693,
"s": 1716,
"text": null
},
{
"code": "# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k): # dictionary to count # occurrences of # each element for i in arr: count=0 for j in arr: if i==j: count=count+1 if count == k: return i # no element occurs k times return -1 # Driver Codeif __name__==\"__main__\": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by Arpit Jain",
"e": 3271,
"s": 2693,
"text": null
},
{
"code": null,
"e": 3273,
"s": 3271,
"text": "7"
},
{
"code": null,
"e": 3297,
"s": 3273,
"text": "Time complexity: O(n2)."
},
{
"code": null,
"e": 3383,
"s": 3297,
"text": "Efficient Approach: Use unordered_map for hashing as the range is not known. Steps: "
},
{
"code": null,
"e": 3658,
"s": 3383,
"text": "Traverse the array of elements from left to right.While traversing increment their count in the hash table.Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop.If no element has a count equal to k, print -1."
},
{
"code": null,
"e": 3709,
"s": 3658,
"text": "Traverse the array of elements from left to right."
},
{
"code": null,
"e": 3767,
"s": 3709,
"text": "While traversing increment their count in the hash table."
},
{
"code": null,
"e": 3888,
"s": 3767,
"text": "Again traverse the array from left to right and check which element has a count equal to k. Print that element and stop."
},
{
"code": null,
"e": 3936,
"s": 3888,
"text": "If no element has a count equal to k, print -1."
},
{
"code": null,
"e": 3979,
"s": 3936,
"text": "Below is a dry run of the above approach: "
},
{
"code": null,
"e": 4031,
"s": 3979,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4035,
"s": 4031,
"text": "C++"
},
{
"code": null,
"e": 4040,
"s": 4035,
"text": "Java"
},
{
"code": null,
"e": 4048,
"s": 4040,
"text": "Python3"
},
{
"code": null,
"e": 4051,
"s": 4048,
"text": "C#"
},
{
"code": null,
"e": 4062,
"s": 4051,
"text": "Javascript"
},
{
"code": "// C++ implementation to find first// element occurring k times#include <bits/stdc++.h> using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // unordered_map to count // occurrences of each element unordered_map<int, int> count_map; for (int i=0; i<n; i++) count_map[arr[i]]++; for (int i=0; i<n; i++) // if count of element == k ,then // it is the required first element if (count_map[arr[i]] == k) return arr[i]; // no element occurs k times return -1;} // Driver program to test aboveint main(){ int arr[] = {1, 7, 4, 3, 4, 8, 7}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0;}",
"e": 4862,
"s": 4062,
"text": null
},
{
"code": "import java.util.HashMap; // Java implementation to find first// element occurring k timesclass GFG { // function to find the first element// occurring k number of times static int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element HashMap<Integer, Integer> count_map = new HashMap<>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.get(arr[i])!=null){ a = count_map.get(arr[i]); } count_map.put(arr[i], a+1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.get(arr[i]) == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver program to test above public static void main(String[] args) { int arr[] = {1, 7, 4, 3, 4, 8, 7}; int n = arr.length; int k = 2; System.out.println(firstElement(arr, n, k)); }} //this code contributed by Rajput-Ji",
"e": 6006,
"s": 4862,
"text": null
},
{
"code": "# Python3 implementation to# find first element# occurring k times # function to find the# first element occurring# k number of timesdef firstElement(arr, n, k): # dictionary to count # occurrences of # each element count_map = {}; for i in range(0, n): if(arr[i] in count_map.keys()): count_map[arr[i]] += 1 else: count_map[arr[i]] = 1 i += 1 for i in range(0, n): # if count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # no element occurs k times return -1 # Driver Codeif __name__==\"__main__\": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed# by Abhishek Sharma",
"e": 6849,
"s": 6006,
"text": null
},
{
"code": "// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element Dictionary<int, int> count_map = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.ContainsKey(arr[i])) { a = count_map[arr[i]]; count_map.Remove(arr[i]); count_map.Add(arr[i], a+1); } else count_map.Add(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map[arr[i]] == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void Main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.Length; int k = 2; Console.WriteLine(firstElement(arr, n, k)); }} // This code has been contributed by 29AjayKumar",
"e": 8141,
"s": 6849,
"text": null
},
{
"code": "<script> // JavaScript implementation to find first// element occurring k times // function to find the first element// occurring k number of timesfunction firstElement(arr, n, k){ // unordered_map to count // occurrences of each element count_map = new Map() for (let i=0; i<n; i++) count_map[arr[i]] = 0; for (let i=0; i<n; i++) count_map[arr[i]]++; for (let i=0; i<n; i++) // if count of element == k ,then // it is the required first element if (count_map[arr[i]] == k) return arr[i]; // no element occurs k times return -1;} // Driver program to test above let arr = [1, 7, 4, 3, 4, 8, 7];let n = arr.length;let k = 2;document.write(firstElement(arr, n, k)); <script>",
"e": 8904,
"s": 8141,
"text": null
},
{
"code": null,
"e": 8906,
"s": 8904,
"text": "7"
},
{
"code": null,
"e": 9018,
"s": 8906,
"text": "Time Complexity: O(n)Auxiliary Space: O(n) because we are using an auxiliary array of size n to store the count"
},
{
"code": null,
"e": 9060,
"s": 9018,
"text": "Method 3:Using Built-in Python functions:"
},
{
"code": null,
"e": 9122,
"s": 9060,
"text": "Count the frequencies of every element using Counter function"
},
{
"code": null,
"e": 9155,
"s": 9122,
"text": "Traverse in frequency dictionary"
},
{
"code": null,
"e": 9229,
"s": 9155,
"text": "Checks which element has a count equal to k. Print that element and stop."
},
{
"code": null,
"e": 9277,
"s": 9229,
"text": "If no element has a count equal to k, print -1."
},
{
"code": null,
"e": 9281,
"s": 9277,
"text": "C++"
},
{
"code": null,
"e": 9286,
"s": 9281,
"text": "Java"
},
{
"code": null,
"e": 9294,
"s": 9286,
"text": "Python3"
},
{
"code": null,
"e": 9297,
"s": 9294,
"text": "C#"
},
{
"code": null,
"e": 9308,
"s": 9297,
"text": "Javascript"
},
{
"code": "// C++ implementation to find first// element occurring k times#include <bits/stdc++.h>using namespace std; // function to find the first element// occurring k number of timesint firstElement(int arr[], int n, int k){ // unordered_map to count // occurrences of each element map<int, int> count_map; for (int i = 0; i < n; i++) { count_map[arr[i]]++; } // count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.find(arr[i]) != count_map.end()) { if (count_map[arr[i]] == k) return arr[i]; } } // no element occurs k times return -1;} // Driver codeint main(){ int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << (firstElement(arr, n, k)); return 0;} // This code is contributed by Rajput-Ji",
"e": 10171,
"s": 9308,
"text": null
},
{
"code": "// java implementation to find first// element occurring k timesimport java.util.*;class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element HashMap<Integer,Integer> count_map = new HashMap<>(); for (int i = 0; i < n; i++) { if(count_map.containsKey(arr[i])) { count_map.put(arr[i], count_map.get(arr[i])+1); } else count_map.put(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.containsKey(arr[i]) ) { if(count_map.get(arr[i]) == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.length; int k = 2; System.out.print(firstElement(arr, n, k)); }} // This code contributed by Rajput-Ji",
"e": 11237,
"s": 10171,
"text": null
},
{
"code": "# importing counter from collectionsfrom collections import Counter # Python3 implementation to find# first element occurring k times# function to find the first element# occurring k number of timesdef firstElement(arr, n, k): # calculating frequencies using Counter count_map = Counter(arr) for i in range(0, n): # If count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # No element occurs k times return -1 # Driver Codeif __name__ == \"__main__\": arr = [1, 7, 4, 3, 4, 8, 7] n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by vikkycirus",
"e": 11950,
"s": 11237,
"text": null
},
{
"code": "// C# implementation to find first// element occurring k timesusing System;using System.Collections.Generic; class GFG{ // function to find the first element // occurring k number of times static int firstElement(int []arr, int n, int k) { // unordered_map to count // occurrences of each element Dictionary<int, int> count_map = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { int a = 0; if(count_map.ContainsKey(arr[i])) { a = count_map[arr[i]]; count_map.Remove(arr[i]); count_map.Add(arr[i], a+1); } else count_map.Add(arr[i], 1); } //count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map[arr[i]] == k) { return arr[i]; } } // no element occurs k times return -1; } // Driver code public static void Main(String[] args) { int []arr = {1, 7, 4, 3, 4, 8, 7}; int n = arr.Length; int k = 2; Console.WriteLine(firstElement(arr, n, k)); }} // This code is contributed by avijitmondal1998.",
"e": 13242,
"s": 11950,
"text": null
},
{
"code": "<script>// javascript implementation to find first// element occurring k times // function to find the first element // occurring k number of times function firstElement(arr , n , k) { // unordered_map to count // occurrences of each element var count_map = new Map(); for (i = 0; i < n; i++) { if (count_map.has(arr[i])) { count_map.set(arr[i], count_map.get(arr[i]) + 1); } else count_map.set(arr[i], 1); } // count_map[arr[i]]++; for (i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.has(arr[i])) { if (count_map.get(arr[i]) == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code var arr = [ 1, 7, 4, 3, 4, 8, 7 ]; var n = arr.length; var k = 2; document.write(firstElement(arr, n, k)); // This code is contributed by Rajput-Ji</script>",
"e": 14306,
"s": 13242,
"text": null
},
{
"code": null,
"e": 14308,
"s": 14306,
"text": "7"
},
{
"code": null,
"e": 14358,
"s": 14308,
"text": "Time Complexity: O(n*log(n))Auxiliary Space: O(n)"
},
{
"code": null,
"e": 14782,
"s": 14358,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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 if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 14795,
"s": 14782,
"text": "Abhishekk781"
},
{
"code": null,
"e": 14805,
"s": 14795,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14817,
"s": 14805,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14828,
"s": 14817,
"text": "vikkycirus"
},
{
"code": null,
"e": 14844,
"s": 14828,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 14860,
"s": 14844,
"text": "simranarora5sos"
},
{
"code": null,
"e": 14875,
"s": 14860,
"text": "prachisoda1234"
},
{
"code": null,
"e": 14892,
"s": 14875,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 14909,
"s": 14892,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 14919,
"s": 14909,
"text": "111arpit1"
},
{
"code": null,
"e": 14932,
"s": 14919,
"text": "codewithmini"
},
{
"code": null,
"e": 14939,
"s": 14932,
"text": "Arrays"
},
{
"code": null,
"e": 14944,
"s": 14939,
"text": "Hash"
},
{
"code": null,
"e": 14951,
"s": 14944,
"text": "Arrays"
},
{
"code": null,
"e": 14956,
"s": 14951,
"text": "Hash"
},
{
"code": null,
"e": 15054,
"s": 14956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15069,
"s": 15054,
"text": "Arrays in Java"
},
{
"code": null,
"e": 15115,
"s": 15069,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 15183,
"s": 15115,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 15227,
"s": 15183,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 15259,
"s": 15227,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 15344,
"s": 15259,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15382,
"s": 15344,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 15418,
"s": 15382,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 15445,
"s": 15418,
"text": "Count pairs with given sum"
}
] |
Python program to get all subsets having sum x
|
25 Feb, 2021
We are given a list of n numbers and a number x, the task is to write a python program to find out all possible subsets of the list such that their sum is x.
Examples:
Input: arr = [2, 4, 5, 9], x = 15
Output: [2, 4, 9]
15 can be obtained by adding 2, 4 and 9 from the given list.
Input : arr = [10, 20, 25, 50, 70, 90], x = 80
Output : [10, 70]
[10, 20, 50]
80 can be obtained by adding 10 and 70 or by adding 10, 20 and 50 from the given list.
Approach #1:
It is a Brute Force approach. Find all possible subset sums of the given list and check if the sum is equal to x. The time complexity using this approach would be O(2^n) which is quite large.
Python3
# Python code with time complexity# O(2^n)to print all subsets whose# sum is equal to a given valuefrom itertools import combinations def subsetSum(n, arr, x): # Iterating through all possible # subsets of arr from lengths 0 to n: for i in range(n+1): for subset in combinations(arr, i): # printing the subset if its sum is x: if sum(subset) == x: print(list(subset)) # Driver Code:n = 6arr = [10, 20, 25, 50, 70, 90]x = 80subsetSum(n, arr, x)
Output:
[10, 70]
[10, 20, 50]
Approach #2:
Meet in the middle is a technique that divides the search space into two equal-sized parts, performs a separate search on both the parts and then combines the search results. Using this technique, the two searches may require less time than one large search and turn the time complexity from O(2^n) to O(2^(n/2)).
Python3
# Efficient Python code to# print all subsets whose sum# is equal to a given valuefrom itertools import combinations def subsetSum(li, comb, sums): # Iterating through all subsets of # list li from length 0 to length of li: for i in range(len(li)+1): for subset in combinations(li, i): # Storing all the subsets in list comb: comb.append(list(subset)) # Storing the subset sums in list sums: sums.append(sum(subset)) def calcSubsets(n, arr, x): # Dividing the list arr into two lists # arr1 and arr2 of about equal sizes # by slicing list arr about index n//2: arr1, arr2 = arr[:n//2], arr[n//2:] # Creating empty lists comb1 and sums1 # to run the subsetSum function and # store subsets of arr1 in comb1 # and the subset sums in sums1: comb1, sums1 = [], [] subsetSum(arr1, comb1, sums1) # Creating empty lists comb2 and sums2 # to run the subsetSum function and # store subsets of arr2 in comb2 # and the subset sums in sums2: comb2, sums2 = [], [] subsetSum(arr2, comb2, sums2) # Iterating i through the indices of sums1: for i in range(len(sums1)): # Iterating j through the indices of sums2: for j in range(len(sums2)): # If two elements (one from sums1 # and one from sums2) add up to x, # the combined list of elements from # corresponding subsets at index i in comb1 # and j in comb2 gives us the required answer: if sums1[i] + sums2[j] == x: print(comb1[i] + comb2[j]) # Driver Code:n = 6arr = [10, 20, 25, 50, 70, 90]x = 80calcSubsets(n, arr, x)
Output:
[10, 70]
[10, 20, 50]
Python collections-module
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "We are given a list of n numbers and a number x, the task is to write a python program to find out all possible subsets of the list such that their sum is x."
},
{
"code": null,
"e": 196,
"s": 186,
"text": "Examples:"
},
{
"code": null,
"e": 230,
"s": 196,
"text": "Input: arr = [2, 4, 5, 9], x = 15"
},
{
"code": null,
"e": 248,
"s": 230,
"text": "Output: [2, 4, 9]"
},
{
"code": null,
"e": 309,
"s": 248,
"text": "15 can be obtained by adding 2, 4 and 9 from the given list."
},
{
"code": null,
"e": 357,
"s": 309,
"text": "Input : arr = [10, 20, 25, 50, 70, 90], x = 80"
},
{
"code": null,
"e": 375,
"s": 357,
"text": "Output : [10, 70]"
},
{
"code": null,
"e": 397,
"s": 375,
"text": " [10, 20, 50]"
},
{
"code": null,
"e": 484,
"s": 397,
"text": "80 can be obtained by adding 10 and 70 or by adding 10, 20 and 50 from the given list."
},
{
"code": null,
"e": 497,
"s": 484,
"text": "Approach #1:"
},
{
"code": null,
"e": 689,
"s": 497,
"text": "It is a Brute Force approach. Find all possible subset sums of the given list and check if the sum is equal to x. The time complexity using this approach would be O(2^n) which is quite large."
},
{
"code": null,
"e": 697,
"s": 689,
"text": "Python3"
},
{
"code": "# Python code with time complexity# O(2^n)to print all subsets whose# sum is equal to a given valuefrom itertools import combinations def subsetSum(n, arr, x): # Iterating through all possible # subsets of arr from lengths 0 to n: for i in range(n+1): for subset in combinations(arr, i): # printing the subset if its sum is x: if sum(subset) == x: print(list(subset)) # Driver Code:n = 6arr = [10, 20, 25, 50, 70, 90]x = 80subsetSum(n, arr, x)",
"e": 1218,
"s": 697,
"text": null
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Output:"
},
{
"code": null,
"e": 1248,
"s": 1226,
"text": "[10, 70]\n[10, 20, 50]"
},
{
"code": null,
"e": 1261,
"s": 1248,
"text": "Approach #2:"
},
{
"code": null,
"e": 1576,
"s": 1261,
"text": "Meet in the middle is a technique that divides the search space into two equal-sized parts, performs a separate search on both the parts and then combines the search results. Using this technique, the two searches may require less time than one large search and turn the time complexity from O(2^n) to O(2^(n/2)). "
},
{
"code": null,
"e": 1584,
"s": 1576,
"text": "Python3"
},
{
"code": "# Efficient Python code to# print all subsets whose sum# is equal to a given valuefrom itertools import combinations def subsetSum(li, comb, sums): # Iterating through all subsets of # list li from length 0 to length of li: for i in range(len(li)+1): for subset in combinations(li, i): # Storing all the subsets in list comb: comb.append(list(subset)) # Storing the subset sums in list sums: sums.append(sum(subset)) def calcSubsets(n, arr, x): # Dividing the list arr into two lists # arr1 and arr2 of about equal sizes # by slicing list arr about index n//2: arr1, arr2 = arr[:n//2], arr[n//2:] # Creating empty lists comb1 and sums1 # to run the subsetSum function and # store subsets of arr1 in comb1 # and the subset sums in sums1: comb1, sums1 = [], [] subsetSum(arr1, comb1, sums1) # Creating empty lists comb2 and sums2 # to run the subsetSum function and # store subsets of arr2 in comb2 # and the subset sums in sums2: comb2, sums2 = [], [] subsetSum(arr2, comb2, sums2) # Iterating i through the indices of sums1: for i in range(len(sums1)): # Iterating j through the indices of sums2: for j in range(len(sums2)): # If two elements (one from sums1 # and one from sums2) add up to x, # the combined list of elements from # corresponding subsets at index i in comb1 # and j in comb2 gives us the required answer: if sums1[i] + sums2[j] == x: print(comb1[i] + comb2[j]) # Driver Code:n = 6arr = [10, 20, 25, 50, 70, 90]x = 80calcSubsets(n, arr, x)",
"e": 3332,
"s": 1584,
"text": null
},
{
"code": null,
"e": 3340,
"s": 3332,
"text": "Output:"
},
{
"code": null,
"e": 3362,
"s": 3340,
"text": "[10, 70]\n[10, 20, 50]"
},
{
"code": null,
"e": 3388,
"s": 3362,
"text": "Python collections-module"
},
{
"code": null,
"e": 3409,
"s": 3388,
"text": "Python list-programs"
},
{
"code": null,
"e": 3416,
"s": 3409,
"text": "Python"
},
{
"code": null,
"e": 3432,
"s": 3416,
"text": "Python Programs"
},
{
"code": null,
"e": 3530,
"s": 3432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3562,
"s": 3530,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3589,
"s": 3562,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3610,
"s": 3589,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3633,
"s": 3610,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3689,
"s": 3633,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3711,
"s": 3689,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3750,
"s": 3711,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3788,
"s": 3750,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3837,
"s": 3788,
"text": "Python | Convert string dictionary to dictionary"
}
] |
pipe() System call
|
12 Jun, 2019
Prerequisite : I/O System calls
Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process. In UNIX Operating System, Pipes are useful for communication between related processes(inter-process communication).
Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe. It opens a pipe, which is an area of main memory that is treated as a “virtual file”.
The pipe can be used by the creating process, as well as all its child processes, for reading and writing. One process can write to this “virtual file” or pipe and another related process can read from it.
If a process tries to read before something is written to the pipe, the process is suspended until something is written.
The pipe system call finds the first two available positions in the process’s open file table and allocates them for the read and write ends of the pipe.
Syntax in C language:
int pipe(int fds[2]);
Parameters :
fd[0] will be the fd(file descriptor) for the
read end of pipe.
fd[1] will be the fd for the write end of pipe.
Returns : 0 on Success.
-1 on error.
Pipes behave FIFO(First in First out), Pipe behave like a queue data structure. Size of read and write don’t have to match here. We can write 512 bytes at a time but we can read only 1 byte at a time in a pipe.
// C program to illustrate// pipe system call in C#include <stdio.h>#include <unistd.h>#define MSGSIZE 16char* msg1 = "hello, world #1";char* msg2 = "hello, world #2";char* msg3 = "hello, world #3"; int main(){ char inbuf[MSGSIZE]; int p[2], i; if (pipe(p) < 0) exit(1); /* continued */ /* write pipe */ write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE); for (i = 0; i < 3; i++) { /* read pipe */ read(p[0], inbuf, MSGSIZE); printf("% s\n", inbuf); } return 0;}
Output:
hello, world #1
hello, world #2
hello, world #3
Parent and child sharing a pipe
When we use fork in any process, file descriptors remain open across child process and also parent process. If we call fork after creating a pipe, then the parent and child can communicate via the pipe.
Output of the following program.
// C program to illustrate// pipe system call in C// shared by Parent and Child#include <stdio.h>#include <unistd.h>#define MSGSIZE 16char* msg1 = "hello, world #1";char* msg2 = "hello, world #2";char* msg3 = "hello, world #3"; int main(){ char inbuf[MSGSIZE]; int p[2], pid, nbytes; if (pipe(p) < 0) exit(1); /* continued */ if ((pid = fork()) > 0) { write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE); // Adding this line will // not hang the program // close(p[1]); wait(NULL); } else { // Adding this line will // not hang the program // close(p[1]); while ((nbytes = read(p[0], inbuf, MSGSIZE)) > 0) printf("% s\n", inbuf); if (nbytes != 0) exit(2); printf("Finished reading\n"); } return 0;}
Output:
hello world, #1
hello world, #2
hello world, #3
(hangs) //program does not terminate but hangs
Here, In this code After finishing reading/writing, both parent and child block instead of terminating the process and that’s why program hangs. This happens because read system call gets as much data it requests or as much data as the pipe has, whichever is less.
If pipe is empty and we call read system call then Reads on the pipe will return EOF (return value 0) if no process has the write end open.
If some other process has the pipe open for writing, read will block in anticipation of new data so this code output hangs because here write ends parent process and also child process doesn’t close.
For more details about parent and child sharing pipe, please refer C program to demonstrate fork() and pipe(). This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
system-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Power Function in C/C++
Enumeration (or enum) in C
C Language Introduction
Memory Layout of C Programs
INT_MAX and INT_MIN in C/C++ and Applications
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 86,
"s": 54,
"text": "Prerequisite : I/O System calls"
},
{
"code": null,
"e": 359,
"s": 86,
"text": "Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process. In UNIX Operating System, Pipes are useful for communication between related processes(inter-process communication)."
},
{
"code": null,
"e": 586,
"s": 359,
"text": "Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe. It opens a pipe, which is an area of main memory that is treated as a “virtual file”."
},
{
"code": null,
"e": 792,
"s": 586,
"text": "The pipe can be used by the creating process, as well as all its child processes, for reading and writing. One process can write to this “virtual file” or pipe and another related process can read from it."
},
{
"code": null,
"e": 913,
"s": 792,
"text": "If a process tries to read before something is written to the pipe, the process is suspended until something is written."
},
{
"code": null,
"e": 1067,
"s": 913,
"text": "The pipe system call finds the first two available positions in the process’s open file table and allocates them for the read and write ends of the pipe."
},
{
"code": null,
"e": 1089,
"s": 1067,
"text": "Syntax in C language:"
},
{
"code": null,
"e": 1275,
"s": 1089,
"text": "int pipe(int fds[2]);\n\nParameters :\nfd[0] will be the fd(file descriptor) for the \nread end of pipe.\nfd[1] will be the fd for the write end of pipe.\nReturns : 0 on Success.\n-1 on error."
},
{
"code": null,
"e": 1486,
"s": 1275,
"text": "Pipes behave FIFO(First in First out), Pipe behave like a queue data structure. Size of read and write don’t have to match here. We can write 512 bytes at a time but we can read only 1 byte at a time in a pipe."
},
{
"code": "// C program to illustrate// pipe system call in C#include <stdio.h>#include <unistd.h>#define MSGSIZE 16char* msg1 = \"hello, world #1\";char* msg2 = \"hello, world #2\";char* msg3 = \"hello, world #3\"; int main(){ char inbuf[MSGSIZE]; int p[2], i; if (pipe(p) < 0) exit(1); /* continued */ /* write pipe */ write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE); for (i = 0; i < 3; i++) { /* read pipe */ read(p[0], inbuf, MSGSIZE); printf(\"% s\\n\", inbuf); } return 0;}",
"e": 2051,
"s": 1486,
"text": null
},
{
"code": null,
"e": 2059,
"s": 2051,
"text": "Output:"
},
{
"code": null,
"e": 2108,
"s": 2059,
"text": "hello, world #1\nhello, world #2\nhello, world #3\n"
},
{
"code": null,
"e": 2140,
"s": 2108,
"text": "Parent and child sharing a pipe"
},
{
"code": null,
"e": 2343,
"s": 2140,
"text": "When we use fork in any process, file descriptors remain open across child process and also parent process. If we call fork after creating a pipe, then the parent and child can communicate via the pipe."
},
{
"code": null,
"e": 2376,
"s": 2343,
"text": "Output of the following program."
},
{
"code": "// C program to illustrate// pipe system call in C// shared by Parent and Child#include <stdio.h>#include <unistd.h>#define MSGSIZE 16char* msg1 = \"hello, world #1\";char* msg2 = \"hello, world #2\";char* msg3 = \"hello, world #3\"; int main(){ char inbuf[MSGSIZE]; int p[2], pid, nbytes; if (pipe(p) < 0) exit(1); /* continued */ if ((pid = fork()) > 0) { write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE); // Adding this line will // not hang the program // close(p[1]); wait(NULL); } else { // Adding this line will // not hang the program // close(p[1]); while ((nbytes = read(p[0], inbuf, MSGSIZE)) > 0) printf(\"% s\\n\", inbuf); if (nbytes != 0) exit(2); printf(\"Finished reading\\n\"); } return 0;}",
"e": 3262,
"s": 2376,
"text": null
},
{
"code": null,
"e": 3270,
"s": 3262,
"text": "Output:"
},
{
"code": null,
"e": 3374,
"s": 3270,
"text": "hello world, #1\nhello world, #2\nhello world, #3\n(hangs) //program does not terminate but hangs\n"
},
{
"code": null,
"e": 3639,
"s": 3374,
"text": "Here, In this code After finishing reading/writing, both parent and child block instead of terminating the process and that’s why program hangs. This happens because read system call gets as much data it requests or as much data as the pipe has, whichever is less."
},
{
"code": null,
"e": 3779,
"s": 3639,
"text": "If pipe is empty and we call read system call then Reads on the pipe will return EOF (return value 0) if no process has the write end open."
},
{
"code": null,
"e": 3979,
"s": 3779,
"text": "If some other process has the pipe open for writing, read will block in anticipation of new data so this code output hangs because here write ends parent process and also child process doesn’t close."
},
{
"code": null,
"e": 4386,
"s": 3979,
"text": "For more details about parent and child sharing pipe, please refer C program to demonstrate fork() and pipe(). This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4511,
"s": 4386,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4524,
"s": 4511,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4543,
"s": 4524,
"text": "system-programming"
},
{
"code": null,
"e": 4554,
"s": 4543,
"text": "C Language"
},
{
"code": null,
"e": 4652,
"s": 4554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4669,
"s": 4652,
"text": "Substring in C++"
},
{
"code": null,
"e": 4691,
"s": 4669,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4736,
"s": 4691,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4761,
"s": 4736,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4809,
"s": 4761,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4833,
"s": 4809,
"text": "Power Function in C/C++"
},
{
"code": null,
"e": 4860,
"s": 4833,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 4884,
"s": 4860,
"text": "C Language Introduction"
},
{
"code": null,
"e": 4912,
"s": 4884,
"text": "Memory Layout of C Programs"
}
] |
Express.js res.status() Function
|
03 Aug, 2021
The res.status() function set the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
Syntax:
res.status( code )
Parameter: This function accepts single parameter code that holds the HTTP status code.
Returns: It returns an Object.
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1:Filename: index.js
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/user', function(req, res){ res.status(200).send("User Page");}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now open browser and go to http://localhost:3000/user, on your screen and you will see the following output:User Page
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now open browser and go to http://localhost:3000/user, on your screen and you will see the following output:User Page
User Page
Example 2:Filename: index.js
var express = require('express');const path = require('path');var app = express();var PORT = 3000; //with middlewareapp.use('/', function(req, res, next){ res.status(200).send("Status Working"); next();}); app.get('/', function(req, res){ console.log("Home Page!") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
Home Page!
And you will see the following output on your browser screen:
Status Working
Reference: https://expressjs.com/en/5x/api.html#res.status
manikarora059
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
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": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "The res.status() function set the HTTP status for the response. It is a chainable alias of Node’s response.statusCode."
},
{
"code": null,
"e": 155,
"s": 147,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 155,
"text": "res.status( code )"
},
{
"code": null,
"e": 262,
"s": 174,
"text": "Parameter: This function accepts single parameter code that holds the HTTP status code."
},
{
"code": null,
"e": 293,
"s": 262,
"text": "Returns: It returns an Object."
},
{
"code": null,
"e": 325,
"s": 293,
"text": "Installation of express module:"
},
{
"code": null,
"e": 715,
"s": 325,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 836,
"s": 715,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 856,
"s": 836,
"text": "npm install express"
},
{
"code": null,
"e": 984,
"s": 856,
"text": "After installing the express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 1004,
"s": 984,
"text": "npm version express"
},
{
"code": null,
"e": 1147,
"s": 1004,
"text": "After that, you can create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1161,
"s": 1147,
"text": "node index.js"
},
{
"code": null,
"e": 1190,
"s": 1161,
"text": "Example 1:Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/user', function(req, res){ res.status(200).send(\"User Page\");}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1475,
"s": 1190,
"text": null
},
{
"code": null,
"e": 1501,
"s": 1475,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1840,
"s": 1501,
"text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open browser and go to http://localhost:3000/user, on your screen and you will see the following output:User Page"
},
{
"code": null,
"e": 1883,
"s": 1840,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1975,
"s": 1883,
"text": "Make sure you have installed express module using the following command:npm install express"
},
{
"code": null,
"e": 1995,
"s": 1975,
"text": "npm install express"
},
{
"code": null,
"e": 2084,
"s": 1995,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2098,
"s": 2084,
"text": "node index.js"
},
{
"code": null,
"e": 2106,
"s": 2098,
"text": "Output:"
},
{
"code": null,
"e": 2137,
"s": 2106,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2255,
"s": 2137,
"text": "Now open browser and go to http://localhost:3000/user, on your screen and you will see the following output:User Page"
},
{
"code": null,
"e": 2265,
"s": 2255,
"text": "User Page"
},
{
"code": null,
"e": 2294,
"s": 2265,
"text": "Example 2:Filename: index.js"
},
{
"code": "var express = require('express');const path = require('path');var app = express();var PORT = 3000; //with middlewareapp.use('/', function(req, res, next){ res.status(200).send(\"Status Working\"); next();}); app.get('/', function(req, res){ console.log(\"Home Page!\") res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 2703,
"s": 2294,
"text": null
},
{
"code": null,
"e": 2742,
"s": 2703,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 2756,
"s": 2742,
"text": "node index.js"
},
{
"code": null,
"e": 2873,
"s": 2756,
"text": "Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:"
},
{
"code": null,
"e": 2915,
"s": 2873,
"text": "Server listening on PORT 3000\nHome Page!\n"
},
{
"code": null,
"e": 2977,
"s": 2915,
"text": "And you will see the following output on your browser screen:"
},
{
"code": null,
"e": 2992,
"s": 2977,
"text": "Status Working"
},
{
"code": null,
"e": 3051,
"s": 2992,
"text": "Reference: https://expressjs.com/en/5x/api.html#res.status"
},
{
"code": null,
"e": 3065,
"s": 3051,
"text": "manikarora059"
},
{
"code": null,
"e": 3076,
"s": 3065,
"text": "Express.js"
},
{
"code": null,
"e": 3084,
"s": 3076,
"text": "Node.js"
},
{
"code": null,
"e": 3101,
"s": 3084,
"text": "Web Technologies"
},
{
"code": null,
"e": 3199,
"s": 3101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3229,
"s": 3199,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 3286,
"s": 3229,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 3340,
"s": 3286,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 3380,
"s": 3340,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 3415,
"s": 3380,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3477,
"s": 3415,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3538,
"s": 3477,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3588,
"s": 3538,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3631,
"s": 3588,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Pandas dataframe.asfreq()
|
19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.asfreq() function is used to convert TimeSeries to specified frequency. This function Optionally provide filling method to pad/backfill missing values. It Returns the original data conformed to a new index with the specified frequency. resample is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency.
Syntax : DataFrame.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)
Parameters :freq : DateOffset object, or stringmethod : Method to use for filling holes in reindexed Serieshow : For PeriodIndex only, see PeriodIndex.asfreqnormalize : Whether to reset output index to midnightfill_value : Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present).
Returns : converted : type of caller
Example #1: Unsample a time series data from weekly frequency to daily frequency
# importing pandas as pdimport pandas as pd # Creating a date_time form index index_values = (pd.date_range('1/1/2000', periods=3,freq='W')) # Creating a series using 'index_values'# Notice, one of the series value is nan valueseries = (pd.Series([0.0,None,2.0], index=index_values)) # Creating dataframe using the seriesdf=pd.DataFrame({"Col_1":series}) # Print the Dataframedf
Now unsample this weekly sampled data into daily sampled data.By default newly created bins will have nan value. So, use fill_value parameter to fill all newly created bins with a provided value.
# unsampling and providing a fill value = 9.0df.asfreq(freq ='D', fill_value = 9.0)
Output :
Note : This does not fill NaNs that already were present before sampling.
Example #2: Unsample a one minute timestamped data into 30s bins.First create a series with 5 one minute timestamps.
# importing pandas as pdimport pandas as pd # Creating a date_time form index index_values = (pd.date_range('1/1/2000', periods=5,freq='T')) # Creating a series using 'index_values'# Notice, one of the series value is nan valueseries = (pd.Series([0.0,1.0,None,3.0,4.0], index=index_values)) # Creating dataframe using the seriesdf=pd.DataFrame({"Col_1":series}) # Print the Dataframedf
Now Unsampling into 30-second bins and providing a fill_value of 100.0
# unsampling and providing a fill value of 100.0df.asfreq(freq ='30S', fill_value = 100.0)
Output :
Note : Nan value present before unsampling will not be filled
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 621,
"s": 242,
"text": "Pandas dataframe.asfreq() function is used to convert TimeSeries to specified frequency. This function Optionally provide filling method to pad/backfill missing values. It Returns the original data conformed to a new index with the specified frequency. resample is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency."
},
{
"code": null,
"e": 710,
"s": 621,
"text": "Syntax : DataFrame.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)"
},
{
"code": null,
"e": 1050,
"s": 710,
"text": "Parameters :freq : DateOffset object, or stringmethod : Method to use for filling holes in reindexed Serieshow : For PeriodIndex only, see PeriodIndex.asfreqnormalize : Whether to reset output index to midnightfill_value : Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present)."
},
{
"code": null,
"e": 1087,
"s": 1050,
"text": "Returns : converted : type of caller"
},
{
"code": null,
"e": 1168,
"s": 1087,
"text": "Example #1: Unsample a time series data from weekly frequency to daily frequency"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating a date_time form index index_values = (pd.date_range('1/1/2000', periods=3,freq='W')) # Creating a series using 'index_values'# Notice, one of the series value is nan valueseries = (pd.Series([0.0,None,2.0], index=index_values)) # Creating dataframe using the seriesdf=pd.DataFrame({\"Col_1\":series}) # Print the Dataframedf",
"e": 1582,
"s": 1168,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1582,
"text": "Now unsample this weekly sampled data into daily sampled data.By default newly created bins will have nan value. So, use fill_value parameter to fill all newly created bins with a provided value."
},
{
"code": "# unsampling and providing a fill value = 9.0df.asfreq(freq ='D', fill_value = 9.0)",
"e": 1862,
"s": 1778,
"text": null
},
{
"code": null,
"e": 1871,
"s": 1862,
"text": "Output :"
},
{
"code": null,
"e": 1945,
"s": 1871,
"text": "Note : This does not fill NaNs that already were present before sampling."
},
{
"code": null,
"e": 2062,
"s": 1945,
"text": "Example #2: Unsample a one minute timestamped data into 30s bins.First create a series with 5 one minute timestamps."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating a date_time form index index_values = (pd.date_range('1/1/2000', periods=5,freq='T')) # Creating a series using 'index_values'# Notice, one of the series value is nan valueseries = (pd.Series([0.0,1.0,None,3.0,4.0], index=index_values)) # Creating dataframe using the seriesdf=pd.DataFrame({\"Col_1\":series}) # Print the Dataframedf",
"e": 2494,
"s": 2062,
"text": null
},
{
"code": null,
"e": 2565,
"s": 2494,
"text": "Now Unsampling into 30-second bins and providing a fill_value of 100.0"
},
{
"code": "# unsampling and providing a fill value of 100.0df.asfreq(freq ='30S', fill_value = 100.0)",
"e": 2656,
"s": 2565,
"text": null
},
{
"code": null,
"e": 2665,
"s": 2656,
"text": "Output :"
},
{
"code": null,
"e": 2727,
"s": 2665,
"text": "Note : Nan value present before unsampling will not be filled"
},
{
"code": null,
"e": 2751,
"s": 2727,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2783,
"s": 2751,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2797,
"s": 2783,
"text": "Python-pandas"
},
{
"code": null,
"e": 2804,
"s": 2797,
"text": "Python"
},
{
"code": null,
"e": 2902,
"s": 2804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2920,
"s": 2902,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2962,
"s": 2920,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2984,
"s": 2962,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3019,
"s": 2984,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3045,
"s": 3019,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3077,
"s": 3045,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3106,
"s": 3077,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3133,
"s": 3106,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3163,
"s": 3133,
"text": "Iterate over a list in Python"
}
] |
Get all HTML tags with BeautifulSoup
|
25 Feb, 2021
Web scraping is a process of using bots like software called web scrapers in extracting information from HTML or XML content. Beautiful Soup is one such library used for scraping data through python. Beautiful Soup parses through the HTML content of the web page and collects it to provide iteration, searching and modification features on it. To provide these functionalities it works with a parser that converts the content to a parse tree. Using a parser you are comfortable with It’s fairly easy to crawl through the web pages using BeautifulSoup.
To get all the HTML tags of a web page using the BeautifulSoup library first import BeautifulSoup and requests library to make a GET request to the web page.
Step-by-step Approach:
Import required modules.
Python3
from bs4 import BeautifulSoupimport requests
After importing the library now assign a URL variable with the URL of the web page and make a GET request to fetch the raw HTML content:
Python3
# Assign URLurl = "https://www.geeksforgeeks.org/" # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text
Now parse the HTML content:
Python3
# Parse the html content using any parser soup = BeautifulSoup(html_content,"html.parser")
Now to get all the HTML tags of the web page run a loop for the .name attribute of the tag using the find_all() function:
Python3
[tag.name for tag in soup.find_all()]
Below is the complete program:
Python3
# Import modulesfrom bs4 import BeautifulSoupimport requests # Assign URLurl = "https://www.geeksforgeeks.org/" # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text # Parse the html content using any parsersoup = BeautifulSoup(html_content, "html.parser") # Display HTML tags[tag.name for tag in soup.find_all()]
Output:
['html',
'head',
'meta',
'meta',
'meta',
'link',
'meta',
'meta',
'meta',
'meta',
'meta',
'script',
'script',
'link',
'title',
'link',
'link',
'script',
'script']
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 582,
"s": 28,
"text": "Web scraping is a process of using bots like software called web scrapers in extracting information from HTML or XML content. Beautiful Soup is one such library used for scraping data through python. Beautiful Soup parses through the HTML content of the web page and collects it to provide iteration, searching and modification features on it. To provide these functionalities it works with a parser that converts the content to a parse tree. Using a parser you are comfortable with It’s fairly easy to crawl through the web pages using BeautifulSoup. "
},
{
"code": null,
"e": 740,
"s": 582,
"text": "To get all the HTML tags of a web page using the BeautifulSoup library first import BeautifulSoup and requests library to make a GET request to the web page."
},
{
"code": null,
"e": 763,
"s": 740,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 788,
"s": 763,
"text": "Import required modules."
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Python3"
},
{
"code": "from bs4 import BeautifulSoupimport requests",
"e": 841,
"s": 796,
"text": null
},
{
"code": null,
"e": 978,
"s": 841,
"text": "After importing the library now assign a URL variable with the URL of the web page and make a GET request to fetch the raw HTML content:"
},
{
"code": null,
"e": 986,
"s": 978,
"text": "Python3"
},
{
"code": "# Assign URLurl = \"https://www.geeksforgeeks.org/\" # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text",
"e": 1126,
"s": 986,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1126,
"text": "Now parse the HTML content:"
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "Python3"
},
{
"code": "# Parse the html content using any parser soup = BeautifulSoup(html_content,\"html.parser\")",
"e": 1253,
"s": 1162,
"text": null
},
{
"code": null,
"e": 1375,
"s": 1253,
"text": "Now to get all the HTML tags of the web page run a loop for the .name attribute of the tag using the find_all() function:"
},
{
"code": null,
"e": 1383,
"s": 1375,
"text": "Python3"
},
{
"code": "[tag.name for tag in soup.find_all()]",
"e": 1421,
"s": 1383,
"text": null
},
{
"code": null,
"e": 1452,
"s": 1421,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 1460,
"s": 1452,
"text": "Python3"
},
{
"code": "# Import modulesfrom bs4 import BeautifulSoupimport requests # Assign URLurl = \"https://www.geeksforgeeks.org/\" # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text # Parse the html content using any parsersoup = BeautifulSoup(html_content, \"html.parser\") # Display HTML tags[tag.name for tag in soup.find_all()]",
"e": 1812,
"s": 1460,
"text": null
},
{
"code": null,
"e": 1820,
"s": 1812,
"text": "Output:"
},
{
"code": null,
"e": 2000,
"s": 1820,
"text": "['html',\n 'head',\n 'meta',\n 'meta',\n 'meta',\n 'link',\n 'meta',\n 'meta',\n 'meta',\n 'meta',\n 'meta',\n 'script',\n 'script',\n 'link',\n 'title',\n 'link',\n 'link',\n 'script',\n 'script']"
},
{
"code": null,
"e": 2007,
"s": 2000,
"text": "Picked"
},
{
"code": null,
"e": 2028,
"s": 2007,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 2035,
"s": 2028,
"text": "Python"
},
{
"code": null,
"e": 2133,
"s": 2035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2165,
"s": 2133,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2192,
"s": 2165,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2223,
"s": 2192,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2246,
"s": 2223,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2267,
"s": 2246,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2323,
"s": 2267,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2365,
"s": 2323,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2407,
"s": 2365,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2446,
"s": 2407,
"text": "Python | Get unique values from a list"
}
] |
ThreadFactory Interface in Java with Examples
|
24 Jun, 2021
The ThreadFactory interface defined in the java.util.concurrent package is based on the factory design pattern. As its name suggests, it is used to create new threads on demand. Threads can be created in two ways:
1. Creating a class that extends the Thread class and then creating its objects.
Java
import java.io.*; class GFG { public static void main(String[] args) { // Creating a thread Thread thread = new CustomThread(); thread.start(); // Starting execution of the created // thread }} // Creating a class that extends the Thread classclass CustomThread extends Thread { @Override public void run() { System.out.println("This is a thread"); }}
This is a thread
2. Creating a class that implements the Runnable interface and then using its object to create threads.
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { // Creating a Runnable object Runnable task = new Task(); // Creating a thread using the Runnable object Thread thread = new Thread(task); // Starting the execution of the created thread thread.start(); }} class Task implements Runnable { @Override public void run() { System.out.println("This is a thread"); }}
This is a thread
However, ThreadFactory is another choice to create new threads. This interface provides a factory method that creates and returns new threads when called. This factory method takes a Runnable object as an argument and creates a new thread using it.
The Hierarchy of ThreadFactory
java.util.concurrent
↳ Interface ThreadFactory
Implementation of ThreadFactory interface
Since ThreadFactory is an interface, the factory method defined inside it has to be implemented first in order to be used. Here is the simplest implementation of the ThreadFactory interface :
Java
import java.util.concurrent.ThreadFactory;import java.io.*; class CustomThreadFactory implements ThreadFactory { // newThread is a factory method // provided by ThreadFactory public Thread newThread(Runnable command) { return new Thread(command); }}
Now, we can create objects of the CustomThreadFactory class and use its newThread(Runnable command) method to create new threads on demand. In the above implementation, the newThread method just creates a new thread by calling the Thread constructor which takes a Runnable command as the parameter.
There are many classes(such as ScheduledThreadPoolExecutor , ThreadPoolExecutor etc.) that use thread factories to create new threads when needed. Those classes have constructors that accept a ThreadFactory as argument. If any custom ThreadFactory is not given then they use the default implementation of ThreadFactory interface.
The Executors class in java.util.concurrent package provides Executors.defaultThreadFactory() static method that returns a default implementation of ThreadFactory interface.
Example: Below example code demonstrates ThreadFactory interface.
Java
// Java code to demonstrate ThreadFactory interface import java.util.concurrent.ThreadFactory;import java.io.*;import java.util.ArrayList; class ThreadFactoryExample { public static void main(String[] args) { // Creating a CustomThreadFactory object CustomThreadFactory threadFactory = new CustomThreadFactory(); // Creating Runnable objects using the lambda // expression Runnable command1 = () -> System.out.println("Command 1 executed"); Runnable command2 = () -> System.out.println("Command 2 executed"); Runnable command3 = () -> System.out.println("Command 3 executed"); Runnable command4 = () -> System.out.println("Command 4 executed"); Runnable command5 = () -> System.out.println("Command 5 executed"); // Putting the commands in an ArrayList ArrayList<Runnable> array = new ArrayList<>(5); array.add(command1); array.add(command2); array.add(command3); array.add(command4); array.add(command5); // creating threads and running them for (Runnable command : array) { threadFactory.newThread(command).start(); } // print the thread count System.out.println( "Total number of threads created using CustomThreadFactory = " + threadFactory.getCount()); }} // ThreadFactory classclass CustomThreadFactory implements ThreadFactory { // stores the thread count private int count = 0; // returns the thread count public int getCount() { return count; } // Factory method @Override public Thread newThread(Runnable command) { count++; return new Thread(command); }}
Command 1 executed
Command 2 executed
Command 4 executed
Command 3 executed
Command 5 executed
Total number of threads created using CustomThreadFactory = 5
Why use ThreadFactory?
In the above example, the newThread(Runnable) factory method ultimately creates a new thread using the given Runnable command. Then why use ThreadFactory? We could directly create threads from the Runnable commands by calling the Thread constructor that we did in the newThread(Runnable) method. Here are some reasons,
We can give the threads more meaningful custom names. It helps in analyzing their purposes and how they work.
We can have the statistics about the created threads like the count of threads and other details. We can restrict the creation of new threads based on the statistics.
We can set the daemon status of threads.
We can set the thread priority.
We can have all the features confined in one class.
Default Thread Factory
It is the default thread factory that is implemented by the Executors.defaultThreadFactory() static method. This default ThreadFactory is used by many classes (such as ScheduledThreadPoolExecutor, ThreadPoolExecutor etc.) when they are not given any custom ThreadFactory. Those classes create new threads using the default ThreadFactory. This default ThreadFactory creates all the new threads in the same ThreadGroup(A ThreadGroup represents a group of threads). All the created new threads are non-daemon with priority set to the smallest of Thread.NORM_PRIORITY and the maximum priority permitted in the ThreadGroup. The threads created by this default ThreadFactory are given names in the form of pool-N-thread-M (As examples, pool-1-thread-1, pool-1-thread-2, pool-2-thread-1 etc.) where N is the sequence number of this factory, and M is the sequence number of the threads created by this factory.
Example: The below example demonstrates how the default ThreadFactory can be used.
Java
// Java program to demonstrate default// ThreadFactory import java.io.*;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory; class DefaultThreadFactoryExample { public static void main(String[] args) { // Default ThreadFactory ThreadFactory threadFactory = Executors.defaultThreadFactory(); for (int i = 1; i < 10; i++) { // Creating new threads with the default // ThreadFactory Thread thread = threadFactory.newThread(new Command()); // print the thread names System.out.println( "Name given by threadFactory = " + thread.getName()); // run the thread thread.start(); } }} class Command implements Runnable { @Override public void run() { // Run some code }}
Name given by threadFactory = pool-1-thread-1
Name given by threadFactory = pool-1-thread-2
Name given by threadFactory = pool-1-thread-3
Name given by threadFactory = pool-1-thread-4
Name given by threadFactory = pool-1-thread-5
Name given by threadFactory = pool-1-thread-6
Name given by threadFactory = pool-1-thread-7
Name given by threadFactory = pool-1-thread-8
Name given by threadFactory = pool-1-thread-9
Note the names of threads given by default ThreadFactory. It has created 9 threads and all the threads are in the same ThreadGroup. All the threads are created using the same ThreadFactory(so the names of the threads are in form of pool -1 -thread-M).
Example:
Java
// Java program to demonstrate ThreadFactory// using default implementation import java.io.*;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory; class DefaultThreadFactoryExample { public static void main(String[] args) { for (int i = 1; i < 10; i++) { // Default ThreadFactory ThreadFactory threadFactory = Executors.defaultThreadFactory(); // Creating new threads with the default // ThreadFactory Thread thread = threadFactory.newThread(new Command()); // print the thread name System.out.println( "Name given by threadFactory = " + thread.getName()); // start the thread thread.start(); } }} class Command implements Runnable { @Override public void run() { // Run some code }}
Name given by threadFactory = pool-1-thread-1
Name given by threadFactory = pool-2-thread-1
Name given by threadFactory = pool-3-thread-1
Name given by threadFactory = pool-4-thread-1
Name given by threadFactory = pool-5-thread-1
Name given by threadFactory = pool-6-thread-1
Name given by threadFactory = pool-7-thread-1
Name given by threadFactory = pool-8-thread-1
Name given by threadFactory = pool-9-thread-1
Here, We have used 9 different default ThreadFactories(in each loop we are creating a new one!). So each thread is in different ThreadGroup and thus the threads are given name in form of pool-N-thread-1.
The default ThreadFactory implementation creates non-daemon threads with normal priority and gives names in form of pool-N-thread-M which contains no information about how they work and what they do. This creates lots of problems in debugging and other important purposes. However, this problem can be solved using a custom ThreadFactory which can give more meaningful names to the threads and can set the daemon and priority statuses.
METHOD
DESCRIPTION
surindertarika1234
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "The ThreadFactory interface defined in the java.util.concurrent package is based on the factory design pattern. As its name suggests, it is used to create new threads on demand. Threads can be created in two ways:"
},
{
"code": null,
"e": 323,
"s": 242,
"text": "1. Creating a class that extends the Thread class and then creating its objects."
},
{
"code": null,
"e": 328,
"s": 323,
"text": "Java"
},
{
"code": "import java.io.*; class GFG { public static void main(String[] args) { // Creating a thread Thread thread = new CustomThread(); thread.start(); // Starting execution of the created // thread }} // Creating a class that extends the Thread classclass CustomThread extends Thread { @Override public void run() { System.out.println(\"This is a thread\"); }}",
"e": 752,
"s": 328,
"text": null
},
{
"code": null,
"e": 772,
"s": 755,
"text": "This is a thread"
},
{
"code": null,
"e": 878,
"s": 774,
"text": "2. Creating a class that implements the Runnable interface and then using its object to create threads."
},
{
"code": null,
"e": 885,
"s": 880,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { // Creating a Runnable object Runnable task = new Task(); // Creating a thread using the Runnable object Thread thread = new Thread(task); // Starting the execution of the created thread thread.start(); }} class Task implements Runnable { @Override public void run() { System.out.println(\"This is a thread\"); }}",
"e": 1390,
"s": 885,
"text": null
},
{
"code": null,
"e": 1410,
"s": 1393,
"text": "This is a thread"
},
{
"code": null,
"e": 1661,
"s": 1412,
"text": "However, ThreadFactory is another choice to create new threads. This interface provides a factory method that creates and returns new threads when called. This factory method takes a Runnable object as an argument and creates a new thread using it."
},
{
"code": null,
"e": 1694,
"s": 1663,
"text": "The Hierarchy of ThreadFactory"
},
{
"code": null,
"e": 1747,
"s": 1696,
"text": "java.util.concurrent\n ↳ Interface ThreadFactory"
},
{
"code": null,
"e": 1791,
"s": 1749,
"text": "Implementation of ThreadFactory interface"
},
{
"code": null,
"e": 1988,
"s": 1793,
"text": " Since ThreadFactory is an interface, the factory method defined inside it has to be implemented first in order to be used. Here is the simplest implementation of the ThreadFactory interface : "
},
{
"code": null,
"e": 1995,
"s": 1990,
"text": "Java"
},
{
"code": "import java.util.concurrent.ThreadFactory;import java.io.*; class CustomThreadFactory implements ThreadFactory { // newThread is a factory method // provided by ThreadFactory public Thread newThread(Runnable command) { return new Thread(command); }}",
"e": 2268,
"s": 1995,
"text": null
},
{
"code": null,
"e": 2571,
"s": 2272,
"text": "Now, we can create objects of the CustomThreadFactory class and use its newThread(Runnable command) method to create new threads on demand. In the above implementation, the newThread method just creates a new thread by calling the Thread constructor which takes a Runnable command as the parameter."
},
{
"code": null,
"e": 2904,
"s": 2573,
"text": "There are many classes(such as ScheduledThreadPoolExecutor , ThreadPoolExecutor etc.) that use thread factories to create new threads when needed. Those classes have constructors that accept a ThreadFactory as argument. If any custom ThreadFactory is not given then they use the default implementation of ThreadFactory interface. "
},
{
"code": null,
"e": 3080,
"s": 2906,
"text": "The Executors class in java.util.concurrent package provides Executors.defaultThreadFactory() static method that returns a default implementation of ThreadFactory interface."
},
{
"code": null,
"e": 3148,
"s": 3082,
"text": "Example: Below example code demonstrates ThreadFactory interface."
},
{
"code": null,
"e": 3155,
"s": 3150,
"text": "Java"
},
{
"code": "// Java code to demonstrate ThreadFactory interface import java.util.concurrent.ThreadFactory;import java.io.*;import java.util.ArrayList; class ThreadFactoryExample { public static void main(String[] args) { // Creating a CustomThreadFactory object CustomThreadFactory threadFactory = new CustomThreadFactory(); // Creating Runnable objects using the lambda // expression Runnable command1 = () -> System.out.println(\"Command 1 executed\"); Runnable command2 = () -> System.out.println(\"Command 2 executed\"); Runnable command3 = () -> System.out.println(\"Command 3 executed\"); Runnable command4 = () -> System.out.println(\"Command 4 executed\"); Runnable command5 = () -> System.out.println(\"Command 5 executed\"); // Putting the commands in an ArrayList ArrayList<Runnable> array = new ArrayList<>(5); array.add(command1); array.add(command2); array.add(command3); array.add(command4); array.add(command5); // creating threads and running them for (Runnable command : array) { threadFactory.newThread(command).start(); } // print the thread count System.out.println( \"Total number of threads created using CustomThreadFactory = \" + threadFactory.getCount()); }} // ThreadFactory classclass CustomThreadFactory implements ThreadFactory { // stores the thread count private int count = 0; // returns the thread count public int getCount() { return count; } // Factory method @Override public Thread newThread(Runnable command) { count++; return new Thread(command); }}",
"e": 4926,
"s": 3155,
"text": null
},
{
"code": null,
"e": 5086,
"s": 4929,
"text": "Command 1 executed\nCommand 2 executed\nCommand 4 executed\nCommand 3 executed\nCommand 5 executed\nTotal number of threads created using CustomThreadFactory = 5"
},
{
"code": null,
"e": 5111,
"s": 5088,
"text": "Why use ThreadFactory?"
},
{
"code": null,
"e": 5432,
"s": 5113,
"text": "In the above example, the newThread(Runnable) factory method ultimately creates a new thread using the given Runnable command. Then why use ThreadFactory? We could directly create threads from the Runnable commands by calling the Thread constructor that we did in the newThread(Runnable) method. Here are some reasons,"
},
{
"code": null,
"e": 5544,
"s": 5434,
"text": "We can give the threads more meaningful custom names. It helps in analyzing their purposes and how they work."
},
{
"code": null,
"e": 5711,
"s": 5544,
"text": "We can have the statistics about the created threads like the count of threads and other details. We can restrict the creation of new threads based on the statistics."
},
{
"code": null,
"e": 5752,
"s": 5711,
"text": "We can set the daemon status of threads."
},
{
"code": null,
"e": 5784,
"s": 5752,
"text": "We can set the thread priority."
},
{
"code": null,
"e": 5836,
"s": 5784,
"text": "We can have all the features confined in one class."
},
{
"code": null,
"e": 5861,
"s": 5838,
"text": "Default Thread Factory"
},
{
"code": null,
"e": 6766,
"s": 5863,
"text": "It is the default thread factory that is implemented by the Executors.defaultThreadFactory() static method. This default ThreadFactory is used by many classes (such as ScheduledThreadPoolExecutor, ThreadPoolExecutor etc.) when they are not given any custom ThreadFactory. Those classes create new threads using the default ThreadFactory. This default ThreadFactory creates all the new threads in the same ThreadGroup(A ThreadGroup represents a group of threads). All the created new threads are non-daemon with priority set to the smallest of Thread.NORM_PRIORITY and the maximum priority permitted in the ThreadGroup. The threads created by this default ThreadFactory are given names in the form of pool-N-thread-M (As examples, pool-1-thread-1, pool-1-thread-2, pool-2-thread-1 etc.) where N is the sequence number of this factory, and M is the sequence number of the threads created by this factory."
},
{
"code": null,
"e": 6852,
"s": 6768,
"text": "Example: The below example demonstrates how the default ThreadFactory can be used. "
},
{
"code": null,
"e": 6859,
"s": 6854,
"text": "Java"
},
{
"code": "// Java program to demonstrate default// ThreadFactory import java.io.*;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory; class DefaultThreadFactoryExample { public static void main(String[] args) { // Default ThreadFactory ThreadFactory threadFactory = Executors.defaultThreadFactory(); for (int i = 1; i < 10; i++) { // Creating new threads with the default // ThreadFactory Thread thread = threadFactory.newThread(new Command()); // print the thread names System.out.println( \"Name given by threadFactory = \" + thread.getName()); // run the thread thread.start(); } }} class Command implements Runnable { @Override public void run() { // Run some code }}",
"e": 7739,
"s": 6859,
"text": null
},
{
"code": null,
"e": 8156,
"s": 7742,
"text": "Name given by threadFactory = pool-1-thread-1\nName given by threadFactory = pool-1-thread-2\nName given by threadFactory = pool-1-thread-3\nName given by threadFactory = pool-1-thread-4\nName given by threadFactory = pool-1-thread-5\nName given by threadFactory = pool-1-thread-6\nName given by threadFactory = pool-1-thread-7\nName given by threadFactory = pool-1-thread-8\nName given by threadFactory = pool-1-thread-9"
},
{
"code": null,
"e": 8410,
"s": 8158,
"text": "Note the names of threads given by default ThreadFactory. It has created 9 threads and all the threads are in the same ThreadGroup. All the threads are created using the same ThreadFactory(so the names of the threads are in form of pool -1 -thread-M)."
},
{
"code": null,
"e": 8422,
"s": 8412,
"text": "Example: "
},
{
"code": null,
"e": 8429,
"s": 8424,
"text": "Java"
},
{
"code": "// Java program to demonstrate ThreadFactory// using default implementation import java.io.*;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory; class DefaultThreadFactoryExample { public static void main(String[] args) { for (int i = 1; i < 10; i++) { // Default ThreadFactory ThreadFactory threadFactory = Executors.defaultThreadFactory(); // Creating new threads with the default // ThreadFactory Thread thread = threadFactory.newThread(new Command()); // print the thread name System.out.println( \"Name given by threadFactory = \" + thread.getName()); // start the thread thread.start(); } }} class Command implements Runnable { @Override public void run() { // Run some code }}",
"e": 9343,
"s": 8429,
"text": null
},
{
"code": null,
"e": 9760,
"s": 9346,
"text": "Name given by threadFactory = pool-1-thread-1\nName given by threadFactory = pool-2-thread-1\nName given by threadFactory = pool-3-thread-1\nName given by threadFactory = pool-4-thread-1\nName given by threadFactory = pool-5-thread-1\nName given by threadFactory = pool-6-thread-1\nName given by threadFactory = pool-7-thread-1\nName given by threadFactory = pool-8-thread-1\nName given by threadFactory = pool-9-thread-1"
},
{
"code": null,
"e": 9966,
"s": 9762,
"text": "Here, We have used 9 different default ThreadFactories(in each loop we are creating a new one!). So each thread is in different ThreadGroup and thus the threads are given name in form of pool-N-thread-1."
},
{
"code": null,
"e": 10404,
"s": 9968,
"text": "The default ThreadFactory implementation creates non-daemon threads with normal priority and gives names in form of pool-N-thread-M which contains no information about how they work and what they do. This creates lots of problems in debugging and other important purposes. However, this problem can be solved using a custom ThreadFactory which can give more meaningful names to the threads and can set the daemon and priority statuses."
},
{
"code": null,
"e": 10413,
"s": 10406,
"text": "METHOD"
},
{
"code": null,
"e": 10425,
"s": 10413,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 10446,
"s": 10427,
"text": "surindertarika1234"
},
{
"code": null,
"e": 10451,
"s": 10446,
"text": "Java"
},
{
"code": null,
"e": 10456,
"s": 10451,
"text": "Java"
},
{
"code": null,
"e": 10554,
"s": 10456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10569,
"s": 10554,
"text": "Stream In Java"
},
{
"code": null,
"e": 10590,
"s": 10569,
"text": "Introduction to Java"
},
{
"code": null,
"e": 10611,
"s": 10590,
"text": "Constructors in Java"
},
{
"code": null,
"e": 10630,
"s": 10611,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 10647,
"s": 10630,
"text": "Generics in Java"
},
{
"code": null,
"e": 10677,
"s": 10647,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 10693,
"s": 10677,
"text": "Strings in Java"
},
{
"code": null,
"e": 10719,
"s": 10693,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 10739,
"s": 10719,
"text": "Abstraction in Java"
}
] |
Last two digits of powers of 7
|
23 Apr, 2021
Given a positive N, the task is to find the last two digits of 7N.Examples:
Input: N = 5 Output: 07 Explanation: The value of 75 = 7 * 7 * 7 * 7 * 7 = 8507 Therefore, the last two digits are 07.Input: N = 12 Output: 01 Explanation: The value of 712 = 13841287201 Therefore, the last two digits are 01.
Approach: A general approach to finding the last K digits of XY is to discuss this article in logarithmic time complexity. In this article, we will discuss the constant time solution.Below is the observation for the value of 7N for some values of N:
71 = 7 last two digit = 07 72 = 49 last two digit = 49 73 = 243 last two digit = 43 74 = 2401 lasr two digit = 0175 = 16807 last two digit = 07 76 = 117649 last two digit = 49 77 = 823543 last two digit = 43 78 = 5764801 last two digit = 01
Based on the above observations we have the following cases:
If the last two digit in 7N = 07 when N = 4K + 3.If the last two digit in 7N = 49 when N = 4K + 2.If the last two digit in 7N = 43 when N = 4K + 1.If the last two digit in 7N = 01 when N = 4K.
If the last two digit in 7N = 07 when N = 4K + 3.
If the last two digit in 7N = 49 when N = 4K + 2.
If the last two digit in 7N = 43 when N = 4K + 1.
If the last two digit in 7N = 01 when N = 4K.
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 last// two digits of 7^Nstring get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return "01"; // Case 3 else if (N % 4 == 1) return "07"; // Case 2 else if (N % 4 == 2) return "49"; // Case 1 return "43";} // Driver Codeint main(){ // Given Number int N = 12; // Function Call cout << get_last_two_digit(N); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to find the last// two digits of 7^Npublic static String get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return "01"; // Case 3 else if (N % 4 == 1) return "07"; // Case 2 else if (N % 4 == 2) return "49"; // Case 1 return "43";} // Driver codepublic static void main(String[] args){ int N = 12; // Function Call System.out.println(get_last_two_digit(N));}} // This code is contributed by grand_master
# Python3 program for the above approach # Function to find the last# two digits of 7 ^ Ndef get_last_two_digit(N): # Case 4 if (N % 4 == 0): return "01"; # Case 3 elif (N % 4 == 1): return "07"; # Case 2 elif (N % 4 == 2): return "49"; # Case 1 return "43"; # Driver Code # Given numberN = 12; # Function callprint( get_last_two_digit(N)) # This code is contributed by grand_master
// C# program for the above approachusing System; namespace GFG{class GFG{ // Function to find the last// two digits of 7^Npublic static String get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return "01"; // Case 3 else if (N % 4 == 1) return "07"; // Case 2 else if (N % 4 == 2) return "49"; // Case 1 return "43";} // Driver codepublic static void Main(){ // Given number int N = 12; // Function Call Console.Write(get_last_two_digit(N));}}} // This code is contributed by grand_master
<script> // Javascript program for the above approach // Function to find the last // two digits of 7^N function get_last_two_digit(N) { // Case 4 if (N % 4 == 0) return "01"; // Case 3 else if (N % 4 == 1) return "07"; // Case 2 else if (N % 4 == 2) return "49"; // Case 1 return "43"; } // Driver code var N = 12; // Function Call document.write(get_last_two_digit(N)); // This code contributed by gauravrajput1 </script>
01
Time Complexity: O(1) Auxiliary Space: O(1)
grand_master
GauravRajput1
maths-power
number-digits
Competitive Programming
Greedy
Mathematical
Pattern Searching
Greedy
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
C++: Methods of code shortening in competitive programming
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "Given a positive N, the task is to find the last two digits of 7N.Examples: "
},
{
"code": null,
"e": 360,
"s": 132,
"text": "Input: N = 5 Output: 07 Explanation: The value of 75 = 7 * 7 * 7 * 7 * 7 = 8507 Therefore, the last two digits are 07.Input: N = 12 Output: 01 Explanation: The value of 712 = 13841287201 Therefore, the last two digits are 01. "
},
{
"code": null,
"e": 614,
"s": 362,
"text": "Approach: A general approach to finding the last K digits of XY is to discuss this article in logarithmic time complexity. In this article, we will discuss the constant time solution.Below is the observation for the value of 7N for some values of N: "
},
{
"code": null,
"e": 857,
"s": 614,
"text": "71 = 7 last two digit = 07 72 = 49 last two digit = 49 73 = 243 last two digit = 43 74 = 2401 lasr two digit = 0175 = 16807 last two digit = 07 76 = 117649 last two digit = 49 77 = 823543 last two digit = 43 78 = 5764801 last two digit = 01 "
},
{
"code": null,
"e": 920,
"s": 857,
"text": "Based on the above observations we have the following cases: "
},
{
"code": null,
"e": 1113,
"s": 920,
"text": "If the last two digit in 7N = 07 when N = 4K + 3.If the last two digit in 7N = 49 when N = 4K + 2.If the last two digit in 7N = 43 when N = 4K + 1.If the last two digit in 7N = 01 when N = 4K."
},
{
"code": null,
"e": 1163,
"s": 1113,
"text": "If the last two digit in 7N = 07 when N = 4K + 3."
},
{
"code": null,
"e": 1213,
"s": 1163,
"text": "If the last two digit in 7N = 49 when N = 4K + 2."
},
{
"code": null,
"e": 1263,
"s": 1213,
"text": "If the last two digit in 7N = 43 when N = 4K + 1."
},
{
"code": null,
"e": 1309,
"s": 1263,
"text": "If the last two digit in 7N = 01 when N = 4K."
},
{
"code": null,
"e": 1361,
"s": 1309,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1365,
"s": 1361,
"text": "C++"
},
{
"code": null,
"e": 1370,
"s": 1365,
"text": "Java"
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": null,
"e": 1381,
"s": 1378,
"text": "C#"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the last// two digits of 7^Nstring get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return \"01\"; // Case 3 else if (N % 4 == 1) return \"07\"; // Case 2 else if (N % 4 == 2) return \"49\"; // Case 1 return \"43\";} // Driver Codeint main(){ // Given Number int N = 12; // Function Call cout << get_last_two_digit(N); return 0;}",
"e": 1885,
"s": 1392,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to find the last// two digits of 7^Npublic static String get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return \"01\"; // Case 3 else if (N % 4 == 1) return \"07\"; // Case 2 else if (N % 4 == 2) return \"49\"; // Case 1 return \"43\";} // Driver codepublic static void main(String[] args){ int N = 12; // Function Call System.out.println(get_last_two_digit(N));}} // This code is contributed by grand_master",
"e": 2448,
"s": 1885,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the last# two digits of 7 ^ Ndef get_last_two_digit(N): # Case 4 if (N % 4 == 0): return \"01\"; # Case 3 elif (N % 4 == 1): return \"07\"; # Case 2 elif (N % 4 == 2): return \"49\"; # Case 1 return \"43\"; # Driver Code # Given numberN = 12; # Function callprint( get_last_two_digit(N)) # This code is contributed by grand_master",
"e": 2884,
"s": 2448,
"text": null
},
{
"code": "// C# program for the above approachusing System; namespace GFG{class GFG{ // Function to find the last// two digits of 7^Npublic static String get_last_two_digit(int N){ // Case 4 if (N % 4 == 0) return \"01\"; // Case 3 else if (N % 4 == 1) return \"07\"; // Case 2 else if (N % 4 == 2) return \"49\"; // Case 1 return \"43\";} // Driver codepublic static void Main(){ // Given number int N = 12; // Function Call Console.Write(get_last_two_digit(N));}}} // This code is contributed by grand_master",
"e": 3447,
"s": 2884,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the last // two digits of 7^N function get_last_two_digit(N) { // Case 4 if (N % 4 == 0) return \"01\"; // Case 3 else if (N % 4 == 1) return \"07\"; // Case 2 else if (N % 4 == 2) return \"49\"; // Case 1 return \"43\"; } // Driver code var N = 12; // Function Call document.write(get_last_two_digit(N)); // This code contributed by gauravrajput1 </script>",
"e": 4006,
"s": 3447,
"text": null
},
{
"code": null,
"e": 4009,
"s": 4006,
"text": "01"
},
{
"code": null,
"e": 4056,
"s": 4011,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 4069,
"s": 4056,
"text": "grand_master"
},
{
"code": null,
"e": 4083,
"s": 4069,
"text": "GauravRajput1"
},
{
"code": null,
"e": 4095,
"s": 4083,
"text": "maths-power"
},
{
"code": null,
"e": 4109,
"s": 4095,
"text": "number-digits"
},
{
"code": null,
"e": 4133,
"s": 4109,
"text": "Competitive Programming"
},
{
"code": null,
"e": 4140,
"s": 4133,
"text": "Greedy"
},
{
"code": null,
"e": 4153,
"s": 4140,
"text": "Mathematical"
},
{
"code": null,
"e": 4171,
"s": 4153,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4178,
"s": 4171,
"text": "Greedy"
},
{
"code": null,
"e": 4191,
"s": 4178,
"text": "Mathematical"
},
{
"code": null,
"e": 4209,
"s": 4191,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4307,
"s": 4209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4341,
"s": 4307,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 4379,
"s": 4341,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 4419,
"s": 4379,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 4454,
"s": 4419,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 4513,
"s": 4454,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 4564,
"s": 4513,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 4591,
"s": 4564,
"text": "Program for array rotation"
},
{
"code": null,
"e": 4642,
"s": 4591,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 4702,
"s": 4642,
"text": "Write a program to print all permutations of a given string"
}
] |
Understanding Time Complexity with Simple Examples
|
22 Jun, 2022
A lot of students get confused while understanding the concept of time complexity, but in this article, we will explain it with a very simple example.
Q. Imagine a classroom of 100 students in which you gave your pen to one person. You have to find that pen without knowing to whom you gave it.
Here are some ways to find the pen and what the O order is.
O(n2): You go and ask the first person in the class if he has the pen. Also, you ask this person about the other 99 people in the classroom if they have that pen and so on, This is what we call O(n2).
O(n): Going and asking each student individually is O(N).
O(log n): Now I divide the class into two groups, then ask: “Is it on the left side, or the right side of the classroom?” Then I take that group and divide it into two and ask again, and so on. Repeat the process till you are left with one student who has your pen. This is what you mean by O(log n).
I might need to do:
The O(n2) searches if only one student knows on which student the pen is hidden.
The O(n) if one student had the pen and only they knew it.
The O(log n) search if all the students knew, but would only tell me if I guessed the right side.
The above O -> is called Big – Oh which is an asymptotic notation. There are other asymptotic notations like theta and Omega.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
NOTE: We are interested in the rate of growth over time with respect to the inputs taken during the program execution.
The Time Complexity of an algorithm/code is not equal to the actual time required to execute a particular code, but the number of times a statement executes. We can prove this by using the time command.
For example: Write code in C/C++ or any other language to find the maximum between N numbers, where N varies from 10, 100, 1000, and 10000. For Linux based operating system (Fedora or Ubuntu), use the below commands:
To compile the program: gcc program.c – o programTo execute the program: time ./program
You will get surprising results i.e.:
For N = 10: you may get 0.5 ms time,
For N = 10,000: you may get 0.2 ms time.
Also, you will get different timings on different machines. Even if you will not get the same timings on the same machine for the same code, the reason behind that is the current network load.
So, we can say that the actual time required to execute code is machine-dependent (whether you are using Pentium 1 or Pentium 5) and also it considers network load if your machine is in LAN/WAN.
Now, the question arises if time complexity is not the actual time required to execute the code, then what is it?
The answer is:
Instead of measuring actual time required in executing each statement in the code, Time Complexity considers how many times each statement executes.
Example 1: Consider the below simple code to print Hello World
C++
C
Java
#include <iostream>using namespace std; int main(){ cout << "Hello World"; return 0;} // This code is contributed by vikash36905.
#include <stdio.h> int main(){ printf("Hello World"); return 0;}
import java.io.*; class GFG { public static void main(String[] args) { System.out.print("Hello World"); }} // This code is contributed by vikash36905.
Hello World
Time Complexity: In the above code “Hello World” is printed only once on the screen. So, the time complexity is constant: O(1) i.e. every time a constant amount of time is required to execute code, no matter which operating system or which machine configurations you are using.
Example 2:
C++
C
Java
C#
Javascript
#include <iostream>using namespace std; int main(){ int i, n = 8; for (i = 1; i <= n; i++) { cout << "Hello World !!!\n"; } return 0;} // This code is contributed by vikash36905.
#include <stdio.h>void main(){ int i, n = 8; for (i = 1; i <= n; i++) { printf("Hello World !!!\n"); }}
class GFG { public static void main(String[] args) { int i, n = 8; for (i = 1; i <= n; i++) { System.out.printf("Hello World !!!\n"); } }} // This code is contributed by Rajput-Ji
using System;public class GFG { public static void Main(String[] args) { int i, n = 8; for (i = 1; i <= n; i++) { Console.Write("Hello World !!!\n"); } }} // This code contributed by Rajput-Ji
<script> var i, n = 8; for (i = 1; i <= n; i++) { document.write("Hello World !!!<br/>"); } // This code is contributed by Rajput-Ji</script>
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Time Complexity: In the above code “Hello World !!!” is printed only n times on the screen, as the value of n can change. So, the time complexity is linear: O(n) i.e. every time, a linear amount of time is required to execute code.
Example 3:
C++
C
Java
#include <iostream>using namespace std; int main(){ int i, n = 8; for (i = 1; i <= n; i=i*2) { cout << "Hello World !!!\n"; } return 0;} // This code is contributed by Suruchi Kumari
#include <stdio.h>void main(){ int i, n = 8; for (i = 1; i <= n; i=i*2) { printf("Hello World !!!\n"); }}// This code is contributed by Suruchi Kumari
class GFG { public static void main(String[] args) { int i, n = 8; for (i = 1; i <= n; i=i*2) { System.out.printf("Hello World !!!\n"); } }} // This code is contributed by Suruchi Kumari
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Time Complexity: O(log2(n))
Example 4:
C++
C
#include <iostream>#include <cmath>using namespace std; int main(){ int i, n = 8; for (i = 2; i <= n; i=pow(i,2)) { cout << "Hello World !!!\n"; } return 0;} // This code is contributed by Suruchi Kumari
#include <stdio.h>#include <math.h>void main(){ int i, n = 8; for (i = 2; i <= n; i=pow(i,2)) { printf("Hello World !!!\n"); }}// This code is contributed by Suruchi Kumari
Hello World !!!
Hello World !!!
Time Complexity: O(log(log n))
Now let us see some other examples and the process to find the time complexity of an algorithm:
Example: Let us consider a model machine that has the following specifications:
Single processor
32 bit
Sequential execution
1 unit time for arithmetic and logical operations
1 unit time for assignment and return statements
Q1. Find the Sum of 2 numbers on the above machine:
For any machine, the pseudocode to add two numbers will be something like this:
C
Pseudocode : Sum(a, b) { return a + b }
Time Complexity:
The above code will take 2 units of time(constant): one for arithmetic operations and one for return. (as per the above conventions).
one for arithmetic operations and
one for return. (as per the above conventions).
Therefore total cost to perform sum operation (Tsum) = 1 + 1 = 2
Time Complexity = O(2) = O(1), since 2 is constant
Q2. Find the sum of all elements of a list/array
The pseudocode to do so can be given as:
C
Pseudocode : list_Sum(A, n)// A->array and// n->number of elements in array{sum = 0 for i = 0 to n-1 sum = sum + A[i]return sum}
To understand the time complexity of the above code, let’s see how much time each statement will take:
C
Pseudocode : list_Sum(A, n){total =0 // cost=1 no of times=1for i=0 to n-1 // cost=2 no of times=n+1 (+1 for the end false condition) sum = sum + A[i] // cost=2 no of times=nreturn sum // cost=1 no of times=1}
Therefore the total cost to perform sum operation
Tsum=1 + 2 * (n+1) + 2 * n + 1 = 4n + 4 =C1 * n + C2 = O(n)
Therefore, the time complexity of the above code is O(n)
Q3. Find the sum of all elements of a matrix
For this one, the complexity is a polynomial equation (quadratic equation for a square matrix)
Matrix of size n*n => Tsum = a.n2 + b.n + c
Since Tsum is in order of n2, therefore Time Complexity = O(n2)
So from the above examples, we can conclude that the time of execution increases with the type of operations we make using the inputs.
Calculating Time Complexity | New Examples | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCalculating Time Complexity | New Examples | 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 / 8:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KXAbAa1mieU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
To compare algorithms, let us define a few objective measures:
Execution times: Not a good measure as execution times are specific to a particular computer.
The number of statements executed: Not a good measure, since the number of statements varies with the programming language as well as the style of the individual programmer.
Ideal solution: Let us assume that we express the running time of a given algorithm as a function of the input size n (i.e., f(n)) and compare these different functions corresponding to running times. This kind of comparison is independent of machine time, programming style, etc. Therefore, an ideal solution can be used to compare algorithms.
Related articles:
Time Complexity and Space Complexity
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Analysis of Algorithms | Set 4 (Analysis of Loops)
Analysis of Algorithm | Set 5 (Amortized Analysis Introduction)
Miscellaneous Problems of Time Complexity
Practice Questions on Time Complexity Analysis
Knowing the complexity in competitive programming
BalajiPathange
deekshadaga
shankaramshubham8
devilchandra
Rajput-Ji
RishabhPrabhu
vikash36905
suruchikumarimfp4
singhankitasingh066
time complexity
Algorithms
Analysis
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 203,
"s": 52,
"text": "A lot of students get confused while understanding the concept of time complexity, but in this article, we will explain it with a very simple example."
},
{
"code": null,
"e": 348,
"s": 203,
"text": "Q. Imagine a classroom of 100 students in which you gave your pen to one person. You have to find that pen without knowing to whom you gave it. "
},
{
"code": null,
"e": 408,
"s": 348,
"text": "Here are some ways to find the pen and what the O order is."
},
{
"code": null,
"e": 610,
"s": 408,
"text": "O(n2): You go and ask the first person in the class if he has the pen. Also, you ask this person about the other 99 people in the classroom if they have that pen and so on, This is what we call O(n2). "
},
{
"code": null,
"e": 669,
"s": 610,
"text": "O(n): Going and asking each student individually is O(N). "
},
{
"code": null,
"e": 971,
"s": 669,
"text": "O(log n): Now I divide the class into two groups, then ask: “Is it on the left side, or the right side of the classroom?” Then I take that group and divide it into two and ask again, and so on. Repeat the process till you are left with one student who has your pen. This is what you mean by O(log n). "
},
{
"code": null,
"e": 991,
"s": 971,
"text": "I might need to do:"
},
{
"code": null,
"e": 1073,
"s": 991,
"text": "The O(n2) searches if only one student knows on which student the pen is hidden. "
},
{
"code": null,
"e": 1133,
"s": 1073,
"text": "The O(n) if one student had the pen and only they knew it. "
},
{
"code": null,
"e": 1232,
"s": 1133,
"text": "The O(log n) search if all the students knew, but would only tell me if I guessed the right side. "
},
{
"code": null,
"e": 1358,
"s": 1232,
"text": "The above O -> is called Big – Oh which is an asymptotic notation. There are other asymptotic notations like theta and Omega."
},
{
"code": null,
"e": 1367,
"s": 1358,
"text": "Chapters"
},
{
"code": null,
"e": 1394,
"s": 1367,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1444,
"s": 1394,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1467,
"s": 1444,
"text": "captions off, selected"
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "English"
},
{
"code": null,
"e": 1499,
"s": 1475,
"text": "This is a modal window."
},
{
"code": null,
"e": 1568,
"s": 1499,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1590,
"s": 1568,
"text": "End of dialog window."
},
{
"code": null,
"e": 1709,
"s": 1590,
"text": "NOTE: We are interested in the rate of growth over time with respect to the inputs taken during the program execution."
},
{
"code": null,
"e": 1913,
"s": 1709,
"text": "The Time Complexity of an algorithm/code is not equal to the actual time required to execute a particular code, but the number of times a statement executes. We can prove this by using the time command. "
},
{
"code": null,
"e": 2131,
"s": 1913,
"text": "For example: Write code in C/C++ or any other language to find the maximum between N numbers, where N varies from 10, 100, 1000, and 10000. For Linux based operating system (Fedora or Ubuntu), use the below commands: "
},
{
"code": null,
"e": 2219,
"s": 2131,
"text": "To compile the program: gcc program.c – o programTo execute the program: time ./program"
},
{
"code": null,
"e": 2257,
"s": 2219,
"text": "You will get surprising results i.e.:"
},
{
"code": null,
"e": 2295,
"s": 2257,
"text": "For N = 10: you may get 0.5 ms time, "
},
{
"code": null,
"e": 2337,
"s": 2295,
"text": "For N = 10,000: you may get 0.2 ms time. "
},
{
"code": null,
"e": 2530,
"s": 2337,
"text": "Also, you will get different timings on different machines. Even if you will not get the same timings on the same machine for the same code, the reason behind that is the current network load."
},
{
"code": null,
"e": 2726,
"s": 2530,
"text": "So, we can say that the actual time required to execute code is machine-dependent (whether you are using Pentium 1 or Pentium 5) and also it considers network load if your machine is in LAN/WAN. "
},
{
"code": null,
"e": 2841,
"s": 2726,
"text": "Now, the question arises if time complexity is not the actual time required to execute the code, then what is it? "
},
{
"code": null,
"e": 2857,
"s": 2841,
"text": "The answer is: "
},
{
"code": null,
"e": 3007,
"s": 2857,
"text": "Instead of measuring actual time required in executing each statement in the code, Time Complexity considers how many times each statement executes. "
},
{
"code": null,
"e": 3070,
"s": 3007,
"text": "Example 1: Consider the below simple code to print Hello World"
},
{
"code": null,
"e": 3074,
"s": 3070,
"text": "C++"
},
{
"code": null,
"e": 3076,
"s": 3074,
"text": "C"
},
{
"code": null,
"e": 3081,
"s": 3076,
"text": "Java"
},
{
"code": "#include <iostream>using namespace std; int main(){ cout << \"Hello World\"; return 0;} // This code is contributed by vikash36905.",
"e": 3217,
"s": 3081,
"text": null
},
{
"code": "#include <stdio.h> int main(){ printf(\"Hello World\"); return 0;}",
"e": 3288,
"s": 3217,
"text": null
},
{
"code": "import java.io.*; class GFG { public static void main(String[] args) { System.out.print(\"Hello World\"); }} // This code is contributed by vikash36905.",
"e": 3455,
"s": 3288,
"text": null
},
{
"code": null,
"e": 3467,
"s": 3455,
"text": "Hello World"
},
{
"code": null,
"e": 3746,
"s": 3467,
"text": "Time Complexity: In the above code “Hello World” is printed only once on the screen. So, the time complexity is constant: O(1) i.e. every time a constant amount of time is required to execute code, no matter which operating system or which machine configurations you are using. "
},
{
"code": null,
"e": 3757,
"s": 3746,
"text": "Example 2:"
},
{
"code": null,
"e": 3761,
"s": 3757,
"text": "C++"
},
{
"code": null,
"e": 3763,
"s": 3761,
"text": "C"
},
{
"code": null,
"e": 3768,
"s": 3763,
"text": "Java"
},
{
"code": null,
"e": 3771,
"s": 3768,
"text": "C#"
},
{
"code": null,
"e": 3782,
"s": 3771,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int main(){ int i, n = 8; for (i = 1; i <= n; i++) { cout << \"Hello World !!!\\n\"; } return 0;} // This code is contributed by vikash36905.",
"e": 3981,
"s": 3782,
"text": null
},
{
"code": "#include <stdio.h>void main(){ int i, n = 8; for (i = 1; i <= n; i++) { printf(\"Hello World !!!\\n\"); }}",
"e": 4101,
"s": 3981,
"text": null
},
{
"code": "class GFG { public static void main(String[] args) { int i, n = 8; for (i = 1; i <= n; i++) { System.out.printf(\"Hello World !!!\\n\"); } }} // This code is contributed by Rajput-Ji",
"e": 4323,
"s": 4101,
"text": null
},
{
"code": "using System;public class GFG { public static void Main(String[] args) { int i, n = 8; for (i = 1; i <= n; i++) { Console.Write(\"Hello World !!!\\n\"); } }} // This code contributed by Rajput-Ji",
"e": 4558,
"s": 4323,
"text": null
},
{
"code": "<script> var i, n = 8; for (i = 1; i <= n; i++) { document.write(\"Hello World !!!<br/>\"); } // This code is contributed by Rajput-Ji</script>",
"e": 4733,
"s": 4558,
"text": null
},
{
"code": null,
"e": 4861,
"s": 4733,
"text": "Hello World !!!\nHello World !!!\nHello World !!!\nHello World !!!\nHello World !!!\nHello World !!!\nHello World !!!\nHello World !!!"
},
{
"code": null,
"e": 5093,
"s": 4861,
"text": "Time Complexity: In the above code “Hello World !!!” is printed only n times on the screen, as the value of n can change. So, the time complexity is linear: O(n) i.e. every time, a linear amount of time is required to execute code."
},
{
"code": null,
"e": 5104,
"s": 5093,
"text": "Example 3:"
},
{
"code": null,
"e": 5108,
"s": 5104,
"text": "C++"
},
{
"code": null,
"e": 5110,
"s": 5108,
"text": "C"
},
{
"code": null,
"e": 5115,
"s": 5110,
"text": "Java"
},
{
"code": "#include <iostream>using namespace std; int main(){ int i, n = 8; for (i = 1; i <= n; i=i*2) { cout << \"Hello World !!!\\n\"; } return 0;} // This code is contributed by Suruchi Kumari",
"e": 5318,
"s": 5115,
"text": null
},
{
"code": "#include <stdio.h>void main(){ int i, n = 8; for (i = 1; i <= n; i=i*2) { printf(\"Hello World !!!\\n\"); }}// This code is contributed by Suruchi Kumari",
"e": 5485,
"s": 5318,
"text": null
},
{
"code": "class GFG { public static void main(String[] args) { int i, n = 8; for (i = 1; i <= n; i=i*2) { System.out.printf(\"Hello World !!!\\n\"); } }} // This code is contributed by Suruchi Kumari",
"e": 5714,
"s": 5485,
"text": null
},
{
"code": null,
"e": 5778,
"s": 5714,
"text": "Hello World !!!\nHello World !!!\nHello World !!!\nHello World !!!"
},
{
"code": null,
"e": 5806,
"s": 5778,
"text": "Time Complexity: O(log2(n))"
},
{
"code": null,
"e": 5817,
"s": 5806,
"text": "Example 4:"
},
{
"code": null,
"e": 5821,
"s": 5817,
"text": "C++"
},
{
"code": null,
"e": 5823,
"s": 5821,
"text": "C"
},
{
"code": "#include <iostream>#include <cmath>using namespace std; int main(){ int i, n = 8; for (i = 2; i <= n; i=pow(i,2)) { cout << \"Hello World !!!\\n\"; } return 0;} // This code is contributed by Suruchi Kumari",
"e": 6047,
"s": 5823,
"text": null
},
{
"code": "#include <stdio.h>#include <math.h>void main(){ int i, n = 8; for (i = 2; i <= n; i=pow(i,2)) { printf(\"Hello World !!!\\n\"); }}// This code is contributed by Suruchi Kumari",
"e": 6236,
"s": 6047,
"text": null
},
{
"code": null,
"e": 6268,
"s": 6236,
"text": "Hello World !!!\nHello World !!!"
},
{
"code": null,
"e": 6299,
"s": 6268,
"text": "Time Complexity: O(log(log n))"
},
{
"code": null,
"e": 6395,
"s": 6299,
"text": "Now let us see some other examples and the process to find the time complexity of an algorithm:"
},
{
"code": null,
"e": 6476,
"s": 6395,
"text": "Example: Let us consider a model machine that has the following specifications: "
},
{
"code": null,
"e": 6494,
"s": 6476,
"text": "Single processor "
},
{
"code": null,
"e": 6502,
"s": 6494,
"text": "32 bit "
},
{
"code": null,
"e": 6524,
"s": 6502,
"text": "Sequential execution "
},
{
"code": null,
"e": 6575,
"s": 6524,
"text": "1 unit time for arithmetic and logical operations "
},
{
"code": null,
"e": 6625,
"s": 6575,
"text": "1 unit time for assignment and return statements "
},
{
"code": null,
"e": 6677,
"s": 6625,
"text": "Q1. Find the Sum of 2 numbers on the above machine:"
},
{
"code": null,
"e": 6757,
"s": 6677,
"text": "For any machine, the pseudocode to add two numbers will be something like this:"
},
{
"code": null,
"e": 6759,
"s": 6757,
"text": "C"
},
{
"code": "Pseudocode : Sum(a, b) { return a + b }",
"e": 6799,
"s": 6759,
"text": null
},
{
"code": null,
"e": 6818,
"s": 6799,
"text": "Time Complexity: "
},
{
"code": null,
"e": 6953,
"s": 6818,
"text": "The above code will take 2 units of time(constant): one for arithmetic operations and one for return. (as per the above conventions). "
},
{
"code": null,
"e": 6988,
"s": 6953,
"text": "one for arithmetic operations and "
},
{
"code": null,
"e": 7037,
"s": 6988,
"text": "one for return. (as per the above conventions). "
},
{
"code": null,
"e": 7102,
"s": 7037,
"text": "Therefore total cost to perform sum operation (Tsum) = 1 + 1 = 2"
},
{
"code": null,
"e": 7153,
"s": 7102,
"text": "Time Complexity = O(2) = O(1), since 2 is constant"
},
{
"code": null,
"e": 7202,
"s": 7153,
"text": "Q2. Find the sum of all elements of a list/array"
},
{
"code": null,
"e": 7243,
"s": 7202,
"text": "The pseudocode to do so can be given as:"
},
{
"code": null,
"e": 7245,
"s": 7243,
"text": "C"
},
{
"code": "Pseudocode : list_Sum(A, n)// A->array and// n->number of elements in array{sum = 0 for i = 0 to n-1 sum = sum + A[i]return sum}",
"e": 7389,
"s": 7245,
"text": null
},
{
"code": null,
"e": 7492,
"s": 7389,
"text": "To understand the time complexity of the above code, let’s see how much time each statement will take:"
},
{
"code": null,
"e": 7494,
"s": 7492,
"text": "C"
},
{
"code": "Pseudocode : list_Sum(A, n){total =0 // cost=1 no of times=1for i=0 to n-1 // cost=2 no of times=n+1 (+1 for the end false condition) sum = sum + A[i] // cost=2 no of times=nreturn sum // cost=1 no of times=1}",
"e": 7763,
"s": 7494,
"text": null
},
{
"code": null,
"e": 7814,
"s": 7763,
"text": "Therefore the total cost to perform sum operation "
},
{
"code": null,
"e": 7874,
"s": 7814,
"text": "Tsum=1 + 2 * (n+1) + 2 * n + 1 = 4n + 4 =C1 * n + C2 = O(n)"
},
{
"code": null,
"e": 7931,
"s": 7874,
"text": "Therefore, the time complexity of the above code is O(n)"
},
{
"code": null,
"e": 7976,
"s": 7931,
"text": "Q3. Find the sum of all elements of a matrix"
},
{
"code": null,
"e": 8071,
"s": 7976,
"text": "For this one, the complexity is a polynomial equation (quadratic equation for a square matrix)"
},
{
"code": null,
"e": 8115,
"s": 8071,
"text": "Matrix of size n*n => Tsum = a.n2 + b.n + c"
},
{
"code": null,
"e": 8179,
"s": 8115,
"text": "Since Tsum is in order of n2, therefore Time Complexity = O(n2)"
},
{
"code": null,
"e": 8315,
"s": 8179,
"text": "So from the above examples, we can conclude that the time of execution increases with the type of operations we make using the inputs. "
},
{
"code": null,
"e": 9217,
"s": 8315,
"text": "Calculating Time Complexity | New Examples | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCalculating Time Complexity | New Examples | 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 / 8:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KXAbAa1mieU\" 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": 9280,
"s": 9217,
"text": "To compare algorithms, let us define a few objective measures:"
},
{
"code": null,
"e": 9374,
"s": 9280,
"text": "Execution times: Not a good measure as execution times are specific to a particular computer."
},
{
"code": null,
"e": 9548,
"s": 9374,
"text": "The number of statements executed: Not a good measure, since the number of statements varies with the programming language as well as the style of the individual programmer."
},
{
"code": null,
"e": 9894,
"s": 9548,
"text": "Ideal solution: Let us assume that we express the running time of a given algorithm as a function of the input size n (i.e., f(n)) and compare these different functions corresponding to running times. This kind of comparison is independent of machine time, programming style, etc. Therefore, an ideal solution can be used to compare algorithms."
},
{
"code": null,
"e": 9912,
"s": 9894,
"text": "Related articles:"
},
{
"code": null,
"e": 9949,
"s": 9912,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 10002,
"s": 9949,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 10065,
"s": 10002,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 10119,
"s": 10065,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 10170,
"s": 10119,
"text": "Analysis of Algorithms | Set 4 (Analysis of Loops)"
},
{
"code": null,
"e": 10234,
"s": 10170,
"text": "Analysis of Algorithm | Set 5 (Amortized Analysis Introduction)"
},
{
"code": null,
"e": 10276,
"s": 10234,
"text": "Miscellaneous Problems of Time Complexity"
},
{
"code": null,
"e": 10323,
"s": 10276,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 10373,
"s": 10323,
"text": "Knowing the complexity in competitive programming"
},
{
"code": null,
"e": 10388,
"s": 10373,
"text": "BalajiPathange"
},
{
"code": null,
"e": 10400,
"s": 10388,
"text": "deekshadaga"
},
{
"code": null,
"e": 10418,
"s": 10400,
"text": "shankaramshubham8"
},
{
"code": null,
"e": 10431,
"s": 10418,
"text": "devilchandra"
},
{
"code": null,
"e": 10441,
"s": 10431,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10455,
"s": 10441,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 10467,
"s": 10455,
"text": "vikash36905"
},
{
"code": null,
"e": 10485,
"s": 10467,
"text": "suruchikumarimfp4"
},
{
"code": null,
"e": 10505,
"s": 10485,
"text": "singhankitasingh066"
},
{
"code": null,
"e": 10521,
"s": 10505,
"text": "time complexity"
},
{
"code": null,
"e": 10532,
"s": 10521,
"text": "Algorithms"
},
{
"code": null,
"e": 10541,
"s": 10532,
"text": "Analysis"
},
{
"code": null,
"e": 10552,
"s": 10541,
"text": "Algorithms"
}
] |
Parsing XML with DOM APIs in Python
|
10 May, 2020
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as below:
<?xml version="1.0"?><company> <name>GeeksForGeeks Company</name> <staff id="1"> <name>Amar Pandey</name> <salary>8.5 LPA</salary> </staff> <staff id="2"> <name>Akbhar Khan</name> <salary>6.5 LPA</salary> </staff> <staff id="3"> <name>Anthony Walter</name> <salary>3.2 LPA</salary> </staff></company>
Now, let’s parse the above XML using python. The below code demonstrates the process,
from xml.dom import minidom doc = minidom.parse("sample.xml") # doc.getElementsByTagName returns the NodeListname = doc.getElementsByTagName("name")[0]print(name.firstChild.data) staffs = doc.getElementsByTagName("staff")for staff in staffs: staff_id = staff.getAttribute("id") name = staff.getElementsByTagName("name")[0] salary = staff.getElementsByTagName("salary")[0] print("id:% s, name:% s, salary:% s" % (staff_id, name.firstChild.data, salary.firstChild.data))
Output:
GeeksForGeeks Company
id:1, name: Amar Pandey, salary:8.5 LPA
id:2, name: Akbar Khan, salary:6.5 LPA
id:3, name: Anthony Walter, salary:3.2 LPA
The same can also be done using a user-defined function as shown in the code below:
from xml.dom import minidom doc = minidom.parse("sample.xml") # user-defined functiondef getNodeText(node): nodelist = node.childNodes result = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: result.append(node.data) return ''.join(result) name = doc.getElementsByTagName("name")[0]print("Company Name : % s \n" % getNodeText(name)) staffs = doc.getElementsByTagName("staff")for staff in staffs: staff_id = staff.getAttribute("id") name = staff.getElementsByTagName("name")[0] salary = staff.getElementsByTagName("salary")[0] print("id:% s, name:% s, salary:% s" % (staff_id, getNodeText(name), getNodeText(salary)))
Output:
Company Name : GeeksForGeeks Company
id:1, name:Amar Pandey, salary:8.5 LPA
id:2, name:Akbhar Khan, salary:6.5 LPA
id:3, name:Anthony Walter, salary:3.2 LPA
Python-XML
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated."
},
{
"code": null,
"e": 382,
"s": 241,
"text": "Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as below:"
},
{
"code": "<?xml version=\"1.0\"?><company> <name>GeeksForGeeks Company</name> <staff id=\"1\"> <name>Amar Pandey</name> <salary>8.5 LPA</salary> </staff> <staff id=\"2\"> <name>Akbhar Khan</name> <salary>6.5 LPA</salary> </staff> <staff id=\"3\"> <name>Anthony Walter</name> <salary>3.2 LPA</salary> </staff></company>",
"e": 746,
"s": 382,
"text": null
},
{
"code": null,
"e": 832,
"s": 746,
"text": "Now, let’s parse the above XML using python. The below code demonstrates the process,"
},
{
"code": "from xml.dom import minidom doc = minidom.parse(\"sample.xml\") # doc.getElementsByTagName returns the NodeListname = doc.getElementsByTagName(\"name\")[0]print(name.firstChild.data) staffs = doc.getElementsByTagName(\"staff\")for staff in staffs: staff_id = staff.getAttribute(\"id\") name = staff.getElementsByTagName(\"name\")[0] salary = staff.getElementsByTagName(\"salary\")[0] print(\"id:% s, name:% s, salary:% s\" % (staff_id, name.firstChild.data, salary.firstChild.data))",
"e": 1345,
"s": 832,
"text": null
},
{
"code": null,
"e": 1353,
"s": 1345,
"text": "Output:"
},
{
"code": null,
"e": 1497,
"s": 1353,
"text": "GeeksForGeeks Company\nid:1, name: Amar Pandey, salary:8.5 LPA\nid:2, name: Akbar Khan, salary:6.5 LPA\nid:3, name: Anthony Walter, salary:3.2 LPA"
},
{
"code": null,
"e": 1581,
"s": 1497,
"text": "The same can also be done using a user-defined function as shown in the code below:"
},
{
"code": "from xml.dom import minidom doc = minidom.parse(\"sample.xml\") # user-defined functiondef getNodeText(node): nodelist = node.childNodes result = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: result.append(node.data) return ''.join(result) name = doc.getElementsByTagName(\"name\")[0]print(\"Company Name : % s \\n\" % getNodeText(name)) staffs = doc.getElementsByTagName(\"staff\")for staff in staffs: staff_id = staff.getAttribute(\"id\") name = staff.getElementsByTagName(\"name\")[0] salary = staff.getElementsByTagName(\"salary\")[0] print(\"id:% s, name:% s, salary:% s\" % (staff_id, getNodeText(name), getNodeText(salary)))",
"e": 2290,
"s": 1581,
"text": null
},
{
"code": null,
"e": 2298,
"s": 2290,
"text": "Output:"
},
{
"code": null,
"e": 2457,
"s": 2298,
"text": "Company Name : GeeksForGeeks Company \n\nid:1, name:Amar Pandey, salary:8.5 LPA\nid:2, name:Akbhar Khan, salary:6.5 LPA\nid:3, name:Anthony Walter, salary:3.2 LPA"
},
{
"code": null,
"e": 2468,
"s": 2457,
"text": "Python-XML"
},
{
"code": null,
"e": 2475,
"s": 2468,
"text": "Python"
},
{
"code": null,
"e": 2573,
"s": 2475,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2591,
"s": 2573,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2633,
"s": 2591,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2655,
"s": 2633,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2687,
"s": 2655,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2713,
"s": 2687,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2742,
"s": 2713,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2769,
"s": 2742,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2790,
"s": 2769,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2820,
"s": 2790,
"text": "Iterate over a list in Python"
}
] |
How to instantiate delegates in C#?
|
Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the
new expression is written similar to a method call, but without the arguments to the method.
For example −
public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);
You can also instantiate a delegate using an anonymous method −
//declare
delegate void Del(string str);
Del d = delegate(string name) {
Console.WriteLine("Notification received for: {0}", name);
};
Let us see an example that declare and instantiates a delegate −
Live Demo
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Value of Num: 35
Value of Num: 175
|
[
{
"code": null,
"e": 1255,
"s": 1062,
"text": "Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the\nnew expression is written similar to a method call, but without the arguments to the method."
},
{
"code": null,
"e": 1269,
"s": 1255,
"text": "For example −"
},
{
"code": null,
"e": 1363,
"s": 1269,
"text": "public delegate void printString(string s);\nprintString ps1 = new printString(WriteToScreen);"
},
{
"code": null,
"e": 1427,
"s": 1363,
"text": "You can also instantiate a delegate using an anonymous method −"
},
{
"code": null,
"e": 1565,
"s": 1427,
"text": "//declare\ndelegate void Del(string str);\nDel d = delegate(string name) {\n Console.WriteLine(\"Notification received for: {0}\", name);\n};"
},
{
"code": null,
"e": 1630,
"s": 1565,
"text": "Let us see an example that declare and instantiates a delegate −"
},
{
"code": null,
"e": 1641,
"s": 1630,
"text": " Live Demo"
},
{
"code": null,
"e": 2455,
"s": 1641,
"text": "using System;\n\ndelegate int NumberChanger(int n);\nnamespace DelegateAppl {\n\n class TestDelegate {\n\n static int num = 10;\n public static int AddNum(int p) {\n num += p;\n return num;\n }\n public static int MultNum(int q) {\n num *= q;\n return num;\n }\n public static int getNum() {\n return num;\n }\n static void Main(string[] args) {\n //create delegate instances\n NumberChanger nc1 = new NumberChanger(AddNum);\n NumberChanger nc2 = new NumberChanger(MultNum);\n\n //calling the methods using the delegate objects\n nc1(25);\n Console.WriteLine(\"Value of Num: {0}\", getNum());\n nc2(5);\n Console.WriteLine(\"Value of Num: {0}\", getNum());\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2490,
"s": 2455,
"text": "Value of Num: 35\nValue of Num: 175"
}
] |
How to fix org.springframework BeanDefinitionOverrideException
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we will see how to fix BeanDefinitionOverrideException.
You may get the BeanDefinitionOverrideException exception while running the test cases, when you update the spring boot version from 2.1.x to 2.2.x.
Here are the sample error logs while building the application.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
Add the below property in your test application.properties file.
spring.main.allow-bean-definition-overriding=true
That’s it, rebuild the application.
Spring Boot BeanDefinitionOverrideException
Happy Learning 🙂
How To Change Spring Boot Context Path
How to change Spring Boot Tomcat Port Number
Spring Boot MockMvc JUnit Test Example
Spring Boot Lazy Loading Beans Example
Spring Boot Environment Properties reading based on activeprofile
Simple Spring Boot Example
MicroServices Spring Boot Eureka Server Example
How to Get All Spring Beans Details Loaded in ICO
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
Spring Boot JPA Integration Example
How to Configure Spring Profile in Tomcat ?
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring Boot Tomcat session timeout
How To Change Spring Boot Context Path
How to change Spring Boot Tomcat Port Number
Spring Boot MockMvc JUnit Test Example
Spring Boot Lazy Loading Beans Example
Spring Boot Environment Properties reading based on activeprofile
Simple Spring Boot Example
MicroServices Spring Boot Eureka Server Example
How to Get All Spring Beans Details Loaded in ICO
How to use Spring Boot Random Port
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
Spring Boot JPA Integration Example
How to Configure Spring Profile in Tomcat ?
Spring Boot How to change the Tomcat to Jetty Server
How to set Spring Boot Tomcat session timeout
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 459,
"s": 398,
"text": "Here we will see how to fix BeanDefinitionOverrideException."
},
{
"code": null,
"e": 608,
"s": 459,
"text": "You may get the BeanDefinitionOverrideException exception while running the test cases, when you update the spring boot version from 2.1.x to 2.2.x."
},
{
"code": null,
"e": 671,
"s": 608,
"text": "Here are the sample error logs while building the application."
},
{
"code": null,
"e": 1819,
"s": 671,
"text": "java.lang.IllegalStateException: Failed to load ApplicationContext\nat org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)\nat org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)\nat org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)\nat org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)\nat org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)\nat org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)\nat org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)\nat org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)"
},
{
"code": null,
"e": 1884,
"s": 1819,
"text": "Add the below property in your test application.properties file."
},
{
"code": null,
"e": 1934,
"s": 1884,
"text": "spring.main.allow-bean-definition-overriding=true"
},
{
"code": null,
"e": 1970,
"s": 1934,
"text": "That’s it, rebuild the application."
},
{
"code": null,
"e": 2014,
"s": 1970,
"text": "Spring Boot BeanDefinitionOverrideException"
},
{
"code": null,
"e": 2031,
"s": 2014,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2681,
"s": 2031,
"text": "\nHow To Change Spring Boot Context Path\nHow to change Spring Boot Tomcat Port Number\nSpring Boot MockMvc JUnit Test Example\nSpring Boot Lazy Loading Beans Example\nSpring Boot Environment Properties reading based on activeprofile\nSimple Spring Boot Example\nMicroServices Spring Boot Eureka Server Example\nHow to Get All Spring Beans Details Loaded in ICO\nHow to use Spring Boot Random Port\nHow to set Spring Boot SetTimeZone\nSpring Boot Apache ActiveMq In Memory Example\nSpring Boot JPA Integration Example\nHow to Configure Spring Profile in Tomcat ?\nSpring Boot How to change the Tomcat to Jetty Server\nHow to set Spring Boot Tomcat session timeout\n"
},
{
"code": null,
"e": 2720,
"s": 2681,
"text": "How To Change Spring Boot Context Path"
},
{
"code": null,
"e": 2765,
"s": 2720,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 2804,
"s": 2765,
"text": "Spring Boot MockMvc JUnit Test Example"
},
{
"code": null,
"e": 2843,
"s": 2804,
"text": "Spring Boot Lazy Loading Beans Example"
},
{
"code": null,
"e": 2909,
"s": 2843,
"text": "Spring Boot Environment Properties reading based on activeprofile"
},
{
"code": null,
"e": 2936,
"s": 2909,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 2984,
"s": 2936,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 3034,
"s": 2984,
"text": "How to Get All Spring Beans Details Loaded in ICO"
},
{
"code": null,
"e": 3069,
"s": 3034,
"text": "How to use Spring Boot Random Port"
},
{
"code": null,
"e": 3104,
"s": 3069,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 3150,
"s": 3104,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 3186,
"s": 3150,
"text": "Spring Boot JPA Integration Example"
},
{
"code": null,
"e": 3230,
"s": 3186,
"text": "How to Configure Spring Profile in Tomcat ?"
},
{
"code": null,
"e": 3283,
"s": 3230,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 3329,
"s": 3283,
"text": "How to set Spring Boot Tomcat session timeout"
},
{
"code": null,
"e": 3335,
"s": 3333,
"text": "Δ"
},
{
"code": null,
"e": 3362,
"s": 3335,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 3389,
"s": 3362,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 3423,
"s": 3389,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 3464,
"s": 3423,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 3509,
"s": 3464,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 3547,
"s": 3509,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 3581,
"s": 3547,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 3612,
"s": 3581,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 3646,
"s": 3612,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 3679,
"s": 3646,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 3712,
"s": 3679,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 3752,
"s": 3712,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 3777,
"s": 3752,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 3808,
"s": 3777,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 3832,
"s": 3808,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 3878,
"s": 3832,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 3901,
"s": 3878,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 3928,
"s": 3901,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 3974,
"s": 3928,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 4014,
"s": 3974,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 4043,
"s": 4014,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 4077,
"s": 4043,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 4107,
"s": 4077,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 4143,
"s": 4107,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 4176,
"s": 4143,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 4209,
"s": 4176,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 4253,
"s": 4209,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 4287,
"s": 4253,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 4319,
"s": 4287,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 4347,
"s": 4319,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 4378,
"s": 4347,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 4419,
"s": 4378,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 4453,
"s": 4419,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 4478,
"s": 4453,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 4512,
"s": 4478,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 4548,
"s": 4512,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 4594,
"s": 4548,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 4645,
"s": 4594,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 4687,
"s": 4645,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 4718,
"s": 4687,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 4741,
"s": 4718,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 4771,
"s": 4741,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 4801,
"s": 4771,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 4850,
"s": 4801,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 4884,
"s": 4850,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 4917,
"s": 4884,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 4946,
"s": 4917,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 4978,
"s": 4946,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 5015,
"s": 4978,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 5044,
"s": 5015,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 5073,
"s": 5044,
"text": " Spring Boot – MockMvc JUnit"
}
] |
Audio processing using Pydub and Google speechRecognition API - GeeksforGeeks
|
10 Jan, 2019
Audio files are a widespread means of transferring information. So, let’s see how to break down audio files (.wav files) into smaller chunks, and to recognize the content in them and store it to a text file. To know more about audio files and their formats, refer Audio_formats.
Need to break down an audio file?
When we do any processing on audio files, it takes a lot of time. Here, processing can mean anything. For example, we may want to increase or decrease the frequency of the audio, or as done in this article, recognize the content in the audio file. By breaking it down into small audio files called chunks, we can ensure that the processing happens fast.
Required Installations:
pip3 install pydub
pip3 install audioread
pip3 install SpeechRecognition
There are majorly two steps in the program.
Step #1: It deals with slicing the audio files into small chunks of a constant interval. The slicing can be done with, or without overlap. Overlap means that the next chunk created will start from a constant time backward, so that during the slicing if any audio/word gets cut, it can be covered by this overlap. For example, if the audio file is 22 seconds, and the overlap is 1.5 seconds, the timing of these chunks will be:
chunk1 : 0 - 5 seconds
chunk2 : 3.5 - 8.5 seconds
chunk3 : 7 - 12 seconds
chunk4 : 10.5 - 15.5 seconds
chunk5 : 14 - 19.5 seconds
chunk6 : 18 - 22 seconds
We can ignore this overlap by setting the overlap to 0.
Step #2: It deals with working with the sliced audio file to do whatever the user requires. Here, for demonstration purposes, the chunks have been passed through the Google Speech recognition module, and the text has been written to a separate file. To understand how to use the Google Speech Recognition module to recognize the audio from a microphone, refer this. In this article, we will be using the sliced audio files to recognize the content.
Step #2 is done in a loop inside Step #1. As soon as the audio file is sliced into the chunk, the chunk is recognized. This process continues till the end of the audio file.
Example:
Input : Geek.wav
Output :
Screenshot of cmd running the code:
Text File: recognized
Below is the implementation:
# Import necessary librariesfrom pydub import AudioSegmentimport speech_recognition as sr # Input audio file to be slicedaudio = AudioSegment.from_wav("1.wav") '''Step #1 - Slicing the audio file into smaller chunks.'''# Length of the audiofile in millisecondsn = len(audio) # Variable to count the number of sliced chunkscounter = 1 # Text file to write the recognized audiofh = open("recognized.txt", "w+") # Interval length at which to slice the audio file.# If length is 22 seconds, and interval is 5 seconds,# The chunks created will be:# chunk1 : 0 - 5 seconds# chunk2 : 5 - 10 seconds# chunk3 : 10 - 15 seconds# chunk4 : 15 - 20 seconds# chunk5 : 20 - 22 secondsinterval = 5 * 1000 # Length of audio to overlap. # If length is 22 seconds, and interval is 5 seconds,# With overlap as 1.5 seconds,# The chunks created will be:# chunk1 : 0 - 5 seconds# chunk2 : 3.5 - 8.5 seconds# chunk3 : 7 - 12 seconds# chunk4 : 10.5 - 15.5 seconds# chunk5 : 14 - 19.5 seconds# chunk6 : 18 - 22 secondsoverlap = 1.5 * 1000 # Initialize start and end seconds to 0start = 0end = 0 # Flag to keep track of end of file.# When audio reaches its end, flag is set to 1 and we breakflag = 0 # Iterate from 0 to end of the file,# with increment = intervalfor i in range(0, 2 * n, interval): # During first iteration, # start is 0, end is the interval if i == 0: start = 0 end = interval # All other iterations, # start is the previous end - overlap # end becomes end + interval else: start = end - overlap end = start + interval # When end becomes greater than the file length, # end is set to the file length # flag is set to 1 to indicate break. if end >= n: end = n flag = 1 # Storing audio file from the defined start to end chunk = audio[start:end] # Filename / Path to store the sliced audio filename = 'chunk'+str(counter)+'.wav' # Store the sliced audio file to the defined path chunk.export(filename, format ="wav") # Print information about the current chunk print("Processing chunk "+str(counter)+". Start = " +str(start)+" end = "+str(end)) # Increment counter for the next chunk counter = counter + 1 # Slicing of the audio file is done. # Skip the below steps if there is some other usage # for the sliced audio files. '''Step #2 - Recognizing the chunk and writing to a file.''' # Here, Google Speech Recognition is used # to take each chunk and recognize the text in it. # Specify the audio file to recognize AUDIO_FILE = filename # Initialize the recognizer r = sr.Recognizer() # Traverse the audio file and listen to the audio with sr.AudioFile(AUDIO_FILE) as source: audio_listened = r.listen(source) # Try to recognize the listened audio # And catch expections. try: rec = r.recognize_google(audio_listened) # If recognized, write into the file. fh.write(rec+" ") # If google could not understand the audio except sr.UnknownValueError: print("Could not understand audio") # If the results cannot be requested from Google. # Probably an internet connection error. except sr.RequestError as e: print("Could not request results.") # Check for flag. # If flag is 1, end of the whole audio reached. # Close the file and break. if flag == 1: fh.close() break
Output:
recognized.txt –As we can see in the above screenshot, all these chunks are stored in the local system. We have now successfully sliced the audio file with an overlap and recognized the content from the chunks.
Advantages of this method:
The interval can be set to any length depending on how long we need the chunks to be.
Overlap ensures that no data is lost even if any word is said precisely at the end of the interval.
The chunks can all be stored in different audio files and used later if need be.
Any processing which can be done on an audio file can be done in these chunks as well, as they are just audio files.
Disadvantages of this method:
Using Google Speech Recognition requires an active internet connection.
After the overlap, some text processing should be done to remove the duplicate words recognized.
The accuracy of Google Speech Recognition varies on a lot of factors like background noise, speaker’s accent etc.
python-utility
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
ML | Linear Regression
Python | Decision tree implementation
System Design Tutorial
Copying Files to and from Docker Containers
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24646,
"s": 24618,
"text": "\n10 Jan, 2019"
},
{
"code": null,
"e": 24925,
"s": 24646,
"text": "Audio files are a widespread means of transferring information. So, let’s see how to break down audio files (.wav files) into smaller chunks, and to recognize the content in them and store it to a text file. To know more about audio files and their formats, refer Audio_formats."
},
{
"code": null,
"e": 24959,
"s": 24925,
"text": "Need to break down an audio file?"
},
{
"code": null,
"e": 25313,
"s": 24959,
"text": "When we do any processing on audio files, it takes a lot of time. Here, processing can mean anything. For example, we may want to increase or decrease the frequency of the audio, or as done in this article, recognize the content in the audio file. By breaking it down into small audio files called chunks, we can ensure that the processing happens fast."
},
{
"code": null,
"e": 25337,
"s": 25313,
"text": "Required Installations:"
},
{
"code": null,
"e": 25410,
"s": 25337,
"text": "pip3 install pydub\npip3 install audioread\npip3 install SpeechRecognition"
},
{
"code": null,
"e": 25454,
"s": 25410,
"text": "There are majorly two steps in the program."
},
{
"code": null,
"e": 25881,
"s": 25454,
"text": "Step #1: It deals with slicing the audio files into small chunks of a constant interval. The slicing can be done with, or without overlap. Overlap means that the next chunk created will start from a constant time backward, so that during the slicing if any audio/word gets cut, it can be covered by this overlap. For example, if the audio file is 22 seconds, and the overlap is 1.5 seconds, the timing of these chunks will be:"
},
{
"code": null,
"e": 26048,
"s": 25881,
"text": " chunk1 : 0 - 5 seconds\n chunk2 : 3.5 - 8.5 seconds\n chunk3 : 7 - 12 seconds\n chunk4 : 10.5 - 15.5 seconds\n chunk5 : 14 - 19.5 seconds\n chunk6 : 18 - 22 seconds"
},
{
"code": null,
"e": 26104,
"s": 26048,
"text": "We can ignore this overlap by setting the overlap to 0."
},
{
"code": null,
"e": 26553,
"s": 26104,
"text": "Step #2: It deals with working with the sliced audio file to do whatever the user requires. Here, for demonstration purposes, the chunks have been passed through the Google Speech recognition module, and the text has been written to a separate file. To understand how to use the Google Speech Recognition module to recognize the audio from a microphone, refer this. In this article, we will be using the sliced audio files to recognize the content."
},
{
"code": null,
"e": 26727,
"s": 26553,
"text": "Step #2 is done in a loop inside Step #1. As soon as the audio file is sliced into the chunk, the chunk is recognized. This process continues till the end of the audio file."
},
{
"code": null,
"e": 26736,
"s": 26727,
"text": "Example:"
},
{
"code": null,
"e": 26828,
"s": 26736,
"text": "Input : Geek.wav\n\n\nOutput : \nScreenshot of cmd running the code:\n\n\nText File: recognized\n\n"
},
{
"code": null,
"e": 26858,
"s": 26828,
"text": " Below is the implementation:"
},
{
"code": "# Import necessary librariesfrom pydub import AudioSegmentimport speech_recognition as sr # Input audio file to be slicedaudio = AudioSegment.from_wav(\"1.wav\") '''Step #1 - Slicing the audio file into smaller chunks.'''# Length of the audiofile in millisecondsn = len(audio) # Variable to count the number of sliced chunkscounter = 1 # Text file to write the recognized audiofh = open(\"recognized.txt\", \"w+\") # Interval length at which to slice the audio file.# If length is 22 seconds, and interval is 5 seconds,# The chunks created will be:# chunk1 : 0 - 5 seconds# chunk2 : 5 - 10 seconds# chunk3 : 10 - 15 seconds# chunk4 : 15 - 20 seconds# chunk5 : 20 - 22 secondsinterval = 5 * 1000 # Length of audio to overlap. # If length is 22 seconds, and interval is 5 seconds,# With overlap as 1.5 seconds,# The chunks created will be:# chunk1 : 0 - 5 seconds# chunk2 : 3.5 - 8.5 seconds# chunk3 : 7 - 12 seconds# chunk4 : 10.5 - 15.5 seconds# chunk5 : 14 - 19.5 seconds# chunk6 : 18 - 22 secondsoverlap = 1.5 * 1000 # Initialize start and end seconds to 0start = 0end = 0 # Flag to keep track of end of file.# When audio reaches its end, flag is set to 1 and we breakflag = 0 # Iterate from 0 to end of the file,# with increment = intervalfor i in range(0, 2 * n, interval): # During first iteration, # start is 0, end is the interval if i == 0: start = 0 end = interval # All other iterations, # start is the previous end - overlap # end becomes end + interval else: start = end - overlap end = start + interval # When end becomes greater than the file length, # end is set to the file length # flag is set to 1 to indicate break. if end >= n: end = n flag = 1 # Storing audio file from the defined start to end chunk = audio[start:end] # Filename / Path to store the sliced audio filename = 'chunk'+str(counter)+'.wav' # Store the sliced audio file to the defined path chunk.export(filename, format =\"wav\") # Print information about the current chunk print(\"Processing chunk \"+str(counter)+\". Start = \" +str(start)+\" end = \"+str(end)) # Increment counter for the next chunk counter = counter + 1 # Slicing of the audio file is done. # Skip the below steps if there is some other usage # for the sliced audio files. '''Step #2 - Recognizing the chunk and writing to a file.''' # Here, Google Speech Recognition is used # to take each chunk and recognize the text in it. # Specify the audio file to recognize AUDIO_FILE = filename # Initialize the recognizer r = sr.Recognizer() # Traverse the audio file and listen to the audio with sr.AudioFile(AUDIO_FILE) as source: audio_listened = r.listen(source) # Try to recognize the listened audio # And catch expections. try: rec = r.recognize_google(audio_listened) # If recognized, write into the file. fh.write(rec+\" \") # If google could not understand the audio except sr.UnknownValueError: print(\"Could not understand audio\") # If the results cannot be requested from Google. # Probably an internet connection error. except sr.RequestError as e: print(\"Could not request results.\") # Check for flag. # If flag is 1, end of the whole audio reached. # Close the file and break. if flag == 1: fh.close() break",
"e": 30338,
"s": 26858,
"text": null
},
{
"code": null,
"e": 30346,
"s": 30338,
"text": "Output:"
},
{
"code": null,
"e": 30557,
"s": 30346,
"text": "recognized.txt –As we can see in the above screenshot, all these chunks are stored in the local system. We have now successfully sliced the audio file with an overlap and recognized the content from the chunks."
},
{
"code": null,
"e": 30584,
"s": 30557,
"text": "Advantages of this method:"
},
{
"code": null,
"e": 30670,
"s": 30584,
"text": "The interval can be set to any length depending on how long we need the chunks to be."
},
{
"code": null,
"e": 30770,
"s": 30670,
"text": "Overlap ensures that no data is lost even if any word is said precisely at the end of the interval."
},
{
"code": null,
"e": 30851,
"s": 30770,
"text": "The chunks can all be stored in different audio files and used later if need be."
},
{
"code": null,
"e": 30968,
"s": 30851,
"text": "Any processing which can be done on an audio file can be done in these chunks as well, as they are just audio files."
},
{
"code": null,
"e": 30998,
"s": 30968,
"text": "Disadvantages of this method:"
},
{
"code": null,
"e": 31070,
"s": 30998,
"text": "Using Google Speech Recognition requires an active internet connection."
},
{
"code": null,
"e": 31167,
"s": 31070,
"text": "After the overlap, some text processing should be done to remove the duplicate words recognized."
},
{
"code": null,
"e": 31281,
"s": 31167,
"text": "The accuracy of Google Speech Recognition varies on a lot of factors like background noise, speaker’s accent etc."
},
{
"code": null,
"e": 31296,
"s": 31281,
"text": "python-utility"
},
{
"code": null,
"e": 31322,
"s": 31296,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 31329,
"s": 31322,
"text": "Python"
},
{
"code": null,
"e": 31427,
"s": 31329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31436,
"s": 31427,
"text": "Comments"
},
{
"code": null,
"e": 31449,
"s": 31436,
"text": "Old Comments"
},
{
"code": null,
"e": 31463,
"s": 31449,
"text": "Decision Tree"
},
{
"code": null,
"e": 31486,
"s": 31463,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 31524,
"s": 31486,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 31547,
"s": 31524,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 31591,
"s": 31547,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 31619,
"s": 31591,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31669,
"s": 31619,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31691,
"s": 31669,
"text": "Python map() function"
}
] |
Kth smallest element | Practice | GeeksforGeeks
|
Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
Example 1:
Input:
N = 6
arr[] = 7 10 4 3 20 15
K = 3
Output : 7
Explanation :
3rd smallest element in the given
array is 7.
Example 2:
Input:
N = 5
arr[] = 7 10 4 20 15
K = 4
Output : 15
Explanation :
4th smallest element in the given
array is 15.
Constraints:
1 <= N <= 105
1 <= arr[i] <= 105
1 <= K <= N
+1
diwakarghosh42 hours ago
Python Solution 1liner
arr.sort()
return arr[k-1]
0
kumkumjain61612 hours ago
class Solution{
public static int kthSmallest(int[] arr, int l, int r, int k)
{
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i =0; i<k;i++){
pq.add(arr[i]);
}
for(int i = k; i<=r;i++){
if(arr[i] < pq.peek()){
pq.poll();
pq.add(arr[i]);
}
}
int ans = pq.peek();
return ans;
}
}
+1
mamidisettynikhilesh18 hours ago
class Solution{ public static int kthSmallest(int[] arr, int l, int r, int k) { //Your code here Arrays.sort(arr); return arr[k-1]; } }
0
himanshusethin2 days ago
sort(arr,arr+r+1); return arr[k-1];
-1
singhpriti2813 days ago
priority_queue<int>maxh;
for(int i=l; i<r; i++){ maxh.push(arr[i]); if(maxh.size()>k){ maxh.pop(); } } return maxh.top();
0
parmeetsghai
This comment was deleted.
+1
harshscode4 days ago
in O(n)...min heap.......
priority_queue<int,vector<int>,greater<int>> q;
for(int i=l;i<=r;i++)
q.push(a[i]);
for(int i=1;i<k;i++)
q.pop();
int ans=q.top();
return ans;
0
koulikmaity5 days ago
int kthSmallest(int arr[], int l, int r, int k) { priority_queue<int> q; // step: 1 for(int i=0; i<k; i++) { q.push(arr[i]); } // step: 2 for(int i=k; i<=r; i++) { if(q.top() > arr[i]) { q.pop(); q.push(arr[i]); } } // step: 3 int ans = q.top(); return ans; }
+1
devanshukum7586 days ago
priority_queue<int> maxh; int n = r-l+1; for(int i =0; i <k; i++){ maxh.push(arr[i]); } for( int i =k; i <n; i++){ if( arr[i] < maxh.top()){ maxh.pop(); maxh.push(arr[i]); } } return maxh.top(); }
-12
prasantpoudel331 week ago
def kthSmallest(self,arr, l, r, k):
arr.sort()
return arr[k-1]
easy
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 430,
"s": 238,
"text": "Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct."
},
{
"code": null,
"e": 441,
"s": 430,
"text": "Example 1:"
},
{
"code": null,
"e": 556,
"s": 441,
"text": "Input:\nN = 6\narr[] = 7 10 4 3 20 15\nK = 3\nOutput : 7\nExplanation :\n3rd smallest element in the given \narray is 7.\n"
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 2:"
},
{
"code": null,
"e": 681,
"s": 567,
"text": "Input:\nN = 5\narr[] = 7 10 4 20 15\nK = 4\nOutput : 15\nExplanation :\n4th smallest element in the given \narray is 15."
},
{
"code": null,
"e": 741,
"s": 681,
"text": "Constraints:\n1 <= N <= 105\n1 <= arr[i] <= 105\n1 <= K <= N\n "
},
{
"code": null,
"e": 744,
"s": 741,
"text": "+1"
},
{
"code": null,
"e": 769,
"s": 744,
"text": "diwakarghosh42 hours ago"
},
{
"code": null,
"e": 792,
"s": 769,
"text": "Python Solution 1liner"
},
{
"code": null,
"e": 803,
"s": 792,
"text": "arr.sort()"
},
{
"code": null,
"e": 819,
"s": 803,
"text": "return arr[k-1]"
},
{
"code": null,
"e": 821,
"s": 819,
"text": "0"
},
{
"code": null,
"e": 847,
"s": 821,
"text": "kumkumjain61612 hours ago"
},
{
"code": null,
"e": 1290,
"s": 847,
"text": "class Solution{\n public static int kthSmallest(int[] arr, int l, int r, int k) \n { \n PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());\n for(int i =0; i<k;i++){\n pq.add(arr[i]);\n }\n for(int i = k; i<=r;i++){\n if(arr[i] < pq.peek()){\n pq.poll();\n pq.add(arr[i]);\n }\n }\n int ans = pq.peek();\n return ans;\n } \n}\n"
},
{
"code": null,
"e": 1293,
"s": 1290,
"text": "+1"
},
{
"code": null,
"e": 1326,
"s": 1293,
"text": "mamidisettynikhilesh18 hours ago"
},
{
"code": null,
"e": 1488,
"s": 1326,
"text": "class Solution{ public static int kthSmallest(int[] arr, int l, int r, int k) { //Your code here Arrays.sort(arr); return arr[k-1]; } }"
},
{
"code": null,
"e": 1490,
"s": 1488,
"text": "0"
},
{
"code": null,
"e": 1515,
"s": 1490,
"text": "himanshusethin2 days ago"
},
{
"code": null,
"e": 1557,
"s": 1515,
"text": "sort(arr,arr+r+1); return arr[k-1];"
},
{
"code": null,
"e": 1560,
"s": 1557,
"text": "-1"
},
{
"code": null,
"e": 1584,
"s": 1560,
"text": "singhpriti2813 days ago"
},
{
"code": null,
"e": 1610,
"s": 1584,
"text": "priority_queue<int>maxh; "
},
{
"code": null,
"e": 1745,
"s": 1610,
"text": " for(int i=l; i<r; i++){ maxh.push(arr[i]); if(maxh.size()>k){ maxh.pop(); } } return maxh.top();"
},
{
"code": null,
"e": 1747,
"s": 1745,
"text": "0"
},
{
"code": null,
"e": 1760,
"s": 1747,
"text": "parmeetsghai"
},
{
"code": null,
"e": 1786,
"s": 1760,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1789,
"s": 1786,
"text": "+1"
},
{
"code": null,
"e": 1810,
"s": 1789,
"text": "harshscode4 days ago"
},
{
"code": null,
"e": 2036,
"s": 1810,
"text": "in O(n)...min heap.......\npriority_queue<int,vector<int>,greater<int>> q;\n for(int i=l;i<=r;i++)\n q.push(a[i]);\n \n for(int i=1;i<k;i++)\n q.pop();\n int ans=q.top();\n return ans;"
},
{
"code": null,
"e": 2038,
"s": 2036,
"text": "0"
},
{
"code": null,
"e": 2060,
"s": 2038,
"text": "koulikmaity5 days ago"
},
{
"code": null,
"e": 2483,
"s": 2060,
"text": "int kthSmallest(int arr[], int l, int r, int k) { priority_queue<int> q; // step: 1 for(int i=0; i<k; i++) { q.push(arr[i]); } // step: 2 for(int i=k; i<=r; i++) { if(q.top() > arr[i]) { q.pop(); q.push(arr[i]); } } // step: 3 int ans = q.top(); return ans; }"
},
{
"code": null,
"e": 2486,
"s": 2483,
"text": "+1"
},
{
"code": null,
"e": 2511,
"s": 2486,
"text": "devanshukum7586 days ago"
},
{
"code": null,
"e": 2805,
"s": 2511,
"text": " priority_queue<int> maxh; int n = r-l+1; for(int i =0; i <k; i++){ maxh.push(arr[i]); } for( int i =k; i <n; i++){ if( arr[i] < maxh.top()){ maxh.pop(); maxh.push(arr[i]); } } return maxh.top(); }"
},
{
"code": null,
"e": 2809,
"s": 2805,
"text": "-12"
},
{
"code": null,
"e": 2835,
"s": 2809,
"text": "prasantpoudel331 week ago"
},
{
"code": null,
"e": 2923,
"s": 2835,
"text": "def kthSmallest(self,arr, l, r, k):\n \n arr.sort()\n\n return arr[k-1]"
},
{
"code": null,
"e": 2928,
"s": 2923,
"text": "easy"
},
{
"code": null,
"e": 3076,
"s": 2930,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3112,
"s": 3076,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3122,
"s": 3112,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3132,
"s": 3122,
"text": "\nContest\n"
},
{
"code": null,
"e": 3195,
"s": 3132,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3343,
"s": 3195,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3551,
"s": 3343,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3657,
"s": 3551,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C# Program for Subset Sum Problem | DP-25 - GeeksforGeeks
|
12 Dec, 2018
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.Example:
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
Following is naive recursive implementation that simply follows the recursive structure mentioned above.
C#
// A recursive solution for subset sum problemusing System; class GFG { // Returns true if there is a subset of set[] with sum // equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } // Driver program public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine("Found a subset with given sum"); else Console.WriteLine("No subset with given sum"); }} // This code is contributed by Sam007
Found a subset with given sum
We can solve the problem in Pseudo-polynomial time using Dynamic programming.
C#
// A Dynamic Programming solution for subset sum problemusing System; class GFG { // Returns true if there is a subset // of set[] with sun equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // The value of subset[i][j] will be true if there // is a subset of set[0..j-1] with sum equal to i bool[, ] subset = new bool[sum + 1, n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0, i] = true; // If sum is not 0 and set is empty, then answer is false for (int i = 1; i <= sum; i++) subset[i, 0] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i, j] = subset[i, j - 1]; if (i >= set[j - 1]) subset[i, j] = subset[i, j] || subset[i - set[j - 1], j - 1]; } } return subset[sum, n]; } // Driver program public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine("Found a subset with given sum"); else Console.WriteLine("No subset with given sum"); }}// This code is contributed by Sam007
Found a subset with given sum
Please refer complete article on Subset Sum Problem | DP-25 for more details!
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to Print a New Line in C#
C# Program to Convert a Binary String to an Integer
C# Program to print all permutations of a given string
Different Ways to Take Input and Print a Float Value in C#
C# Program to Read and Write a Byte Array to File using FileStream Class
C# Program to Demonstrate the IList Interface
How to Convert ASCII Char to Byte in C#?
C# Program to Check a Specified Type is an Enum or Not
How to Calculate the Code Execution Time in C#?
How to Remove Duplicate Values From an Array in C#?
|
[
{
"code": null,
"e": 25174,
"s": 25146,
"text": "\n12 Dec, 2018"
},
{
"code": null,
"e": 25314,
"s": 25174,
"text": "Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.Example:"
},
{
"code": null,
"e": 25415,
"s": 25314,
"text": "Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9\nOutput: True //There is a subset (4, 5) with sum 9.\n"
},
{
"code": null,
"e": 25520,
"s": 25415,
"text": "Following is naive recursive implementation that simply follows the recursive structure mentioned above."
},
{
"code": null,
"e": 25523,
"s": 25520,
"text": "C#"
},
{
"code": "// A recursive solution for subset sum problemusing System; class GFG { // Returns true if there is a subset of set[] with sum // equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } // Driver program public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine(\"Found a subset with given sum\"); else Console.WriteLine(\"No subset with given sum\"); }} // This code is contributed by Sam007",
"e": 26647,
"s": 25523,
"text": null
},
{
"code": null,
"e": 26678,
"s": 26647,
"text": "Found a subset with given sum\n"
},
{
"code": null,
"e": 26756,
"s": 26678,
"text": "We can solve the problem in Pseudo-polynomial time using Dynamic programming."
},
{
"code": null,
"e": 26759,
"s": 26756,
"text": "C#"
},
{
"code": "// A Dynamic Programming solution for subset sum problemusing System; class GFG { // Returns true if there is a subset // of set[] with sun equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // The value of subset[i][j] will be true if there // is a subset of set[0..j-1] with sum equal to i bool[, ] subset = new bool[sum + 1, n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0, i] = true; // If sum is not 0 and set is empty, then answer is false for (int i = 1; i <= sum; i++) subset[i, 0] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i, j] = subset[i, j - 1]; if (i >= set[j - 1]) subset[i, j] = subset[i, j] || subset[i - set[j - 1], j - 1]; } } return subset[sum, n]; } // Driver program public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine(\"Found a subset with given sum\"); else Console.WriteLine(\"No subset with given sum\"); }}// This code is contributed by Sam007",
"e": 28129,
"s": 26759,
"text": null
},
{
"code": null,
"e": 28160,
"s": 28129,
"text": "Found a subset with given sum\n"
},
{
"code": null,
"e": 28238,
"s": 28160,
"text": "Please refer complete article on Subset Sum Problem | DP-25 for more details!"
},
{
"code": null,
"e": 28250,
"s": 28238,
"text": "C# Programs"
},
{
"code": null,
"e": 28348,
"s": 28250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28357,
"s": 28348,
"text": "Comments"
},
{
"code": null,
"e": 28370,
"s": 28357,
"text": "Old Comments"
},
{
"code": null,
"e": 28404,
"s": 28370,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 28456,
"s": 28404,
"text": "C# Program to Convert a Binary String to an Integer"
},
{
"code": null,
"e": 28511,
"s": 28456,
"text": "C# Program to print all permutations of a given string"
},
{
"code": null,
"e": 28570,
"s": 28511,
"text": "Different Ways to Take Input and Print a Float Value in C#"
},
{
"code": null,
"e": 28643,
"s": 28570,
"text": "C# Program to Read and Write a Byte Array to File using FileStream Class"
},
{
"code": null,
"e": 28689,
"s": 28643,
"text": "C# Program to Demonstrate the IList Interface"
},
{
"code": null,
"e": 28730,
"s": 28689,
"text": "How to Convert ASCII Char to Byte in C#?"
},
{
"code": null,
"e": 28785,
"s": 28730,
"text": "C# Program to Check a Specified Type is an Enum or Not"
},
{
"code": null,
"e": 28833,
"s": 28785,
"text": "How to Calculate the Code Execution Time in C#?"
}
] |
Hangman Game in Python?
|
Hangman is a classic word game in which participants needs to guess as many secret words as you can before time runs out! So, it’s a nice game to learn new words, one letter at a time!
So we are going to write python script for this classic game “hangman”.
#importing the time module
import time
#welcoming the user
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
print ("")
#wait for 1 second
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
#here we set the secret
word= ("Secret")
word = word.lower()
#creates an variable with an empty value
guesses = ''
#determine the number of turns
turns = 12
# Create a while loop
#check if the turns are more than zero
while turns > 0:
# make a counter that starts with zero
failed = 0
# for every character in secret_word
for char in word:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print (char, )
else:
# if not found, print a dash
print ("_",)
# and increase the failed counter with one
failed += 1
# if failed is equal to zero
# print You Won
if failed == 0:
print ("You won" )
# exit the script
break
print
# ask the user go guess a character
guess = input("guess a character:")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
# turns counter decreases with 1 (now 9)
turns -= 1
# print wrong
print ("Wrong")
# how many turns are left
print("You have", + turns, 'more guesses' )
# if the turns are equal to zero
if turns == 0:
# print "You Loose"
print ("You Loose")
================== RESTART: C:\Python\Python361\hangman1.py ==================
What is your name? Raj
Hello, Raj Time to play hangman!
Start guessing...
_
_
_
_
_
_
guess a character:s
s
_
_
_
_
_
guess a character:h
Wrong
You have 11 more guesses
s
_
_
_
_
_
guess a character:e
s
e
_
_
e
_
guess a character:c
s
e
c
_
e
_
guess a character:r
s
e
c
r
e
_
guess a character:e
s
e
c
r
e
_
guess a character:t
s
e
c
r
e
t
You won
>>>
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "Hangman is a classic word game in which participants needs to guess as many secret words as you can before time runs out! So, it’s a nice game to learn new words, one letter at a time!"
},
{
"code": null,
"e": 1319,
"s": 1247,
"text": "So we are going to write python script for this classic game “hangman”."
},
{
"code": null,
"e": 2750,
"s": 1319,
"text": "#importing the time module\nimport time\n\n#welcoming the user\nname = input(\"What is your name? \")\n\nprint(\"Hello, \" + name, \"Time to play hangman!\")\n\nprint (\"\")\n\n#wait for 1 second\ntime.sleep(1)\n\nprint (\"Start guessing...\")\ntime.sleep(0.5)\n\n#here we set the secret\nword= (\"Secret\")\nword = word.lower()\n\n#creates an variable with an empty value\nguesses = ''\n\n#determine the number of turns\nturns = 12\n\n# Create a while loop\n\n#check if the turns are more than zero\nwhile turns > 0:\n\n # make a counter that starts with zero\n failed = 0\n\n # for every character in secret_word\n for char in word:\n\n # see if the character is in the players guess\n if char in guesses:\n\n # print then out the character\n print (char, )\n\n else:\n\n # if not found, print a dash\n print (\"_\",)\n\n # and increase the failed counter with one\n failed += 1\n\n# if failed is equal to zero\n\n# print You Won\nif failed == 0:\n print (\"You won\" )\n\n# exit the script\n break\n\nprint\n# ask the user go guess a character\nguess = input(\"guess a character:\")\n\n# set the players guess to guesses\nguesses += guess\n\n# if the guess is not found in the secret word\nif guess not in word:\n\n# turns counter decreases with 1 (now 9)\nturns -= 1\n\n# print wrong\nprint (\"Wrong\")\n\n# how many turns are left\nprint(\"You have\", + turns, 'more guesses' )\n\n# if the turns are equal to zero\n if turns == 0:\n\n # print \"You Loose\"\n print (\"You Loose\")"
},
{
"code": null,
"e": 3183,
"s": 2750,
"text": "================== RESTART: C:\\Python\\Python361\\hangman1.py ==================\nWhat is your name? Raj\nHello, Raj Time to play hangman!\n\nStart guessing...\n_\n_\n_\n_\n_\n_\nguess a character:s\ns\n_\n_\n_\n_\n_\nguess a character:h\nWrong\nYou have 11 more guesses\ns\n_\n_\n_\n_\n_\nguess a character:e\ns\ne\n_\n_\ne\n_\nguess a character:c\ns\ne\nc\n_\ne\n_\nguess a character:r\ns\ne\nc\nr\ne\n_\nguess a character:e\ns\ne\nc\nr\ne\n_\nguess a character:t\ns\ne\nc\nr\ne\nt\nYou won\n>>>"
}
] |
Number of unique rectangles formed using N unit squares - GeeksforGeeks
|
29 Nov, 2021
You are given N unit squares (squares with side length 1 unit), and you are asked to make rectangles using these squares. You have to count the number of rotationally unique rectangles than you can make. What does rotationally unique mean? Well, two rectangles are rotationally unique if one can’t be rotated to become equivalent to the other one.
Example – The 4×2 rectangle can be rotated 90 degrees clockwise to make it the exact same as the 2×4 rectangle and so these are not rotationally unique.
Examples :
Input : N = 4
Output : 5
We can make following five rectangles
1 x 1, 1 x 2, 2 x 2, 1 x 3 and 1 x 4
Input : N = 5
Output : 6
Input : 6
Output : 8
So how do we solve this problem? Every rectangle is uniquely determined by its length and its height. A rectangle of length = l and height = h then l * h <= n is considered equivalent to a rectangle with length = h and height = l provided l is not equal to h. If we can have some sort of “ordering” in these pairs then we can avoid counting (l, h) and (h, l) as different rectangles. One way to define such an ordering is:
Assume that length <= height and count for all such pairs such that length*height <= n. We have, length <= height or, length*length <= length*height or, length*length <= n or, length <= sqrt(n)
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count rotationally equivalent// rectangles with n unit squares#include<bits/stdc++.h>using namespace std; int countRect(int n){ int ans = 0; for (int length = 1; length <= sqrt(n); ++length) for (int height = length; height*length <= n; ++height) // height >= length is maintained ans++; return ans;} // Driver codeint main() { int n = 5; printf("%d", countRect(n)); return 0;}
// Java program to count rotationally equivalent// rectangles with n unit squaresclass GFG { static int countRect(int n) { int ans = 0; for (int length = 1; length <= Math.sqrt(n); ++length) for (int height = length; height*length <= n; ++height) // height >= length is maintained ans++; return ans; } //driver code public static void main (String[] args) { int n = 5; System.out.print(countRect(n)); }} // This code is contributed by Anant Agarwal.
# Python3 program to count rotationally # equivalent rectangles with n unit squaresimport math def countRect(n): ans = 0 for length in range(1, int(math.sqrt(n)) + 1): height = length while(height * length <= n): # height >= length is maintained ans += 1 height += 1 return ans # Driver coden = 5print(countRect(n)) # This code is contributed by Anant Agarwal.
// C# program to count rotationally // equivalent rectangles with n unit// squaresusing System; class GFG { static int countRect(int n) { int ans = 0; for (int length = 1; length <= Math.Sqrt(n); ++length) for (int height = length; height*length <= n; ++height) ans++; return ans; } //driver code public static void Main() { int n = 5; Console.Write(countRect(n)); }} //This code is contributed by Anant Agarwal.
<?php// PHP program to count // rotationally equivalent // rectangles with n unit squaresfunction countRect($n){ $ans = 0; for ($length = 1; $length <= sqrt($n); $length++) for ($height = $length; $height * $length <= $n; $height++) // height >= length is maintained $ans++; return $ans;} // Driver code$n = 5;echo countRect($n); // This code is contributed by @ajit?>
<script> // Javascript program to count rotationally // equivalent rectangles with n unit// squaresfunction countRect(n){ let ans = 0; for(let length = 1; length <= parseInt(Math.sqrt(n), 10); ++length) for(let height = length; height * length <= n; ++height) ans++; return ans;} // Driver codelet n = 5; document.write(countRect(n)); // This code is contributed by divyesh072019 </script>
Output :
6
This article is contributed by Hemang Sarkar. 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
divyesh072019
square-rectangle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for distance between two points on earth
Closest Pair of Points | O(nlogn) Implementation
Equation of circle when three points on the circle are given
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": 25054,
"s": 25026,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 25403,
"s": 25054,
"text": "You are given N unit squares (squares with side length 1 unit), and you are asked to make rectangles using these squares. You have to count the number of rotationally unique rectangles than you can make. What does rotationally unique mean? Well, two rectangles are rotationally unique if one can’t be rotated to become equivalent to the other one. "
},
{
"code": null,
"e": 25558,
"s": 25403,
"text": "Example – The 4×2 rectangle can be rotated 90 degrees clockwise to make it the exact same as the 2×4 rectangle and so these are not rotationally unique. "
},
{
"code": null,
"e": 25570,
"s": 25558,
"text": "Examples : "
},
{
"code": null,
"e": 25719,
"s": 25570,
"text": "Input : N = 4\nOutput : 5\nWe can make following five rectangles \n1 x 1, 1 x 2, 2 x 2, 1 x 3 and 1 x 4\n\nInput : N = 5\nOutput : 6\n\nInput : 6\nOutput : 8"
},
{
"code": null,
"e": 26143,
"s": 25719,
"text": "So how do we solve this problem? Every rectangle is uniquely determined by its length and its height. A rectangle of length = l and height = h then l * h <= n is considered equivalent to a rectangle with length = h and height = l provided l is not equal to h. If we can have some sort of “ordering” in these pairs then we can avoid counting (l, h) and (h, l) as different rectangles. One way to define such an ordering is: "
},
{
"code": null,
"e": 26338,
"s": 26143,
"text": "Assume that length <= height and count for all such pairs such that length*height <= n. We have, length <= height or, length*length <= length*height or, length*length <= n or, length <= sqrt(n) "
},
{
"code": null,
"e": 26342,
"s": 26338,
"text": "C++"
},
{
"code": null,
"e": 26347,
"s": 26342,
"text": "Java"
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Python3"
},
{
"code": null,
"e": 26358,
"s": 26355,
"text": "C#"
},
{
"code": null,
"e": 26362,
"s": 26358,
"text": "PHP"
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "Javascript"
},
{
"code": "// C++ program to count rotationally equivalent// rectangles with n unit squares#include<bits/stdc++.h>using namespace std; int countRect(int n){ int ans = 0; for (int length = 1; length <= sqrt(n); ++length) for (int height = length; height*length <= n; ++height) // height >= length is maintained ans++; return ans;} // Driver codeint main() { int n = 5; printf(\"%d\", countRect(n)); return 0;}",
"e": 26810,
"s": 26373,
"text": null
},
{
"code": "// Java program to count rotationally equivalent// rectangles with n unit squaresclass GFG { static int countRect(int n) { int ans = 0; for (int length = 1; length <= Math.sqrt(n); ++length) for (int height = length; height*length <= n; ++height) // height >= length is maintained ans++; return ans; } //driver code public static void main (String[] args) { int n = 5; System.out.print(countRect(n)); }} // This code is contributed by Anant Agarwal.",
"e": 27493,
"s": 26810,
"text": null
},
{
"code": " # Python3 program to count rotationally # equivalent rectangles with n unit squaresimport math def countRect(n): ans = 0 for length in range(1, int(math.sqrt(n)) + 1): height = length while(height * length <= n): # height >= length is maintained ans += 1 height += 1 return ans # Driver coden = 5print(countRect(n)) # This code is contributed by Anant Agarwal.",
"e": 27932,
"s": 27493,
"text": null
},
{
"code": "// C# program to count rotationally // equivalent rectangles with n unit// squaresusing System; class GFG { static int countRect(int n) { int ans = 0; for (int length = 1; length <= Math.Sqrt(n); ++length) for (int height = length; height*length <= n; ++height) ans++; return ans; } //driver code public static void Main() { int n = 5; Console.Write(countRect(n)); }} //This code is contributed by Anant Agarwal.",
"e": 28526,
"s": 27932,
"text": null
},
{
"code": "<?php// PHP program to count // rotationally equivalent // rectangles with n unit squaresfunction countRect($n){ $ans = 0; for ($length = 1; $length <= sqrt($n); $length++) for ($height = $length; $height * $length <= $n; $height++) // height >= length is maintained $ans++; return $ans;} // Driver code$n = 5;echo countRect($n); // This code is contributed by @ajit?>",
"e": 28945,
"s": 28526,
"text": null
},
{
"code": "<script> // Javascript program to count rotationally // equivalent rectangles with n unit// squaresfunction countRect(n){ let ans = 0; for(let length = 1; length <= parseInt(Math.sqrt(n), 10); ++length) for(let height = length; height * length <= n; ++height) ans++; return ans;} // Driver codelet n = 5; document.write(countRect(n)); // This code is contributed by divyesh072019 </script>",
"e": 29453,
"s": 28945,
"text": null
},
{
"code": null,
"e": 29463,
"s": 29453,
"text": "Output : "
},
{
"code": null,
"e": 29466,
"s": 29463,
"text": "6 "
},
{
"code": null,
"e": 29888,
"s": 29466,
"text": "This article is contributed by Hemang Sarkar. 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": 29894,
"s": 29888,
"text": "jit_t"
},
{
"code": null,
"e": 29908,
"s": 29894,
"text": "divyesh072019"
},
{
"code": null,
"e": 29925,
"s": 29908,
"text": "square-rectangle"
},
{
"code": null,
"e": 29935,
"s": 29925,
"text": "Geometric"
},
{
"code": null,
"e": 29948,
"s": 29935,
"text": "Mathematical"
},
{
"code": null,
"e": 29961,
"s": 29948,
"text": "Mathematical"
},
{
"code": null,
"e": 29971,
"s": 29961,
"text": "Geometric"
},
{
"code": null,
"e": 30069,
"s": 29971,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30078,
"s": 30069,
"text": "Comments"
},
{
"code": null,
"e": 30091,
"s": 30078,
"text": "Old Comments"
},
{
"code": null,
"e": 30144,
"s": 30091,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 30195,
"s": 30144,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30244,
"s": 30195,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 30293,
"s": 30244,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 30354,
"s": 30293,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 30384,
"s": 30354,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30444,
"s": 30384,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30459,
"s": 30444,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30502,
"s": 30459,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
10 Tips for Choosing the Optimal Number of Clusters | by Matt.0 | Towards Data Science
|
Clustering is one of the most common unsupervised machine learning problems. Similarity between observations is defined using some inter-observation distance measures or correlation-based distance measures.
There are 5 classes of clustering methods:
+ Hierarchical Clustering+ Partitioning Methods (k-means, PAM, CLARA)+ Density-Based Clustering+ Model-based Clustering+ Fuzzy Clustering
My desire to write this post came mainly from reading about the clustree package, the dendextend documentation, and the Practical Guide to Cluster Analysis in R book written by Alboukadel Kassambara author of the factoextra package.
I will be using a lesser known data set from the cluster package: all.mammals.milk.1956, one which I haven’t looked at before.
This small dataset contains a list of 25 mammals and the constituents of their milk (water, protein, fat, lactose, ash percentages) from John Hartigan, Clustering Algorithms, Wiley, 1975.
First let’s load the required packages.
library(tidyverse)library(magrittr)library(cluster)library(cluster.datasets)library(cowplot)library(NbClust)library(clValid)library(ggfortify)library(clustree)library(dendextend)library(factoextra)library(FactoMineR)library(corrplot)library(GGally)library(ggiraphExtra)library(knitr)library(kableExtra)
Now load the data.
data("all.mammals.milk.1956")raw_mammals <- all.mammals.milk.1956# subset datasetmammals <- raw_mammals %>% select(-name) # set rownamesmammals <- as_tibble(mammals)
Let’s explore and visualize the data.
# Glimpse the data setglimpse(mammals)Observations: 25Variables: 5$ water <dbl> 90.1, 88.5, 88.4, 90.3, 90.4, 87.7, 86.9, 82.1, 81.9, 81.6, 81.6, 86.5, 90.0,...$ protein <dbl> 2.6, 1.4, 2.2, 1.7, 0.6, 3.5, 4.8, 5.9, 7.4, 10.1, 6.6, 3.9, 2.0, 7.1, 3.0, 5...$ fat <dbl> 1.0, 3.5, 2.7, 1.4, 4.5, 3.4, 1.7, 7.9, 7.2, 6.3, 5.9, 3.2, 1.8, 5.1, 4.8, 6....$ lactose <dbl> 6.9, 6.0, 6.4, 6.2, 4.4, 4.8, 5.7, 4.7, 2.7, 4.4, 4.9, 5.6, 5.5, 3.7, 5.3, 4....$ ash <dbl> 0.35, 0.24, 0.18, 0.40, 0.10, 0.71, 0.90, 0.78, 0.85, 0.75, 0.93, 0.80, 0.47,...
All the variables are expressed as numeric. What about the statistical distribution?
# Summary of data setsummary(mammals) %>% kable() %>% kable_styling()
# Historgram for each attributemammals %>% gather(Attributes, value, 1:5) %>% ggplot(aes(x=value)) + geom_histogram(fill = "lightblue2", color = "black") + facet_wrap(~Attributes, scales = "free_x") + labs(x = "Value", y = "Frequency")
What’s the relationship between the different attributes? Use `corrplot()` to create correlation matrix.
corrplot(cor(mammals), type = "upper", method = "ellipse", tl.cex = 0.9)
When you have variables which are measured in different scales it is useful to scale the data.
mammals_scaled <- scale(mammals)rownames(mammals_scaled) <- raw_mammals$name
Dimensionality reduction can help with data visualization (e.g. PCA method).
res.pca <- PCA(mammals_scaled, graph = FALSE)# Visualize eigenvalues/variancesfviz_screeplot(res.pca, addlabels = TRUE, ylim = c(0, 50))
These are the 5 PCs that capture 80% of the variance. The scree plot shows that PC1 captured ~ 75% of the variance.
# Extract the results for variablesvar <- get_pca_var(res.pca)# Contributions of variables to PC1fviz_contrib(res.pca, choice = "var", axes = 1, top = 10)# Contributions of variables to PC2fviz_contrib(res.pca, choice = "var", axes = 2, top = 10)# Control variable colors using their contributions to the principle axisfviz_pca_var(res.pca, col.var="contrib", gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"), repel = TRUE # Avoid text overlapping ) + theme_minimal() + ggtitle("Variables - PCA")
From these visualizations it’s apparrent that water and lactose tend to increase together and that protein, ash and fat increase together; the two groups being inversely related.
Partitioning clustering methods, like k-means and Partitioning Around Medoids (PAM), require that you specify the number of clusters to be generated.
k-means clusters is probably one of the most well known partitioning methods. The idea behind k-means clustering consists of defining clusters the total within-cluster variation , which measures the compactness of the clusters is minimized.
We can compute k-means in R with the kmeans() function:
km2 <- kmeans(mammals_scaled, centers = 2, nstart = 30)
The above example would group the data into two clusters, centers = 2, and attempt multiple initial configurations, reporting on the best one. For example, as this algorithm is sensitive to the initial positions of the cluster centroids adding nstart = 30 will generate 30 initial configurations and then average all the centroid results.
Because the number of clusters (k) needs to be set before we start it can be advantageous to examine several different values of k.
kmean_calc <- function(df, ...){ kmeans(df, scaled = ..., nstart = 30)}km2 <- kmean_calc(mammals_scaled, 2)km3 <- kmean_calc(mammals_scaled, 3)km4 <- kmeans(mammals_scaled, 4)km5 <- kmeans(mammals_scaled, 5)km6 <- kmeans(mammals_scaled, 6)km7 <- kmeans(mammals_scaled, 7)km8 <- kmeans(mammals_scaled, 8)km9 <- kmeans(mammals_scaled, 9)km10 <- kmeans(mammals_scaled, 10)km11 <- kmeans(mammals_scaled, 11)p1 <- fviz_cluster(km2, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 2") p2 <- fviz_cluster(km3, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 3")p3 <- fviz_cluster(km4, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 4")p4 <- fviz_cluster(km5, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 5")p5 <- fviz_cluster(km6, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 6")p6 <- fviz_cluster(km7, data = mammals_scaled, frame.type = "convex") + theme_minimal() + ggtitle("k = 7")plot_grid(p1, p2, p3, p4, p5, p6, labels = c("k2", "k3", "k4", "k5", "k6", "k7"))
Although this visual assessment tells us where delineations occur between clusters, it does not tell us what the optimal number of clusters is.
A variety of measures have been proposed in the literature for evaluating clustering results. The term clustering validation is used to design the procedure of evaluating the results of a clustering algorithm. There are more than thirty indices and methods for identifying the optimal number of clusters so I’ll just focus on a few here including the very neat clustree package.
Probably the most well known method, the elbow method, in which the sum of squares at each number of clusters is calculated and graphed, and the user looks for a change of slope from steep to shallow (an elbow) to determine the optimal number of clusters. This method is inexact, but still potentially helpful.
set.seed(31)# function to compute total within-cluster sum of squaresfviz_nbclust(mammals_scaled, kmeans, method = "wss", k.max = 24) + theme_minimal() + ggtitle("the Elbow Method")
The Elbow Curve method is helpful because it shows how increasing the number of the clusters contribute separating the clusters in a meaningful way, not in a marginal way. The bend indicates that additional clusters beyond the third have little value (See [here] for a more mathematically rigorous interpretation and implementation of this method). The Elbow method is fairly clear, if not a naïve solution based on intra-cluster variance. The gap statistic is more sophisticated method to deal with data that has a distribution with no obvious clustering (can find the correct number of k for globular, Gaussian-distributed, mildly disjoint data distributions).
The gap statistic compares the total within intra-cluster variation for different values of k with their expected values under null reference distribution of the data. The estimate of the optimal clusters will be value that maximize the gap statistic (i.e., that yields the largest gap statistic). This means that the clustering structure is far away from the random uniform distribution of points.
gap_stat <- clusGap(mammals_scaled, FUN = kmeans, nstart = 30, K.max = 24, B = 50)fviz_gap_stat(gap_stat) + theme_minimal() + ggtitle("fviz_gap_stat: Gap Statistic")
The gap stats plot shows the statistics by number of clusters (k) with standard errors drawn with vertical segments and the optimal value of k marked with a vertical dashed blue line. According to this observation k = 2 is the optimal number of clusters in the data.
Another visualization that can help determine the optimal number of clusters is called the a silhouette method. Average silhouette method computes the average silhouette of observations for different values of k. The optimal number of clusters k is the one that maximize the average silhouette over a range of possible values for k.
fviz_nbclust(mammals_scaled, kmeans, method = "silhouette", k.max = 24) + theme_minimal() + ggtitle("The Silhouette Plot")
This also suggests an optimal of 2 clusters.
Another clustering validation method would be to choose the optimal number of cluster by minimizing the within-cluster sum of squares (a measure of how tight each cluster is) and maximizing the between-cluster sum of squares (a measure of how seperated each cluster is from the others).
ssc <- data.frame( kmeans = c(2,3,4,5,6,7,8), within_ss = c(mean(km2$withinss), mean(km3$withinss), mean(km4$withinss), mean(km5$withinss), mean(km6$withinss), mean(km7$withinss), mean(km8$withinss)), between_ss = c(km2$betweenss, km3$betweenss, km4$betweenss, km5$betweenss, km6$betweenss, km7$betweenss, km8$betweenss))ssc %<>% gather(., key = "measurement", value = value, -kmeans)#ssc$value <- log10(ssc$value)ssc %>% ggplot(., aes(x=kmeans, y=log10(value), fill = measurement)) + geom_bar(stat = "identity", position = "dodge") + ggtitle("Cluster Model Comparison") + xlab("Number of Clusters") + ylab("Log10 Total Sum of Squares") + scale_x_discrete(name = "Number of Clusters", limits = c("0", "2", "3", "4", "5", "6", "7", "8"))
From this measurement it appears 7 clusters would be the appropriate choice.
The NbClust package provides 30 indices for determining the relevant number of clusters and proposes to users the best clustering scheme from the different results obtained by varying all combinations of number of clusters, distance measures, and clustering methods.
res.nbclust <- NbClust(mammals_scaled, distance = "euclidean", min.nc = 2, max.nc = 9, method = "complete", index ="all")factoextra::fviz_nbclust(res.nbclust) + theme_minimal() + ggtitle("NbClust's optimal number of clusters")
This suggest the optimal number of clusters is 3.
The statistical method above produce a single score that only considers a single set of clusters at a time. The clustree R package takes an alternative approach by considering how samples change groupings as the number of clusters increases. This is useful for showing which clusters are distinct and which are unstable. It doesn’t explicitly tell you which choice of optimal clusters is but it is useful for exploring possible choices.
Let’s take a look at 1 to 11 clusters.
tmp <- NULLfor (k in 1:11){ tmp[k] <- kmeans(mammals_scaled, k, nstart = 30)}df <- data.frame(tmp)# add a prefix to the column namescolnames(df) <- seq(1:11)colnames(df) <- paste0("k",colnames(df))# get individual PCAdf.pca <- prcomp(df, center = TRUE, scale. = FALSE)ind.coord <- df.pca$xind.coord <- ind.coord[,1:2]df <- bind_cols(as.data.frame(df), as.data.frame(ind.coord))clustree(df, prefix = "k")
In this figure the size of each node corresponds to the number of samples in each cluster, and the arrows are coloured according to the number of samples each cluster receives. A separate set of arrows, the transparent ones, called the incoming node proportion, are also coloured and shows how samples from one group end up in another group — an indicator of cluster instability.
In this graph we see that as we move from k=2 to k=3 a number of species from the lookers-left cluster are reasigned to the third cluster on the right. As we move from k=8 to k=9 we see one node with multiple incoming edges an indicator that we over-clustered the data.
It can also be useful to overlay this dimension on other dimensions in the data, particularly those that come from dimensionality reduction techniques. We can do this using the clustree_overlay() function:
df_subset <- df %>% select(1:8,12:13)clustree_overlay(df_subset, prefix = "k", x_value = "PC1", y_value = "PC2")
I prefer to see it from the side, showing one of the x or y dimensions against the resolution dimension.
overlay_list <- clustree_overlay(df_subset, prefix = "k", x_value = "PC1", y_value = "PC2", plot_sides = TRUE)overlay_list$x_sideoverlay_list$y_side
This shows that we can an indication of the correct clustering resolution by examining the edges and we can overly information to assess the quality of the clustering.
What about choice of appropriate clustering algorithm? The cValid package can be used to simultaneously compare multiple clustering algorithms, to identify the best clustering approach and the optimal number of clusters. We will compare k-means, hierarchical and PAM clustering.
intern <- clValid(mammals_scaled, nClust = 2:24, clMethods = c("hierarchical","kmeans","pam"), validation = "internal")# Summarysummary(intern) %>% kable() %>% kable_styling()Clustering Methods: hierarchical kmeans pam Cluster sizes: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Validation Measures: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 hierarchical Connectivity 4.1829 10.5746 13.2579 20.1579 22.8508 25.8258 32.6270 35.3032 38.2905 39.2405 41.2405 45.7742 47.2742 50.6075 52.6075 55.8575 58.7242 60.7242 63.2242 65.2242 67.2242 69.2242 71.2242 Dunn 0.3595 0.3086 0.3282 0.2978 0.3430 0.3430 0.4390 0.4390 0.5804 0.5938 0.5938 0.8497 0.8497 0.5848 0.5848 0.4926 0.9138 0.9138 0.8892 0.9049 0.9335 1.0558 2.1253 Silhouette 0.5098 0.5091 0.4592 0.4077 0.4077 0.3664 0.3484 0.4060 0.3801 0.3749 0.3322 0.3646 0.3418 0.2650 0.2317 0.2166 0.2469 0.2213 0.1659 0.1207 0.1050 0.0832 0.0691kmeans Connectivity 7.2385 10.5746 15.8159 20.1579 22.8508 25.8258 33.5198 35.3032 38.2905 39.2405 41.2405 45.7742 47.2742 51.8909 53.8909 57.1409 58.7242 60.7242 63.2242 65.2242 67.2242 69.2242 71.2242 Dunn 0.2070 0.3086 0.2884 0.2978 0.3430 0.3430 0.3861 0.4390 0.5804 0.5938 0.5938 0.8497 0.8497 0.5866 0.5866 0.5725 0.9138 0.9138 0.8892 0.9049 0.9335 1.0558 2.1253 Silhouette 0.5122 0.5091 0.4260 0.4077 0.4077 0.3664 0.3676 0.4060 0.3801 0.3749 0.3322 0.3646 0.3418 0.2811 0.2478 0.2402 0.2469 0.2213 0.1659 0.1207 0.1050 0.0832 0.0691pam Connectivity 7.2385 14.1385 17.4746 24.0024 26.6857 32.0413 33.8913 36.0579 38.6607 40.6607 42.7869 45.7742 47.2742 51.7242 53.7242 56.9742 58.7242 60.7242 62.7242 64.7242 66.7242 69.2242 71.2242 Dunn 0.2070 0.1462 0.2180 0.2180 0.2978 0.2980 0.4390 0.4390 0.4390 0.4390 0.4390 0.8497 0.8497 0.5314 0.5314 0.4782 0.9138 0.9138 0.8333 0.8189 0.7937 1.0558 2.1253 Silhouette 0.5122 0.3716 0.4250 0.3581 0.3587 0.3318 0.3606 0.3592 0.3664 0.3237 0.3665 0.3646 0.3418 0.2830 0.2497 0.2389 0.2469 0.2213 0.1758 0.1598 0.1380 0.0832 0.0691Optimal Scores: Score Method ClustersConnectivity 4.1829 hierarchical 2 Dunn 2.1253 hierarchical 24 Silhouette 0.5122 kmeans 2
Connectivity and Silhouette are both measurements of connectedness while the Dunn Index is the ratio of the smallest distance between observations not in the same cluster to the largest intra-cluster distance.
As mentioned earlier it’s difficult to assess the quality of results from clustering. We don’t have true labels so so it’s unclear how one would measure “how good it actually works” in term of interal validation. However, clustering is an excellent EDA starting point for exploring the differences between clusters in greater detail. Think of clustering like manufacturing shirt sizes. We could choose to only make three sizes: small, medium and large. we’re sure to cut down cost but not everyone is going to have a great fit. Think about pant sizes now (or shirt brands with many sizes (XS, XL, XXL, etc.)) where you have many more categories (or clusters). For some fields the choice of optimal cluster may depend on some external knowledge like cost of producing k clusters to satisfy customers with the best possible fit. In other domains like biology where you are trying to determine the exact number of cells a more in-depth approach would be required. For example, many of the above heuristics contradicted each other for what the optimal number of clusters was. Keep in mind these were all evaluating the k-means algorithm at different numbers of k. This could potentially mean that the k-means algorithm fails and no k is good. The k-means algorithm is not a very robust algorithm that is sensitive to outliers and this data set is quit small. The best thing to do would be to explore the above methods on the output of other algorithms (for example hierarchical clustering which clValid suggested), collect more data, or spend some time labelling samples for other ML methods if possible.
Ultimately, we would like to answer questions like “what is it that makes this cluster unique from others?” and “what are the clusters that are similar to one another”. Let’s select five clusters and interrogate the features of these clusters.
# Compute dissimilarity matrix with euclidean distancesd <- dist(mammals_scaled, method = "euclidean")# Hierarchical clustering using Ward's methodres.hc <- hclust(d, method = "ward.D2" )# Cut tree into 5 groupsgrp <- cutree(res.hc, k = 5)# Visualizeplot(res.hc, cex = 0.6) # plot treerect.hclust(res.hc, k = 5, border = 2:5) # add rectangle
# Execution of k-means with k=5final <- kmeans(mammals_scaled, 5, nstart = 30)fviz_cluster(final, data = mammals_scaled) + theme_minimal() + ggtitle("k = 5")
Let’s extract the clusters and add them back to our initial data to do some descriptive statistics at the cluster level:
as.data.frame(mammals_scaled) %>% mutate(Cluster = final$cluster) %>% group_by(Cluster) %>% summarise_all("mean") %>% kable() %>% kable_styling()
We see that cluster 2, composed solely of the Rabbit has a high ash content. Group 3 composed of the seal and dolphin are high in fat, which makes sense given the harsh demands of such a cold climate whil group 4 has a large lactose content.
mammals_df <- as.data.frame(mammals_scaled) %>% rownames_to_column()cluster_pos <- as.data.frame(final$cluster) %>% rownames_to_column()colnames(cluster_pos) <- c("rowname", "cluster")mammals_final <- inner_join(cluster_pos, mammals_df)ggRadar(mammals_final[-1], aes(group = cluster), rescale = FALSE, legend.position = "none", size = 1, interactive = FALSE, use.label = TRUE) + facet_wrap(~cluster) + scale_y_discrete(breaks = NULL) + # don't show tickstheme(axis.text.x = element_text(size = 10)) + scale_fill_manual(values = rep("#1c6193", nrow(mammals_final))) +scale_color_manual(values = rep("#1c6193", nrow(mammals_final))) +ggtitle("Mammals Milk Attributes")
mammals_df <- as.data.frame(mammals_scaled)mammals_df$cluster <- final$clustermammals_df$cluster <- as.character(mammals_df$cluster)ggpairs(mammals_df, 1:5, mapping = ggplot2::aes(color = cluster, alpha = 0.5), diag = list(continuous = wrap("densityDiag")), lower=list(continuous = wrap("points", alpha=0.9)))
# plot specific graphs from previous matrix with scatterplotg <- ggplot(mammals_df, aes(x = water, y = lactose, color = cluster)) + geom_point() + theme(legend.position = "bottom")ggExtra::ggMarginal(g, type = "histogram", bins = 20, color = "grey", fill = "blue")b <- ggplot(mammals_df, aes(x = protein, y = fat, color = cluster)) + geom_point() + theme(legend.position = "bottom")ggExtra::ggMarginal(b, type = "histogram", bins = 20, color = "grey", fill = "blue")
ggplot(mammals_df, aes(x = cluster, y = protein)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = fat)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = lactose)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = ash)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = water)) + geom_boxplot(aes(fill = cluster))
# Parallel coordiante plots allow us to put each feature on seperate column and lines connecting each columnggparcoord(data = mammals_df, columns = 1:5, groupColumn = 6, alphaLines = 0.4, title = "Parallel Coordinate Plot for the Mammals Milk Data", scale = "globalminmax", showPoints = TRUE) + theme(legend.position = "bottom")
If you find this article useful feel free to share it with others or recommend this article! 😃
As always, if you have any questions or comments feel free to leave your feedback below or you can always reach me on LinkedIn. Till then, see you in the next post! 😄
|
[
{
"code": null,
"e": 379,
"s": 172,
"text": "Clustering is one of the most common unsupervised machine learning problems. Similarity between observations is defined using some inter-observation distance measures or correlation-based distance measures."
},
{
"code": null,
"e": 422,
"s": 379,
"text": "There are 5 classes of clustering methods:"
},
{
"code": null,
"e": 560,
"s": 422,
"text": "+ Hierarchical Clustering+ Partitioning Methods (k-means, PAM, CLARA)+ Density-Based Clustering+ Model-based Clustering+ Fuzzy Clustering"
},
{
"code": null,
"e": 793,
"s": 560,
"text": "My desire to write this post came mainly from reading about the clustree package, the dendextend documentation, and the Practical Guide to Cluster Analysis in R book written by Alboukadel Kassambara author of the factoextra package."
},
{
"code": null,
"e": 920,
"s": 793,
"text": "I will be using a lesser known data set from the cluster package: all.mammals.milk.1956, one which I haven’t looked at before."
},
{
"code": null,
"e": 1108,
"s": 920,
"text": "This small dataset contains a list of 25 mammals and the constituents of their milk (water, protein, fat, lactose, ash percentages) from John Hartigan, Clustering Algorithms, Wiley, 1975."
},
{
"code": null,
"e": 1148,
"s": 1108,
"text": "First let’s load the required packages."
},
{
"code": null,
"e": 1451,
"s": 1148,
"text": "library(tidyverse)library(magrittr)library(cluster)library(cluster.datasets)library(cowplot)library(NbClust)library(clValid)library(ggfortify)library(clustree)library(dendextend)library(factoextra)library(FactoMineR)library(corrplot)library(GGally)library(ggiraphExtra)library(knitr)library(kableExtra)"
},
{
"code": null,
"e": 1470,
"s": 1451,
"text": "Now load the data."
},
{
"code": null,
"e": 1636,
"s": 1470,
"text": "data(\"all.mammals.milk.1956\")raw_mammals <- all.mammals.milk.1956# subset datasetmammals <- raw_mammals %>% select(-name) # set rownamesmammals <- as_tibble(mammals)"
},
{
"code": null,
"e": 1674,
"s": 1636,
"text": "Let’s explore and visualize the data."
},
{
"code": null,
"e": 2221,
"s": 1674,
"text": "# Glimpse the data setglimpse(mammals)Observations: 25Variables: 5$ water <dbl> 90.1, 88.5, 88.4, 90.3, 90.4, 87.7, 86.9, 82.1, 81.9, 81.6, 81.6, 86.5, 90.0,...$ protein <dbl> 2.6, 1.4, 2.2, 1.7, 0.6, 3.5, 4.8, 5.9, 7.4, 10.1, 6.6, 3.9, 2.0, 7.1, 3.0, 5...$ fat <dbl> 1.0, 3.5, 2.7, 1.4, 4.5, 3.4, 1.7, 7.9, 7.2, 6.3, 5.9, 3.2, 1.8, 5.1, 4.8, 6....$ lactose <dbl> 6.9, 6.0, 6.4, 6.2, 4.4, 4.8, 5.7, 4.7, 2.7, 4.4, 4.9, 5.6, 5.5, 3.7, 5.3, 4....$ ash <dbl> 0.35, 0.24, 0.18, 0.40, 0.10, 0.71, 0.90, 0.78, 0.85, 0.75, 0.93, 0.80, 0.47,..."
},
{
"code": null,
"e": 2306,
"s": 2221,
"text": "All the variables are expressed as numeric. What about the statistical distribution?"
},
{
"code": null,
"e": 2376,
"s": 2306,
"text": "# Summary of data setsummary(mammals) %>% kable() %>% kable_styling()"
},
{
"code": null,
"e": 2620,
"s": 2376,
"text": "# Historgram for each attributemammals %>% gather(Attributes, value, 1:5) %>% ggplot(aes(x=value)) + geom_histogram(fill = \"lightblue2\", color = \"black\") + facet_wrap(~Attributes, scales = \"free_x\") + labs(x = \"Value\", y = \"Frequency\")"
},
{
"code": null,
"e": 2725,
"s": 2620,
"text": "What’s the relationship between the different attributes? Use `corrplot()` to create correlation matrix."
},
{
"code": null,
"e": 2798,
"s": 2725,
"text": "corrplot(cor(mammals), type = \"upper\", method = \"ellipse\", tl.cex = 0.9)"
},
{
"code": null,
"e": 2893,
"s": 2798,
"text": "When you have variables which are measured in different scales it is useful to scale the data."
},
{
"code": null,
"e": 2970,
"s": 2893,
"text": "mammals_scaled <- scale(mammals)rownames(mammals_scaled) <- raw_mammals$name"
},
{
"code": null,
"e": 3047,
"s": 2970,
"text": "Dimensionality reduction can help with data visualization (e.g. PCA method)."
},
{
"code": null,
"e": 3185,
"s": 3047,
"text": "res.pca <- PCA(mammals_scaled, graph = FALSE)# Visualize eigenvalues/variancesfviz_screeplot(res.pca, addlabels = TRUE, ylim = c(0, 50))"
},
{
"code": null,
"e": 3301,
"s": 3185,
"text": "These are the 5 PCs that capture 80% of the variance. The scree plot shows that PC1 captured ~ 75% of the variance."
},
{
"code": null,
"e": 3836,
"s": 3301,
"text": "# Extract the results for variablesvar <- get_pca_var(res.pca)# Contributions of variables to PC1fviz_contrib(res.pca, choice = \"var\", axes = 1, top = 10)# Contributions of variables to PC2fviz_contrib(res.pca, choice = \"var\", axes = 2, top = 10)# Control variable colors using their contributions to the principle axisfviz_pca_var(res.pca, col.var=\"contrib\", gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"), repel = TRUE # Avoid text overlapping ) + theme_minimal() + ggtitle(\"Variables - PCA\")"
},
{
"code": null,
"e": 4015,
"s": 3836,
"text": "From these visualizations it’s apparrent that water and lactose tend to increase together and that protein, ash and fat increase together; the two groups being inversely related."
},
{
"code": null,
"e": 4165,
"s": 4015,
"text": "Partitioning clustering methods, like k-means and Partitioning Around Medoids (PAM), require that you specify the number of clusters to be generated."
},
{
"code": null,
"e": 4406,
"s": 4165,
"text": "k-means clusters is probably one of the most well known partitioning methods. The idea behind k-means clustering consists of defining clusters the total within-cluster variation , which measures the compactness of the clusters is minimized."
},
{
"code": null,
"e": 4462,
"s": 4406,
"text": "We can compute k-means in R with the kmeans() function:"
},
{
"code": null,
"e": 4518,
"s": 4462,
"text": "km2 <- kmeans(mammals_scaled, centers = 2, nstart = 30)"
},
{
"code": null,
"e": 4857,
"s": 4518,
"text": "The above example would group the data into two clusters, centers = 2, and attempt multiple initial configurations, reporting on the best one. For example, as this algorithm is sensitive to the initial positions of the cluster centroids adding nstart = 30 will generate 30 initial configurations and then average all the centroid results."
},
{
"code": null,
"e": 4989,
"s": 4857,
"text": "Because the number of clusters (k) needs to be set before we start it can be advantageous to examine several different values of k."
},
{
"code": null,
"e": 6112,
"s": 4989,
"text": "kmean_calc <- function(df, ...){ kmeans(df, scaled = ..., nstart = 30)}km2 <- kmean_calc(mammals_scaled, 2)km3 <- kmean_calc(mammals_scaled, 3)km4 <- kmeans(mammals_scaled, 4)km5 <- kmeans(mammals_scaled, 5)km6 <- kmeans(mammals_scaled, 6)km7 <- kmeans(mammals_scaled, 7)km8 <- kmeans(mammals_scaled, 8)km9 <- kmeans(mammals_scaled, 9)km10 <- kmeans(mammals_scaled, 10)km11 <- kmeans(mammals_scaled, 11)p1 <- fviz_cluster(km2, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 2\") p2 <- fviz_cluster(km3, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 3\")p3 <- fviz_cluster(km4, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 4\")p4 <- fviz_cluster(km5, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 5\")p5 <- fviz_cluster(km6, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 6\")p6 <- fviz_cluster(km7, data = mammals_scaled, frame.type = \"convex\") + theme_minimal() + ggtitle(\"k = 7\")plot_grid(p1, p2, p3, p4, p5, p6, labels = c(\"k2\", \"k3\", \"k4\", \"k5\", \"k6\", \"k7\"))"
},
{
"code": null,
"e": 6256,
"s": 6112,
"text": "Although this visual assessment tells us where delineations occur between clusters, it does not tell us what the optimal number of clusters is."
},
{
"code": null,
"e": 6635,
"s": 6256,
"text": "A variety of measures have been proposed in the literature for evaluating clustering results. The term clustering validation is used to design the procedure of evaluating the results of a clustering algorithm. There are more than thirty indices and methods for identifying the optimal number of clusters so I’ll just focus on a few here including the very neat clustree package."
},
{
"code": null,
"e": 6946,
"s": 6635,
"text": "Probably the most well known method, the elbow method, in which the sum of squares at each number of clusters is calculated and graphed, and the user looks for a change of slope from steep to shallow (an elbow) to determine the optimal number of clusters. This method is inexact, but still potentially helpful."
},
{
"code": null,
"e": 7128,
"s": 6946,
"text": "set.seed(31)# function to compute total within-cluster sum of squaresfviz_nbclust(mammals_scaled, kmeans, method = \"wss\", k.max = 24) + theme_minimal() + ggtitle(\"the Elbow Method\")"
},
{
"code": null,
"e": 7792,
"s": 7128,
"text": "The Elbow Curve method is helpful because it shows how increasing the number of the clusters contribute separating the clusters in a meaningful way, not in a marginal way. The bend indicates that additional clusters beyond the third have little value (See [here] for a more mathematically rigorous interpretation and implementation of this method). The Elbow method is fairly clear, if not a naïve solution based on intra-cluster variance. The gap statistic is more sophisticated method to deal with data that has a distribution with no obvious clustering (can find the correct number of k for globular, Gaussian-distributed, mildly disjoint data distributions)."
},
{
"code": null,
"e": 8191,
"s": 7792,
"text": "The gap statistic compares the total within intra-cluster variation for different values of k with their expected values under null reference distribution of the data. The estimate of the optimal clusters will be value that maximize the gap statistic (i.e., that yields the largest gap statistic). This means that the clustering structure is far away from the random uniform distribution of points."
},
{
"code": null,
"e": 8357,
"s": 8191,
"text": "gap_stat <- clusGap(mammals_scaled, FUN = kmeans, nstart = 30, K.max = 24, B = 50)fviz_gap_stat(gap_stat) + theme_minimal() + ggtitle(\"fviz_gap_stat: Gap Statistic\")"
},
{
"code": null,
"e": 8624,
"s": 8357,
"text": "The gap stats plot shows the statistics by number of clusters (k) with standard errors drawn with vertical segments and the optimal value of k marked with a vertical dashed blue line. According to this observation k = 2 is the optimal number of clusters in the data."
},
{
"code": null,
"e": 8957,
"s": 8624,
"text": "Another visualization that can help determine the optimal number of clusters is called the a silhouette method. Average silhouette method computes the average silhouette of observations for different values of k. The optimal number of clusters k is the one that maximize the average silhouette over a range of possible values for k."
},
{
"code": null,
"e": 9080,
"s": 8957,
"text": "fviz_nbclust(mammals_scaled, kmeans, method = \"silhouette\", k.max = 24) + theme_minimal() + ggtitle(\"The Silhouette Plot\")"
},
{
"code": null,
"e": 9125,
"s": 9080,
"text": "This also suggests an optimal of 2 clusters."
},
{
"code": null,
"e": 9412,
"s": 9125,
"text": "Another clustering validation method would be to choose the optimal number of cluster by minimizing the within-cluster sum of squares (a measure of how tight each cluster is) and maximizing the between-cluster sum of squares (a measure of how seperated each cluster is from the others)."
},
{
"code": null,
"e": 10152,
"s": 9412,
"text": "ssc <- data.frame( kmeans = c(2,3,4,5,6,7,8), within_ss = c(mean(km2$withinss), mean(km3$withinss), mean(km4$withinss), mean(km5$withinss), mean(km6$withinss), mean(km7$withinss), mean(km8$withinss)), between_ss = c(km2$betweenss, km3$betweenss, km4$betweenss, km5$betweenss, km6$betweenss, km7$betweenss, km8$betweenss))ssc %<>% gather(., key = \"measurement\", value = value, -kmeans)#ssc$value <- log10(ssc$value)ssc %>% ggplot(., aes(x=kmeans, y=log10(value), fill = measurement)) + geom_bar(stat = \"identity\", position = \"dodge\") + ggtitle(\"Cluster Model Comparison\") + xlab(\"Number of Clusters\") + ylab(\"Log10 Total Sum of Squares\") + scale_x_discrete(name = \"Number of Clusters\", limits = c(\"0\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\"))"
},
{
"code": null,
"e": 10229,
"s": 10152,
"text": "From this measurement it appears 7 clusters would be the appropriate choice."
},
{
"code": null,
"e": 10496,
"s": 10229,
"text": "The NbClust package provides 30 indices for determining the relevant number of clusters and proposes to users the best clustering scheme from the different results obtained by varying all combinations of number of clusters, distance measures, and clustering methods."
},
{
"code": null,
"e": 10758,
"s": 10496,
"text": "res.nbclust <- NbClust(mammals_scaled, distance = \"euclidean\", min.nc = 2, max.nc = 9, method = \"complete\", index =\"all\")factoextra::fviz_nbclust(res.nbclust) + theme_minimal() + ggtitle(\"NbClust's optimal number of clusters\")"
},
{
"code": null,
"e": 10808,
"s": 10758,
"text": "This suggest the optimal number of clusters is 3."
},
{
"code": null,
"e": 11245,
"s": 10808,
"text": "The statistical method above produce a single score that only considers a single set of clusters at a time. The clustree R package takes an alternative approach by considering how samples change groupings as the number of clusters increases. This is useful for showing which clusters are distinct and which are unstable. It doesn’t explicitly tell you which choice of optimal clusters is but it is useful for exploring possible choices."
},
{
"code": null,
"e": 11284,
"s": 11245,
"text": "Let’s take a look at 1 to 11 clusters."
},
{
"code": null,
"e": 11689,
"s": 11284,
"text": "tmp <- NULLfor (k in 1:11){ tmp[k] <- kmeans(mammals_scaled, k, nstart = 30)}df <- data.frame(tmp)# add a prefix to the column namescolnames(df) <- seq(1:11)colnames(df) <- paste0(\"k\",colnames(df))# get individual PCAdf.pca <- prcomp(df, center = TRUE, scale. = FALSE)ind.coord <- df.pca$xind.coord <- ind.coord[,1:2]df <- bind_cols(as.data.frame(df), as.data.frame(ind.coord))clustree(df, prefix = \"k\")"
},
{
"code": null,
"e": 12069,
"s": 11689,
"text": "In this figure the size of each node corresponds to the number of samples in each cluster, and the arrows are coloured according to the number of samples each cluster receives. A separate set of arrows, the transparent ones, called the incoming node proportion, are also coloured and shows how samples from one group end up in another group — an indicator of cluster instability."
},
{
"code": null,
"e": 12339,
"s": 12069,
"text": "In this graph we see that as we move from k=2 to k=3 a number of species from the lookers-left cluster are reasigned to the third cluster on the right. As we move from k=8 to k=9 we see one node with multiple incoming edges an indicator that we over-clustered the data."
},
{
"code": null,
"e": 12545,
"s": 12339,
"text": "It can also be useful to overlay this dimension on other dimensions in the data, particularly those that come from dimensionality reduction techniques. We can do this using the clustree_overlay() function:"
},
{
"code": null,
"e": 12658,
"s": 12545,
"text": "df_subset <- df %>% select(1:8,12:13)clustree_overlay(df_subset, prefix = \"k\", x_value = \"PC1\", y_value = \"PC2\")"
},
{
"code": null,
"e": 12763,
"s": 12658,
"text": "I prefer to see it from the side, showing one of the x or y dimensions against the resolution dimension."
},
{
"code": null,
"e": 12944,
"s": 12763,
"text": "overlay_list <- clustree_overlay(df_subset, prefix = \"k\", x_value = \"PC1\", y_value = \"PC2\", plot_sides = TRUE)overlay_list$x_sideoverlay_list$y_side"
},
{
"code": null,
"e": 13112,
"s": 12944,
"text": "This shows that we can an indication of the correct clustering resolution by examining the edges and we can overly information to assess the quality of the clustering."
},
{
"code": null,
"e": 13391,
"s": 13112,
"text": "What about choice of appropriate clustering algorithm? The cValid package can be used to simultaneously compare multiple clustering algorithms, to identify the best clustering approach and the optimal number of clusters. We will compare k-means, hierarchical and PAM clustering."
},
{
"code": null,
"e": 16203,
"s": 13391,
"text": "intern <- clValid(mammals_scaled, nClust = 2:24, clMethods = c(\"hierarchical\",\"kmeans\",\"pam\"), validation = \"internal\")# Summarysummary(intern) %>% kable() %>% kable_styling()Clustering Methods: hierarchical kmeans pam Cluster sizes: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Validation Measures: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 hierarchical Connectivity 4.1829 10.5746 13.2579 20.1579 22.8508 25.8258 32.6270 35.3032 38.2905 39.2405 41.2405 45.7742 47.2742 50.6075 52.6075 55.8575 58.7242 60.7242 63.2242 65.2242 67.2242 69.2242 71.2242 Dunn 0.3595 0.3086 0.3282 0.2978 0.3430 0.3430 0.4390 0.4390 0.5804 0.5938 0.5938 0.8497 0.8497 0.5848 0.5848 0.4926 0.9138 0.9138 0.8892 0.9049 0.9335 1.0558 2.1253 Silhouette 0.5098 0.5091 0.4592 0.4077 0.4077 0.3664 0.3484 0.4060 0.3801 0.3749 0.3322 0.3646 0.3418 0.2650 0.2317 0.2166 0.2469 0.2213 0.1659 0.1207 0.1050 0.0832 0.0691kmeans Connectivity 7.2385 10.5746 15.8159 20.1579 22.8508 25.8258 33.5198 35.3032 38.2905 39.2405 41.2405 45.7742 47.2742 51.8909 53.8909 57.1409 58.7242 60.7242 63.2242 65.2242 67.2242 69.2242 71.2242 Dunn 0.2070 0.3086 0.2884 0.2978 0.3430 0.3430 0.3861 0.4390 0.5804 0.5938 0.5938 0.8497 0.8497 0.5866 0.5866 0.5725 0.9138 0.9138 0.8892 0.9049 0.9335 1.0558 2.1253 Silhouette 0.5122 0.5091 0.4260 0.4077 0.4077 0.3664 0.3676 0.4060 0.3801 0.3749 0.3322 0.3646 0.3418 0.2811 0.2478 0.2402 0.2469 0.2213 0.1659 0.1207 0.1050 0.0832 0.0691pam Connectivity 7.2385 14.1385 17.4746 24.0024 26.6857 32.0413 33.8913 36.0579 38.6607 40.6607 42.7869 45.7742 47.2742 51.7242 53.7242 56.9742 58.7242 60.7242 62.7242 64.7242 66.7242 69.2242 71.2242 Dunn 0.2070 0.1462 0.2180 0.2180 0.2978 0.2980 0.4390 0.4390 0.4390 0.4390 0.4390 0.8497 0.8497 0.5314 0.5314 0.4782 0.9138 0.9138 0.8333 0.8189 0.7937 1.0558 2.1253 Silhouette 0.5122 0.3716 0.4250 0.3581 0.3587 0.3318 0.3606 0.3592 0.3664 0.3237 0.3665 0.3646 0.3418 0.2830 0.2497 0.2389 0.2469 0.2213 0.1758 0.1598 0.1380 0.0832 0.0691Optimal Scores: Score Method ClustersConnectivity 4.1829 hierarchical 2 Dunn 2.1253 hierarchical 24 Silhouette 0.5122 kmeans 2"
},
{
"code": null,
"e": 16413,
"s": 16203,
"text": "Connectivity and Silhouette are both measurements of connectedness while the Dunn Index is the ratio of the smallest distance between observations not in the same cluster to the largest intra-cluster distance."
},
{
"code": null,
"e": 18014,
"s": 16413,
"text": "As mentioned earlier it’s difficult to assess the quality of results from clustering. We don’t have true labels so so it’s unclear how one would measure “how good it actually works” in term of interal validation. However, clustering is an excellent EDA starting point for exploring the differences between clusters in greater detail. Think of clustering like manufacturing shirt sizes. We could choose to only make three sizes: small, medium and large. we’re sure to cut down cost but not everyone is going to have a great fit. Think about pant sizes now (or shirt brands with many sizes (XS, XL, XXL, etc.)) where you have many more categories (or clusters). For some fields the choice of optimal cluster may depend on some external knowledge like cost of producing k clusters to satisfy customers with the best possible fit. In other domains like biology where you are trying to determine the exact number of cells a more in-depth approach would be required. For example, many of the above heuristics contradicted each other for what the optimal number of clusters was. Keep in mind these were all evaluating the k-means algorithm at different numbers of k. This could potentially mean that the k-means algorithm fails and no k is good. The k-means algorithm is not a very robust algorithm that is sensitive to outliers and this data set is quit small. The best thing to do would be to explore the above methods on the output of other algorithms (for example hierarchical clustering which clValid suggested), collect more data, or spend some time labelling samples for other ML methods if possible."
},
{
"code": null,
"e": 18258,
"s": 18014,
"text": "Ultimately, we would like to answer questions like “what is it that makes this cluster unique from others?” and “what are the clusters that are similar to one another”. Let’s select five clusters and interrogate the features of these clusters."
},
{
"code": null,
"e": 18600,
"s": 18258,
"text": "# Compute dissimilarity matrix with euclidean distancesd <- dist(mammals_scaled, method = \"euclidean\")# Hierarchical clustering using Ward's methodres.hc <- hclust(d, method = \"ward.D2\" )# Cut tree into 5 groupsgrp <- cutree(res.hc, k = 5)# Visualizeplot(res.hc, cex = 0.6) # plot treerect.hclust(res.hc, k = 5, border = 2:5) # add rectangle"
},
{
"code": null,
"e": 18758,
"s": 18600,
"text": "# Execution of k-means with k=5final <- kmeans(mammals_scaled, 5, nstart = 30)fviz_cluster(final, data = mammals_scaled) + theme_minimal() + ggtitle(\"k = 5\")"
},
{
"code": null,
"e": 18879,
"s": 18758,
"text": "Let’s extract the clusters and add them back to our initial data to do some descriptive statistics at the cluster level:"
},
{
"code": null,
"e": 19025,
"s": 18879,
"text": "as.data.frame(mammals_scaled) %>% mutate(Cluster = final$cluster) %>% group_by(Cluster) %>% summarise_all(\"mean\") %>% kable() %>% kable_styling()"
},
{
"code": null,
"e": 19267,
"s": 19025,
"text": "We see that cluster 2, composed solely of the Rabbit has a high ash content. Group 3 composed of the seal and dolphin are high in fat, which makes sense given the harsh demands of such a cold climate whil group 4 has a large lactose content."
},
{
"code": null,
"e": 19934,
"s": 19267,
"text": "mammals_df <- as.data.frame(mammals_scaled) %>% rownames_to_column()cluster_pos <- as.data.frame(final$cluster) %>% rownames_to_column()colnames(cluster_pos) <- c(\"rowname\", \"cluster\")mammals_final <- inner_join(cluster_pos, mammals_df)ggRadar(mammals_final[-1], aes(group = cluster), rescale = FALSE, legend.position = \"none\", size = 1, interactive = FALSE, use.label = TRUE) + facet_wrap(~cluster) + scale_y_discrete(breaks = NULL) + # don't show tickstheme(axis.text.x = element_text(size = 10)) + scale_fill_manual(values = rep(\"#1c6193\", nrow(mammals_final))) +scale_color_manual(values = rep(\"#1c6193\", nrow(mammals_final))) +ggtitle(\"Mammals Milk Attributes\")"
},
{
"code": null,
"e": 20260,
"s": 19934,
"text": "mammals_df <- as.data.frame(mammals_scaled)mammals_df$cluster <- final$clustermammals_df$cluster <- as.character(mammals_df$cluster)ggpairs(mammals_df, 1:5, mapping = ggplot2::aes(color = cluster, alpha = 0.5), diag = list(continuous = wrap(\"densityDiag\")), lower=list(continuous = wrap(\"points\", alpha=0.9)))"
},
{
"code": null,
"e": 20755,
"s": 20260,
"text": "# plot specific graphs from previous matrix with scatterplotg <- ggplot(mammals_df, aes(x = water, y = lactose, color = cluster)) + geom_point() + theme(legend.position = \"bottom\")ggExtra::ggMarginal(g, type = \"histogram\", bins = 20, color = \"grey\", fill = \"blue\")b <- ggplot(mammals_df, aes(x = protein, y = fat, color = cluster)) + geom_point() + theme(legend.position = \"bottom\")ggExtra::ggMarginal(b, type = \"histogram\", bins = 20, color = \"grey\", fill = \"blue\")"
},
{
"code": null,
"e": 21211,
"s": 20755,
"text": "ggplot(mammals_df, aes(x = cluster, y = protein)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = fat)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = lactose)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = ash)) + geom_boxplot(aes(fill = cluster))ggplot(mammals_df, aes(x = cluster, y = water)) + geom_boxplot(aes(fill = cluster))"
},
{
"code": null,
"e": 21540,
"s": 21211,
"text": "# Parallel coordiante plots allow us to put each feature on seperate column and lines connecting each columnggparcoord(data = mammals_df, columns = 1:5, groupColumn = 6, alphaLines = 0.4, title = \"Parallel Coordinate Plot for the Mammals Milk Data\", scale = \"globalminmax\", showPoints = TRUE) + theme(legend.position = \"bottom\")"
},
{
"code": null,
"e": 21635,
"s": 21540,
"text": "If you find this article useful feel free to share it with others or recommend this article! 😃"
}
] |
VB.Net - RadioButton Control
|
The RadioButton control is used to provide a set of mutually exclusive options. The user can select one radio button in a group. If you need to place more than one group of radio buttons in the same form, you should place them in different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping on the form.
The Checked property of the radio button is used to set the state of a radio button. You can display text, image or both on radio button control. You can also change the appearance of the radio button control by using the Appearance property.
The following are some of the commonly used properties of the RadioButton control −
Appearance
Gets or sets a value determining the appearance of the radio button.
AutoCheck
Gets or sets a value indicating whether the Checked value and the appearance of the control automatically change when the control is clicked.
CheckAlign
Gets or sets the location of the check box portion of the radio button.
Checked
Gets or sets a value indicating whether the control is checked.
Text
Gets or sets the caption for a radio button.
TabStop
Gets or sets a value indicating whether a user can give focus to the RadioButton control using the TAB key.
The following are some of the commonly used methods of the RadioButton control −
PerformClick
Generates a Click event for the control, simulating a click by a user.
The following are some of the commonly used events of the RadioButton control −
AppearanceChanged
Occurs when the value of the Appearance property of the RadioButton control is changed.
CheckedChanged
Occurs when the value of the Checked property of the RadioButton control is changed.
Consult Microsoft documentation for detailed list of properties, methods and events of the RadioButton control.
In the following example, let us create two groups of radio buttons and use their CheckedChanged events for changing the BackColor and ForeColor property of the form.
Let's double click on the radio buttons and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Sub RadioButton1_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton1.CheckedChanged
Me.BackColor = Color.Red
End Sub
Private Sub RadioButton2_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton2.CheckedChanged
Me.BackColor = Color.Green
End Sub
Private Sub RadioButton3_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton3.CheckedChanged
Me.BackColor = Color.Blue
End Sub
Private Sub RadioButton4_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton4.CheckedChanged
Me.ForeColor = Color.Black
End Sub
Private Sub RadioButton5_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton5.CheckedChanged
Me.ForeColor = Color.White
End Sub
Private Sub RadioButton6_CheckedChanged(sender As Object, _
e As EventArgs) Handles RadioButton6.CheckedChanged
Me.ForeColor = Color.Red
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2584,
"s": 2300,
"text": "The RadioButton control is used to provide a set of mutually exclusive options. The user can select one radio button in a group. If you need to place more than one group of radio buttons in the same form, you should place them in different container controls like a GroupBox control."
},
{
"code": null,
"e": 2693,
"s": 2584,
"text": "Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping on the form."
},
{
"code": null,
"e": 2936,
"s": 2693,
"text": "The Checked property of the radio button is used to set the state of a radio button. You can display text, image or both on radio button control. You can also change the appearance of the radio button control by using the Appearance property."
},
{
"code": null,
"e": 3020,
"s": 2936,
"text": "The following are some of the commonly used properties of the RadioButton control −"
},
{
"code": null,
"e": 3031,
"s": 3020,
"text": "Appearance"
},
{
"code": null,
"e": 3100,
"s": 3031,
"text": "Gets or sets a value determining the appearance of the radio button."
},
{
"code": null,
"e": 3110,
"s": 3100,
"text": "AutoCheck"
},
{
"code": null,
"e": 3252,
"s": 3110,
"text": "Gets or sets a value indicating whether the Checked value and the appearance of the control automatically change when the control is clicked."
},
{
"code": null,
"e": 3263,
"s": 3252,
"text": "CheckAlign"
},
{
"code": null,
"e": 3335,
"s": 3263,
"text": "Gets or sets the location of the check box portion of the radio button."
},
{
"code": null,
"e": 3343,
"s": 3335,
"text": "Checked"
},
{
"code": null,
"e": 3407,
"s": 3343,
"text": "Gets or sets a value indicating whether the control is checked."
},
{
"code": null,
"e": 3412,
"s": 3407,
"text": "Text"
},
{
"code": null,
"e": 3457,
"s": 3412,
"text": "Gets or sets the caption for a radio button."
},
{
"code": null,
"e": 3465,
"s": 3457,
"text": "TabStop"
},
{
"code": null,
"e": 3573,
"s": 3465,
"text": "Gets or sets a value indicating whether a user can give focus to the RadioButton control using the TAB key."
},
{
"code": null,
"e": 3654,
"s": 3573,
"text": "The following are some of the commonly used methods of the RadioButton control −"
},
{
"code": null,
"e": 3667,
"s": 3654,
"text": "PerformClick"
},
{
"code": null,
"e": 3738,
"s": 3667,
"text": "Generates a Click event for the control, simulating a click by a user."
},
{
"code": null,
"e": 3818,
"s": 3738,
"text": "The following are some of the commonly used events of the RadioButton control −"
},
{
"code": null,
"e": 3836,
"s": 3818,
"text": "AppearanceChanged"
},
{
"code": null,
"e": 3924,
"s": 3836,
"text": "Occurs when the value of the Appearance property of the RadioButton control is changed."
},
{
"code": null,
"e": 3939,
"s": 3924,
"text": "CheckedChanged"
},
{
"code": null,
"e": 4024,
"s": 3939,
"text": "Occurs when the value of the Checked property of the RadioButton control is changed."
},
{
"code": null,
"e": 4136,
"s": 4024,
"text": "Consult Microsoft documentation for detailed list of properties, methods and events of the RadioButton control."
},
{
"code": null,
"e": 4303,
"s": 4136,
"text": "In the following example, let us create two groups of radio buttons and use their CheckedChanged events for changing the BackColor and ForeColor property of the form."
},
{
"code": null,
"e": 4389,
"s": 4303,
"text": "Let's double click on the radio buttons and put the follow code in the opened window."
},
{
"code": null,
"e": 5600,
"s": 4389,
"text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspont.com\"\n End Sub\n\n Private Sub RadioButton1_CheckedChanged(sender As Object, _\n e As EventArgs) Handles RadioButton1.CheckedChanged\n Me.BackColor = Color.Red\n End Sub\n \n Private Sub RadioButton2_CheckedChanged(sender As Object, _\n e As EventArgs) Handles RadioButton2.CheckedChanged\n Me.BackColor = Color.Green\n End Sub\n \n Private Sub RadioButton3_CheckedChanged(sender As Object, _ \n e As EventArgs) Handles RadioButton3.CheckedChanged\n Me.BackColor = Color.Blue\n End Sub\n \n Private Sub RadioButton4_CheckedChanged(sender As Object, _\n e As EventArgs) Handles RadioButton4.CheckedChanged\n Me.ForeColor = Color.Black\n End Sub\n \n Private Sub RadioButton5_CheckedChanged(sender As Object, _\n e As EventArgs) Handles RadioButton5.CheckedChanged\n Me.ForeColor = Color.White\n End Sub\n \n Private Sub RadioButton6_CheckedChanged(sender As Object, _\n e As EventArgs) Handles RadioButton6.CheckedChanged\n Me.ForeColor = Color.Red\n End Sub\nEnd Class"
},
{
"code": null,
"e": 5746,
"s": 5600,
"text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −"
},
{
"code": null,
"e": 5779,
"s": 5746,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5796,
"s": 5779,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5831,
"s": 5796,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5846,
"s": 5831,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5881,
"s": 5846,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5896,
"s": 5881,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5929,
"s": 5896,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5944,
"s": 5929,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5951,
"s": 5944,
"text": " Print"
},
{
"code": null,
"e": 5962,
"s": 5951,
"text": " Add Notes"
}
] |
How to pick the RIGHT model. Looking at accuracy distribution, IQR... | by François St-Amant | Towards Data Science
|
Finding yourself with a few models/methods that perform almost equally is not rare in data science. When that happens, how do you know which model to choose? In this article, I will present a way to pick the best model, the real one.
I will be using the Breast Cancer Wisconsin Dataset, available here: https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It contains 569 observations and 32 descriptive variables. The dependent variable, diagnosis, is binary. It is equal to 1 if the cancer is malignant and to 0 if the cancer is benign. Let’s begin by importing the needed packages and the data.
library(ggplot2)library(randomForest)library (e1071)library(devtools)library(ggbiplot)#Import datadf = read.csv("data.csv")
Then, quickly, let’s clean the data (some columns are empty or useless) and transform the diagnosis variable into a [0,1] variable instead of a string.
#Y as factordf$diagnosis = ifelse(df$diagnosis=="M", gsub("M", 1, df$diagnosis), gsub("B", 0, df$diagnosis))df$diagnosis = as.factor(df$diagnosis)#Remove useless columnsdf = df[,c(-33,-1)]
Here is the distribution of the dependent variable:
The classes don’t appear to be imbalanced. We can now move on to the next step. Below, I will create a “for loop”. In every iteration of the loop, I will separate data into two sets, training and validation. Afterwards, I will train and predict three separate models, using Random Forests, SVM and Logistic Regression. By putting all this into a “for loop” and changing the seed every time, it will allow me to each time collect the accuracy performance of the three models at each iteration. Changing the set.seed() changes the random repartition of data between train and validation.
This is essentially cross validation on three models at the same time. It is also beneficial because it allows me to compare the models on the same datasets every time. Each model is trained and validated on the same data, for every iteration. This means that we can make a fair and consistent comparison between each of the fitted models. Here is the code:
Here is the mean accuracy for the three models over the 200 iterations:
Random Forests: 96.7%SVM: 95.1%Logistic Regression: 97.1%
Random Forests: 96.7%
SVM: 95.1%
Logistic Regression: 97.1%
Logistic Regression seems to be the best algorithm for this dataset. However, to pick the RIGHT model, we cannot stop here.
Looking at the results above, we see that Logistic Regression wins but that the difference in its accuracy and the other models accuracy is not that significant. In order to know if we really have the best model, we need to look at the distribution of the accuracy measures. It is similar to the idea of marginal interpretation vs conditional interpretation: is the model good on average or is it always performing well, no matter the data.
This is useful because it lets us know if the models are always precise or if their performance is variable. We might want the best average model or the least variable model, depending on the situation. Having the accuracy distribution information can only help in making a coherent choice!
Here is how to get the plot of the distributions stored in the result_matrix, using the density function:
a=density(result_matrix[,1])#Getting the plotplot(a, xlim=c(0.92, 1), ylim=c(0, 60), col='blue', lwd=2, main='Accuracy distribution of all models', xlab='Accuracy')lines(density(result_matrix[,2]), col='red', lwd=2)lines(density(result_matrix[,3]), col='green', lwd=2)legend(x=0.975, y=59,legend = c("Random Forest", "SVM", "Logistic Regression"), col = c("blue","red", 'green'), lty = c(1,1))
We see that Logistic Regression does seem to be narrowingly better than Random Forests, even if both accuracy distributions are spread pretty symmetrically and leanly around their mean (logistic regression seems to be ever so slightly leaner). Indeed, both distributions look normal. However, SVM distribution seems to be much more variable, with a much larger spread, and almost a second peek at around 95% accuracy.
We can also get box plots and the interquantile range, which will let us see if we have outliers (with box plots) and how narrow is the range between the 1st and 3rd quantile in our accuracy values (with IQR). Here is how to do it:
#Boxplotsboxplot(result_matrix, use.cols = TRUE, main='Boxplot by algorithm', ylab='Accuracy', xaxt = "n", col=c('blue', 'red', 'green'))axis(1, at=1:3, labels=c('Random Forests', 'SVM', 'Logistic Regression'))#IQRIQR(result_matrix[,1])IQR(result_matrix[,2])IQR(result_matrix[,3])
Here are the IQRs for the three algorithms:
Random Forests: 1.05SVM: 1.4Logistic Regression: 1.05
Random Forests: 1.05
SVM: 1.4
Logistic Regression: 1.05
This means that for Random Forests and Logistic Regression, 50% of the values (between the first and the third quantile) are found in a range of 1.05% of accuracy. For SVM, the IQR is a bit wider, at 1.4%.
Looking at the boxplots, what we see is that for all three methods, we have very few outliers (1 or 2). Logistic Regression only has 1, while Random Forests has 2.
Now, I believe we can objectively say that the Logistic Regression algorithm is the best one to use in our case, and we have the data to prove it.
Thanks for reading!
|
[
{
"code": null,
"e": 406,
"s": 172,
"text": "Finding yourself with a few models/methods that perform almost equally is not rare in data science. When that happens, how do you know which model to choose? In this article, I will present a way to pick the best model, the real one."
},
{
"code": null,
"e": 776,
"s": 406,
"text": "I will be using the Breast Cancer Wisconsin Dataset, available here: https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It contains 569 observations and 32 descriptive variables. The dependent variable, diagnosis, is binary. It is equal to 1 if the cancer is malignant and to 0 if the cancer is benign. Let’s begin by importing the needed packages and the data."
},
{
"code": null,
"e": 900,
"s": 776,
"text": "library(ggplot2)library(randomForest)library (e1071)library(devtools)library(ggbiplot)#Import datadf = read.csv(\"data.csv\")"
},
{
"code": null,
"e": 1052,
"s": 900,
"text": "Then, quickly, let’s clean the data (some columns are empty or useless) and transform the diagnosis variable into a [0,1] variable instead of a string."
},
{
"code": null,
"e": 1301,
"s": 1052,
"text": "#Y as factordf$diagnosis = ifelse(df$diagnosis==\"M\", gsub(\"M\", 1, df$diagnosis), gsub(\"B\", 0, df$diagnosis))df$diagnosis = as.factor(df$diagnosis)#Remove useless columnsdf = df[,c(-33,-1)]"
},
{
"code": null,
"e": 1353,
"s": 1301,
"text": "Here is the distribution of the dependent variable:"
},
{
"code": null,
"e": 1939,
"s": 1353,
"text": "The classes don’t appear to be imbalanced. We can now move on to the next step. Below, I will create a “for loop”. In every iteration of the loop, I will separate data into two sets, training and validation. Afterwards, I will train and predict three separate models, using Random Forests, SVM and Logistic Regression. By putting all this into a “for loop” and changing the seed every time, it will allow me to each time collect the accuracy performance of the three models at each iteration. Changing the set.seed() changes the random repartition of data between train and validation."
},
{
"code": null,
"e": 2297,
"s": 1939,
"text": "This is essentially cross validation on three models at the same time. It is also beneficial because it allows me to compare the models on the same datasets every time. Each model is trained and validated on the same data, for every iteration. This means that we can make a fair and consistent comparison between each of the fitted models. Here is the code:"
},
{
"code": null,
"e": 2369,
"s": 2297,
"text": "Here is the mean accuracy for the three models over the 200 iterations:"
},
{
"code": null,
"e": 2427,
"s": 2369,
"text": "Random Forests: 96.7%SVM: 95.1%Logistic Regression: 97.1%"
},
{
"code": null,
"e": 2449,
"s": 2427,
"text": "Random Forests: 96.7%"
},
{
"code": null,
"e": 2460,
"s": 2449,
"text": "SVM: 95.1%"
},
{
"code": null,
"e": 2487,
"s": 2460,
"text": "Logistic Regression: 97.1%"
},
{
"code": null,
"e": 2611,
"s": 2487,
"text": "Logistic Regression seems to be the best algorithm for this dataset. However, to pick the RIGHT model, we cannot stop here."
},
{
"code": null,
"e": 3052,
"s": 2611,
"text": "Looking at the results above, we see that Logistic Regression wins but that the difference in its accuracy and the other models accuracy is not that significant. In order to know if we really have the best model, we need to look at the distribution of the accuracy measures. It is similar to the idea of marginal interpretation vs conditional interpretation: is the model good on average or is it always performing well, no matter the data."
},
{
"code": null,
"e": 3343,
"s": 3052,
"text": "This is useful because it lets us know if the models are always precise or if their performance is variable. We might want the best average model or the least variable model, depending on the situation. Having the accuracy distribution information can only help in making a coherent choice!"
},
{
"code": null,
"e": 3449,
"s": 3343,
"text": "Here is how to get the plot of the distributions stored in the result_matrix, using the density function:"
},
{
"code": null,
"e": 3847,
"s": 3449,
"text": "a=density(result_matrix[,1])#Getting the plotplot(a, xlim=c(0.92, 1), ylim=c(0, 60), col='blue', lwd=2, main='Accuracy distribution of all models', xlab='Accuracy')lines(density(result_matrix[,2]), col='red', lwd=2)lines(density(result_matrix[,3]), col='green', lwd=2)legend(x=0.975, y=59,legend = c(\"Random Forest\", \"SVM\", \"Logistic Regression\"), col = c(\"blue\",\"red\", 'green'), lty = c(1,1))"
},
{
"code": null,
"e": 4265,
"s": 3847,
"text": "We see that Logistic Regression does seem to be narrowingly better than Random Forests, even if both accuracy distributions are spread pretty symmetrically and leanly around their mean (logistic regression seems to be ever so slightly leaner). Indeed, both distributions look normal. However, SVM distribution seems to be much more variable, with a much larger spread, and almost a second peek at around 95% accuracy."
},
{
"code": null,
"e": 4497,
"s": 4265,
"text": "We can also get box plots and the interquantile range, which will let us see if we have outliers (with box plots) and how narrow is the range between the 1st and 3rd quantile in our accuracy values (with IQR). Here is how to do it:"
},
{
"code": null,
"e": 4802,
"s": 4497,
"text": "#Boxplotsboxplot(result_matrix, use.cols = TRUE, main='Boxplot by algorithm', ylab='Accuracy', xaxt = \"n\", col=c('blue', 'red', 'green'))axis(1, at=1:3, labels=c('Random Forests', 'SVM', 'Logistic Regression'))#IQRIQR(result_matrix[,1])IQR(result_matrix[,2])IQR(result_matrix[,3])"
},
{
"code": null,
"e": 4846,
"s": 4802,
"text": "Here are the IQRs for the three algorithms:"
},
{
"code": null,
"e": 4900,
"s": 4846,
"text": "Random Forests: 1.05SVM: 1.4Logistic Regression: 1.05"
},
{
"code": null,
"e": 4921,
"s": 4900,
"text": "Random Forests: 1.05"
},
{
"code": null,
"e": 4930,
"s": 4921,
"text": "SVM: 1.4"
},
{
"code": null,
"e": 4956,
"s": 4930,
"text": "Logistic Regression: 1.05"
},
{
"code": null,
"e": 5162,
"s": 4956,
"text": "This means that for Random Forests and Logistic Regression, 50% of the values (between the first and the third quantile) are found in a range of 1.05% of accuracy. For SVM, the IQR is a bit wider, at 1.4%."
},
{
"code": null,
"e": 5326,
"s": 5162,
"text": "Looking at the boxplots, what we see is that for all three methods, we have very few outliers (1 or 2). Logistic Regression only has 1, while Random Forests has 2."
},
{
"code": null,
"e": 5473,
"s": 5326,
"text": "Now, I believe we can objectively say that the Logistic Regression algorithm is the best one to use in our case, and we have the data to prove it."
}
] |
Roman Number to Integer | Practice | GeeksforGeeks
|
Given a string in roman no format (s) your task is to convert it to an integer . Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input:
s = V
Output: 5
Example 2:
Input:
s = III
Output: 3
Your Task:
Complete the function romanToDecimal() which takes a string as input parameter and returns the equivalent decimal number.
Expected Time Complexity: O(|S|), |S| = length of string S.
Expected Auxiliary Space: O(1)
Constraints:
1<=roman no range<=3999
0
preethirakasi4 days ago
Can someone say what's wrong with this code, its failing for this i/p:-"CMXVI" , my program o/p here after submiting is 916, expected is 1116. When i run this outside on any othersite its giving me correct o/p for the above i/p
public int romanToDecimal(String str) { // code here HashMap<String,Integer> RomanValuesMap=new HashMap<String,Integer>(); RomanValuesMap.put("I",1); RomanValuesMap.put("V",5); RomanValuesMap.put("X",10); RomanValuesMap.put("L",50); RomanValuesMap.put("C",100); RomanValuesMap.put("D",500); RomanValuesMap.put("M",1000); int count=0; for(int i=0;i<str.length();i++){ char ch=str.charAt(i); String s=Character.toString(ch); if(RomanValuesMap.containsKey(s)){ count+=RomanValuesMap.get(s); } } return count; }
0
chandumarghade6 days ago
Code For JAVA
class Solution {
// Finds decimal value of a given roman numeral
public int romanToDecimal(String str) {
int sum=0;
for(int i=0;i<str.length()-1;i++){
int a =value(str.charAt(i));
int b =value(str.charAt(i+1));
if(a>=b){
sum=sum+value(str.charAt(i));
}
else {
sum=sum-value(str.charAt(i));
}
}
sum=sum+value(str.charAt(str.length()-1));
return sum;
// code here
}
public int value(char s){
if(s=='I'){
return 1;
}
else if(s=='V'){
return 5;
}
else if(s=='X'){
return 10;
}
else if(s=='L'){
return 50;
}
else if(s=='C'){
return 100;
}
else if(s=='D'){
return 500;
}
else if(s=='M'){
return 1000;
}
return -1;
}
}
+2
darkvoid65656 days ago
EASY TO READ SOLUTION-→
Runtime = 0.01 sec
idea is to store the value of roman numbers in an unordered map, and iterate over the string if char at i> i+1,then add, otherwise subtract it from the ans, it is the rule of writing roman numbers.
class Solution { public: int romanToDecimal(string &str) {unordered_map<char,int> m; m['I']=1; m['V']=5; m['X']=10; m['L']=50; m['C']=100; m['D']=500; m['M']=1000; int n=str.length(); int ans=0; for (int i = 0; i < n; i++) {if (m[str[i]]>=m[str[i+1]]) { ans+=m[str[i]]; } else{ ans-=m[str[i]]; } } return ans; }};upvote if you understand
0
velspace011 week ago
Java sol
public int romanToDecimal(String str) {
HashMap<String,Integer> hm=new HashMap<>();
hm.put("M",1000);
hm.put("CM",900);
hm.put("D",500);
hm.put("CD",400);
hm.put("C",100);
hm.put("XC",90);
hm.put("L",50);
hm.put("XL",40);
hm.put("X",10);
hm.put("IX",9);
hm.put("V",5);
hm.put("IV",4);
hm.put("I",1);
int sum=0;
for(int i=0;i<str.length();i++){
String s=" ";
if(i<str.length()-1){
s=str.substring(i,i+2);
}
if(hm.containsKey(s)){
sum+=hm.get(s);
i++;
}else{
sum+=hm.get(str.substring(i,i+1));
}
}
return sum;
}
+1
badgujarsachin831 week ago
int romanToDecimal(string &str) {
// code here
map<char,int> mp={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int val=0;
int pre=INT_MAX;
for(int i=0;i<str.size();i++){
if(mp[str[i]]>=mp[str[i+1]]){
val+=mp[str[i]];
}else{
val-=mp[str[i]];
}
}
return val;
}
-1
tapanmanu20002 weeks ago
0.01 sec runtime
int romanToDecimal(string &str) {
map<char,int> romans = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},
{'D',500},{'M',1000}};
int val = 0;
int prev = INT_MAX;
for(auto ch:str){
if(romans.find(ch) != romans.end()){
if(romans[ch] > prev){
val -= 2 * prev;
}
val += romans[ch];
}
prev = romans[ch];
}
return val;
}
+2
anandgeeky2 weeks ago
JAVA CODE:
class Solution { // Finds decimal value of a given roman numeral public int romanToDecimal(String str) { // code here int result = convertRomanToInteger(str.charAt(0)); for(int i = 1; i < str.length(); i++) { int pre = convertRomanToInteger(str.charAt(i - 1)); int curr = convertRomanToInteger(str.charAt(i)); if(pre >= curr) result += curr; else result = result - pre + curr - pre; } return result; } private int convertRomanToInteger(char roman) { switch(roman) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; }}
-1
mdnafishalam542 weeks ago
int romanToDecimal(string &str) { // code here map<char,int> val={ {'I',1},{'V',5},{'X',10},{'L',50}, {'C',100},{'D',500},{'M',1000} }; int decimal=0; for(int i=0;i<str.size();i++){ // If the current value is greater than or equal // to the value of the symbol to the right if(val[str[i]]>=val[str[i+1]]) decimal+=val[str[i]]; // If the current value is smaller than // the value of the symbol to the right else decimal-=val[str[i]]; } return decimal; }
+1
lokeshchoubisa263 weeks ago
int romanToDecimal(string &str) { // code here map<char,int> m; m.insert({'I',1}); m.insert({'V',5}); m.insert({'X',10}); m.insert({'L',50}); m.insert({'C',100}); m.insert({'D',500}); m.insert({'M',1000}); int n=str.size(); char ch=str[n-1]; int sum=m[ch]; int prev=sum; for(int i=str.size()-2;i>=0;i--) { char ch=str[i]; if(m[ch]>=prev) { sum+=m[ch]; } else { sum-=m[ch]; } prev=m[ch]; } return sum; }
0
imohdalam3 weeks ago
JAVA | O(n)
class Solution {
// Finds decimal value of a given roman numeral
public int romanToDecimal(String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int result = 0;
int n = str.length();
for(int i=0; i<n-1; i++){
char curr = str.charAt(i);
char next = str.charAt(i + 1);
if(map.get(curr) < map.get(next))
result -= map.get(curr);
else
result += map.get(curr);
}
result += map.get(str.charAt(n - 1));
return result;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 407,
"s": 238,
"text": "Given a string in roman no format (s) your task is to convert it to an integer . Various symbols and their values are given below.\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000"
},
{
"code": null,
"e": 418,
"s": 407,
"text": "Example 1:"
},
{
"code": null,
"e": 442,
"s": 418,
"text": "Input:\ns = V\nOutput: 5\n"
},
{
"code": null,
"e": 453,
"s": 442,
"text": "Example 2:"
},
{
"code": null,
"e": 480,
"s": 453,
"text": "Input:\ns = III \nOutput: 3\n"
},
{
"code": null,
"e": 614,
"s": 480,
"text": "Your Task:\nComplete the function romanToDecimal() which takes a string as input parameter and returns the equivalent decimal number. "
},
{
"code": null,
"e": 705,
"s": 614,
"text": "Expected Time Complexity: O(|S|), |S| = length of string S.\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 742,
"s": 705,
"text": "Constraints:\n1<=roman no range<=3999"
},
{
"code": null,
"e": 746,
"s": 744,
"text": "0"
},
{
"code": null,
"e": 770,
"s": 746,
"text": "preethirakasi4 days ago"
},
{
"code": null,
"e": 998,
"s": 770,
"text": "Can someone say what's wrong with this code, its failing for this i/p:-\"CMXVI\" , my program o/p here after submiting is 916, expected is 1116. When i run this outside on any othersite its giving me correct o/p for the above i/p"
},
{
"code": null,
"e": 1642,
"s": 1000,
"text": "public int romanToDecimal(String str) { // code here HashMap<String,Integer> RomanValuesMap=new HashMap<String,Integer>(); RomanValuesMap.put(\"I\",1); RomanValuesMap.put(\"V\",5); RomanValuesMap.put(\"X\",10); RomanValuesMap.put(\"L\",50); RomanValuesMap.put(\"C\",100); RomanValuesMap.put(\"D\",500); RomanValuesMap.put(\"M\",1000); int count=0; for(int i=0;i<str.length();i++){ char ch=str.charAt(i); String s=Character.toString(ch); if(RomanValuesMap.containsKey(s)){ count+=RomanValuesMap.get(s); } } return count; }"
},
{
"code": null,
"e": 1644,
"s": 1642,
"text": "0"
},
{
"code": null,
"e": 1669,
"s": 1644,
"text": "chandumarghade6 days ago"
},
{
"code": null,
"e": 2683,
"s": 1669,
"text": "Code For JAVA\n\nclass Solution {\n // Finds decimal value of a given roman numeral\n public int romanToDecimal(String str) {\n int sum=0;\n for(int i=0;i<str.length()-1;i++){\n int a =value(str.charAt(i));\n int b =value(str.charAt(i+1));\n if(a>=b){\n sum=sum+value(str.charAt(i));\n }\n else {\n sum=sum-value(str.charAt(i));\n }\n }\n \n sum=sum+value(str.charAt(str.length()-1));\n return sum;\n // code here\n }\n public int value(char s){\n if(s=='I'){\n return 1;\n }\n else if(s=='V'){\n return 5;\n }\n else if(s=='X'){\n return 10;\n }\n else if(s=='L'){\n return 50;\n }\n else if(s=='C'){\n return 100;\n }\n else if(s=='D'){\n return 500;\n }\n else if(s=='M'){\n return 1000;\n }\n return -1;\n }\n}"
},
{
"code": null,
"e": 2686,
"s": 2683,
"text": "+2"
},
{
"code": null,
"e": 2709,
"s": 2686,
"text": "darkvoid65656 days ago"
},
{
"code": null,
"e": 2733,
"s": 2709,
"text": "EASY TO READ SOLUTION-→"
},
{
"code": null,
"e": 2752,
"s": 2733,
"text": "Runtime = 0.01 sec"
},
{
"code": null,
"e": 2950,
"s": 2752,
"text": "idea is to store the value of roman numbers in an unordered map, and iterate over the string if char at i> i+1,then add, otherwise subtract it from the ans, it is the rule of writing roman numbers."
},
{
"code": null,
"e": 3370,
"s": 2950,
"text": "class Solution { public: int romanToDecimal(string &str) {unordered_map<char,int> m; m['I']=1; m['V']=5; m['X']=10; m['L']=50; m['C']=100; m['D']=500; m['M']=1000; int n=str.length(); int ans=0; for (int i = 0; i < n; i++) {if (m[str[i]]>=m[str[i+1]]) { ans+=m[str[i]]; } else{ ans-=m[str[i]]; } } return ans; }};upvote if you understand"
},
{
"code": null,
"e": 3372,
"s": 3370,
"text": "0"
},
{
"code": null,
"e": 3393,
"s": 3372,
"text": "velspace011 week ago"
},
{
"code": null,
"e": 4193,
"s": 3393,
"text": "Java sol\npublic int romanToDecimal(String str) {\n HashMap<String,Integer> hm=new HashMap<>();\n hm.put(\"M\",1000);\n hm.put(\"CM\",900);\n hm.put(\"D\",500);\n hm.put(\"CD\",400);\n hm.put(\"C\",100);\n hm.put(\"XC\",90);\n hm.put(\"L\",50);\n hm.put(\"XL\",40);\n hm.put(\"X\",10);\n hm.put(\"IX\",9);\n hm.put(\"V\",5);\n hm.put(\"IV\",4);\n hm.put(\"I\",1);\n int sum=0;\n for(int i=0;i<str.length();i++){\n String s=\" \";\n if(i<str.length()-1){\n s=str.substring(i,i+2);\n }\n if(hm.containsKey(s)){\n sum+=hm.get(s);\n i++;\n }else{\n sum+=hm.get(str.substring(i,i+1));\n }\n }\n return sum;\n }"
},
{
"code": null,
"e": 4196,
"s": 4193,
"text": "+1"
},
{
"code": null,
"e": 4223,
"s": 4196,
"text": "badgujarsachin831 week ago"
},
{
"code": null,
"e": 4632,
"s": 4223,
"text": " int romanToDecimal(string &str) {\n // code here\n map<char,int> mp={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};\n int val=0;\n int pre=INT_MAX;\n for(int i=0;i<str.size();i++){\n if(mp[str[i]]>=mp[str[i+1]]){\n val+=mp[str[i]];\n }else{\n val-=mp[str[i]];\n }\n }\n return val;\n }"
},
{
"code": null,
"e": 4635,
"s": 4632,
"text": "-1"
},
{
"code": null,
"e": 4660,
"s": 4635,
"text": "tapanmanu20002 weeks ago"
},
{
"code": null,
"e": 4677,
"s": 4660,
"text": "0.01 sec runtime"
},
{
"code": null,
"e": 5185,
"s": 4677,
"text": "int romanToDecimal(string &str) {\n map<char,int> romans = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},\n {'D',500},{'M',1000}};\n int val = 0;\n int prev = INT_MAX;\n for(auto ch:str){\n if(romans.find(ch) != romans.end()){\n if(romans[ch] > prev){\n val -= 2 * prev;\n }\n val += romans[ch];\n }\n prev = romans[ch];\n }\n return val;\n }"
},
{
"code": null,
"e": 5188,
"s": 5185,
"text": "+2"
},
{
"code": null,
"e": 5210,
"s": 5188,
"text": "anandgeeky2 weeks ago"
},
{
"code": null,
"e": 5221,
"s": 5210,
"text": "JAVA CODE:"
},
{
"code": null,
"e": 6178,
"s": 5223,
"text": "class Solution { // Finds decimal value of a given roman numeral public int romanToDecimal(String str) { // code here int result = convertRomanToInteger(str.charAt(0)); for(int i = 1; i < str.length(); i++) { int pre = convertRomanToInteger(str.charAt(i - 1)); int curr = convertRomanToInteger(str.charAt(i)); if(pre >= curr) result += curr; else result = result - pre + curr - pre; } return result; } private int convertRomanToInteger(char roman) { switch(roman) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; }}"
},
{
"code": null,
"e": 6181,
"s": 6178,
"text": "-1"
},
{
"code": null,
"e": 6207,
"s": 6181,
"text": "mdnafishalam542 weeks ago"
},
{
"code": null,
"e": 6822,
"s": 6207,
"text": " int romanToDecimal(string &str) { // code here map<char,int> val={ {'I',1},{'V',5},{'X',10},{'L',50}, {'C',100},{'D',500},{'M',1000} }; int decimal=0; for(int i=0;i<str.size();i++){ // If the current value is greater than or equal // to the value of the symbol to the right if(val[str[i]]>=val[str[i+1]]) decimal+=val[str[i]]; // If the current value is smaller than // the value of the symbol to the right else decimal-=val[str[i]]; } return decimal; }"
},
{
"code": null,
"e": 6825,
"s": 6822,
"text": "+1"
},
{
"code": null,
"e": 6853,
"s": 6825,
"text": "lokeshchoubisa263 weeks ago"
},
{
"code": null,
"e": 7497,
"s": 6853,
"text": " int romanToDecimal(string &str) { // code here map<char,int> m; m.insert({'I',1}); m.insert({'V',5}); m.insert({'X',10}); m.insert({'L',50}); m.insert({'C',100}); m.insert({'D',500}); m.insert({'M',1000}); int n=str.size(); char ch=str[n-1]; int sum=m[ch]; int prev=sum; for(int i=str.size()-2;i>=0;i--) { char ch=str[i]; if(m[ch]>=prev) { sum+=m[ch]; } else { sum-=m[ch]; } prev=m[ch]; } return sum; }"
},
{
"code": null,
"e": 7499,
"s": 7497,
"text": "0"
},
{
"code": null,
"e": 7520,
"s": 7499,
"text": "imohdalam3 weeks ago"
},
{
"code": null,
"e": 7532,
"s": 7520,
"text": "JAVA | O(n)"
},
{
"code": null,
"e": 8391,
"s": 7532,
"text": "class Solution {\n // Finds decimal value of a given roman numeral\n public int romanToDecimal(String str) {\n \n HashMap<Character, Integer> map = new HashMap<Character, Integer>();\n \n map.put('I', 1);\n map.put('V', 5);\n map.put('X', 10);\n map.put('L', 50);\n map.put('C', 100);\n map.put('D', 500);\n map.put('M', 1000);\n \n int result = 0;\n int n = str.length();\n \n for(int i=0; i<n-1; i++){\n char curr = str.charAt(i);\n char next = str.charAt(i + 1);\n if(map.get(curr) < map.get(next))\n result -= map.get(curr);\n else\n result += map.get(curr);\n }\n \n result += map.get(str.charAt(n - 1));\n \n return result;\n }\n}"
},
{
"code": null,
"e": 8537,
"s": 8391,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 8573,
"s": 8537,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8583,
"s": 8573,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8593,
"s": 8583,
"text": "\nContest\n"
},
{
"code": null,
"e": 8656,
"s": 8593,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8804,
"s": 8656,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9012,
"s": 8804,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9118,
"s": 9012,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Batch Script - PROMPT
|
This batch command can be used to change or reset the cmd.exe prompt.
PROMPT [newpromptname]
@echo off
prompt myprompt$G
The $G is the greater than sign which is added at the end of the prompt.
The prompt shown to the user will now be myprompt>
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2239,
"s": 2169,
"text": "This batch command can be used to change or reset the cmd.exe prompt."
},
{
"code": null,
"e": 2263,
"s": 2239,
"text": "PROMPT [newpromptname]\n"
},
{
"code": null,
"e": 2292,
"s": 2263,
"text": "@echo off \nprompt myprompt$G"
},
{
"code": null,
"e": 2365,
"s": 2292,
"text": "The $G is the greater than sign which is added at the end of the prompt."
},
{
"code": null,
"e": 2416,
"s": 2365,
"text": "The prompt shown to the user will now be myprompt>"
},
{
"code": null,
"e": 2423,
"s": 2416,
"text": " Print"
},
{
"code": null,
"e": 2434,
"s": 2423,
"text": " Add Notes"
}
] |
C# Program to write a number in hexadecimal format
|
Let’s say the following is the number −
int a = 12250;
You can work around the following ways to get a number in hexadecimal format −
{0:x}
{0:x8}
{0:X}
{0:X8}
Here is the code −
Live Demo
using System;
class Demo {
static void Main() {
int a = 12250;
Console.WriteLine("{0:x}", a);
Console.WriteLine("{0:x8}", a);
Console.WriteLine("{0:X}", a);
Console.WriteLine("{0:X8}", a);
}
}
2fda
00002fda
2FDA
00002FDA
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is the number −"
},
{
"code": null,
"e": 1117,
"s": 1102,
"text": "int a = 12250;"
},
{
"code": null,
"e": 1196,
"s": 1117,
"text": "You can work around the following ways to get a number in hexadecimal format −"
},
{
"code": null,
"e": 1222,
"s": 1196,
"text": "{0:x}\n{0:x8}\n{0:X}\n{0:X8}"
},
{
"code": null,
"e": 1241,
"s": 1222,
"text": "Here is the code −"
},
{
"code": null,
"e": 1252,
"s": 1241,
"text": " Live Demo"
},
{
"code": null,
"e": 1481,
"s": 1252,
"text": "using System;\nclass Demo {\n static void Main() {\n int a = 12250;\n Console.WriteLine(\"{0:x}\", a);\n Console.WriteLine(\"{0:x8}\", a);\n Console.WriteLine(\"{0:X}\", a);\n Console.WriteLine(\"{0:X8}\", a);\n }\n}"
},
{
"code": null,
"e": 1509,
"s": 1481,
"text": "2fda\n00002fda\n2FDA\n00002FDA"
}
] |
Bootstrap 4 - Flex
|
Flex utility can be used to manage the layout, alignment, grid columns, navigation and other components of the page. It makes easy to design layout structure without using float or positioning.
Use the flexbox display utilities like d-flex and d-inline-flex to display the flexbox container and children elements into flex items. You can set the direction of flex items in horizontal direction and vertical direction by using .flex-row (use .flex-row-reverse to display horizontal direction from the opposite side) and .flex-column (use .flex-column-reverse to display vertical direction from the opposite side) classes respectively as shown in the below example −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Flex Behaviors</h2>
<div class = "d-flex p-2 bg-info">
This is flex container, uses the 'd-flex' class
</div>
<br>
<div class = "d-inline-flex p-2 bg-info">
This is inline flexbox container, uses the 'd-inline-flex' class
</div>
<br>
<br>
<h2>Direction</h2>
<h4>Horizontal Direction</h4>
<div class = "d-flex flex-row bg-info mb-3">
<div class = "p-2 border border-dark ">flex-row: Item 1</div>
<div class = "p-2 border border-dark">flex-row: Item 2</div>
<div class = "p-2 border border-dark">flex-row: Item 3</div>
</div>
<div class = "d-flex flex-row-reverse bg-info">
<div class = "p-2 border border-dark">flex-row-reverse: Item 1</div>
<div class = "p-2 border border-dark">flex-row-reverse: Item 2</div>
<div class = "p-2 border border-dark">flex-row-reverse: Item 3</div>
</div>
<br>
<h4>Vertical Direction</h4>
<div class = "d-flex flex-column bg-info mb-3">
<div class = "p-2 border border-dark">flex-column: Item 1</div>
<div class = "p-2 border border-dark">flex-column: Item 2</div>
<div class = "p-2 border border-dark">flex-column: Item 3</div>
</div>
<div class = "d-flex flex-column-reverse bg-info">
<div class = "p-2 border border-dark">flex-column-reverse: Item 1</div>
<div class = "p-2 border border-dark">flex-column-reverse: Item 2</div>
<div class = "p-2 border border-dark">flex-column-reverse: Item 3</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The alignment of flex items (such as start, end, center, between and around) can be changed on the main axis (x-axis to start) of the flexbox containers by using justify-content utility.
The following example demonstrates this −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Alignment - Start</h2>
<div class = "d-flex justify-content-start bg-info">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Alignment - End</h2>
<div class = "d-flex justify-content-end bg-info">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Alignment - Center</h2>
<div class = "d-flex justify-content-center bg-info">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Alignment - Between</h2>
<div class = "d-flex justify-content-between bg-info">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Alignment - Around</h2>
<div class = "d-flex justify-content-around bg-info">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The alignment of flex items (such as start, end, center, baseline and stretch) can be changed on the cross axis (y-axis to start) of the flexbox containers by using align-items utility.
The following example demonstrates this −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Align Items - Start</h2>
<div class = "d-flex align-items-start bg-info" style = "height: 100px">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Align Items - End</h2>
<div class = "d-flex align-items-end bg-info" style = "height: 100px">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Align Items - Center</h2>
<div class = "d-flex align-items-center bg-info" style = "height: 100px">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Align Items - Baseline</h2>
<div class = "d-flex align-items-baseline bg-info" style = "height: 100px">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
<h2>Align Items - Stretch</h2>
<div class = "d-flex align-items-stretch bg-info" style = "height: 100px">
<div class = "p-2 border border-dark">Item 1</div>
<div class = "p-2 border border-dark">Item 2</div>
<div class = "p-2 border border-dark">Item 3</div>
</div>
<br>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The elements can be displayed into an equal widths on horizontal space by using .flex-fill class. The flex item will grow, if there is available space by using .flex-grow-* class and flex item will shrink, if necessary by using .flex-shrink-* class.
The following example demonstrates usage of above utilities −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Fill</h2>
<div class = "d-flex bg-info">
<div class = "p-2 flex-fill border border-dark">Item 1</div>
<div class = "p-2 flex-fill border border-dark">Item 2</div>
<div class = "p-2 flex-fill border border-dark">Item 3</div>
</div>
<br>
<h2>Grow</h2>
<div class = "d-flex bg-info">
<div class = "p-2 flex-grow-1 bg-info">Item 1 (Using class flex-grow-1)</div>
<div class = "p-2 bg-warning">Item 2</div>
<div class = "p-2 bg-secondary">Item 3</div>
</div>
<br>
<h2>Shrink</h2>
<div class = "d-flex bg-info">
<div class = "p-2 w-100 bg-info">Item 1</div>
<div class = "p-2 flex-shrink-1 bg-warning">Item 2 (Using class flex-shrink-1)</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The flex utility provides auto margin feature on the flex items by using the .mr-auto (pushes items to the right) and .ml-auto (pushes items to the left) classes. The flex items can be moved to top or bottom by using mt-auto or mb-auto classes on a container.
The following example demonstrates usage of above classes −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Auto Margins</h2>
<div class = "d-flex bg-info mb-3">
<div class = "p-2 bg-warning">Item 1</div>
<div class = "p-2 bg-primary">Item 2</div>
<div class = "p-2 bg-secondary">Item 3</div>
</div>
<div class = "d-flex bg-info mb-3">
<div class = "mr-auto p-2 bg-warning">mr-auto: Item 1</div>
<div class = "p-2 bg-primary">Item 2</div>
<div class = "p-2 bg-secondary">Item 3</div>
</div>
<div class = "d-flex bg-info mb-3">
<div class = "p-2 bg-secondary">Item 1</div>
<div class = "p-2 bg-primary">Item 2</div>
<div class = "ml-auto p-2 bg-warning">ml-auto: Item 3</div>
</div>
<h2>With align-items</h2>
<div class = "d-flex align-items-start flex-column bg-info mb-3"
style = "height: 200px;">
<div class = "mb-auto p-2 bg-warning">mb-auto: Item 1</div>
<div class = "p-2 bg-primary">Item 2</div>
<div class = "p-2 bg-secondary">Item 3</div>
</div>
<div class = "d-flex align-items-end flex-column bg-info mb-3"
style = "height: 200px;">
<div class = "p-2 bg-secondary">Item 1</div>
<div class = "p-2 bg-primary">Item 2</div>
<div class = "mt-auto p-2 bg-warning">mt-auto: Item 3</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
The flex uses order utilities to change the order of flex items in a container as shown in the following example −
<html>
<head>
<!-- Meta tags -->
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>Flex Items Order</h2>
<div class = "d-flex flex-nowrap bg-info">
<div class = "order-3 p-2 bg-secondary">'order-3': Item 1</div>
<div class = "order-1 p-2 bg-primary">'order-1': Item 2</div>
<div class = "order-2 p-2 bg-warning">'order-2': Item 3</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
You can align (such as start, end, center, between and around) the flex items on the cross axis on the container by using align-content utility.
The following example demonstrates this −
<html>
<head>
<!-- Meta tags -->
<meta charset="utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
<!-- Bootstrap CSS -->
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Bootstrap 4 Example</title>
</head>
<body>
<div class = "container">
<h2>align-content-start</h2>
<div class = "d-flex bg-info align-content-start flex-wrap" style = "height: 150px">
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
</div>
<br>
<h2>align-content-end</h2>
<div class = "d-flex bg-info align-content-end flex-wrap" style = "height: 150px">
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
</div>
<br>
<h2>align-content-center</h2>
<div class = "d-flex bg-info align-content-center flex-wrap" style = "height: 150px">
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
</div>
<br>
<h2>align-content-between</h2>
<div class = "d-flex bg-info align-content-between flex-wrap" style = "height: 150px">
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
</div>
<br>
<h2>align-content-around</h2>
<div class = "d-flex bg-info align-content-around flex-wrap" style = "height: 150px">
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
<div class = "p-2 border border-dark">Demo Item</div>
</div>
<br>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin = "anonymous">
</script>
<!-- Popper -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin = "anonymous">
</script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin = "anonymous">
</script>
</body>
</html>
It will produce the following result −
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2010,
"s": 1816,
"text": "Flex utility can be used to manage the layout, alignment, grid columns, navigation and other components of the page. It makes easy to design layout structure without using float or positioning."
},
{
"code": null,
"e": 2482,
"s": 2010,
"text": "Use the flexbox display utilities like d-flex and d-inline-flex to display the flexbox container and children elements into flex items. You can set the direction of flex items in horizontal direction and vertical direction by using .flex-row (use .flex-row-reverse to display horizontal direction from the opposite side) and .flex-column (use .flex-column-reverse to display vertical direction from the opposite side) classes respectively as shown in the below example −"
},
{
"code": null,
"e": 5531,
"s": 2482,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Flex Behaviors</h2>\n <div class = \"d-flex p-2 bg-info\">\n This is flex container, uses the 'd-flex' class\n </div>\n <br>\n \n <div class = \"d-inline-flex p-2 bg-info\">\n This is inline flexbox container, uses the 'd-inline-flex' class\n </div>\n <br>\n <br>\n\n <h2>Direction</h2>\n <h4>Horizontal Direction</h4>\n <div class = \"d-flex flex-row bg-info mb-3\">\n <div class = \"p-2 border border-dark \">flex-row: Item 1</div>\n <div class = \"p-2 border border-dark\">flex-row: Item 2</div>\n <div class = \"p-2 border border-dark\">flex-row: Item 3</div>\n </div>\n <div class = \"d-flex flex-row-reverse bg-info\">\n <div class = \"p-2 border border-dark\">flex-row-reverse: Item 1</div>\n <div class = \"p-2 border border-dark\">flex-row-reverse: Item 2</div>\n <div class = \"p-2 border border-dark\">flex-row-reverse: Item 3</div>\n </div>\n <br>\n\n <h4>Vertical Direction</h4>\n <div class = \"d-flex flex-column bg-info mb-3\">\n <div class = \"p-2 border border-dark\">flex-column: Item 1</div>\n <div class = \"p-2 border border-dark\">flex-column: Item 2</div>\n <div class = \"p-2 border border-dark\">flex-column: Item 3</div>\n </div>\n <div class = \"d-flex flex-column-reverse bg-info\">\n <div class = \"p-2 border border-dark\">flex-column-reverse: Item 1</div>\n <div class = \"p-2 border border-dark\">flex-column-reverse: Item 2</div>\n <div class = \"p-2 border border-dark\">flex-column-reverse: Item 3</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 5570,
"s": 5531,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5757,
"s": 5570,
"text": "The alignment of flex items (such as start, end, center, between and around) can be changed on the main axis (x-axis to start) of the flexbox containers by using justify-content utility."
},
{
"code": null,
"e": 5799,
"s": 5757,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 8762,
"s": 5799,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Alignment - Start</h2>\n <div class = \"d-flex justify-content-start bg-info\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Alignment - End</h2>\n <div class = \"d-flex justify-content-end bg-info\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Alignment - Center</h2>\n <div class = \"d-flex justify-content-center bg-info\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Alignment - Between</h2>\n <div class = \"d-flex justify-content-between bg-info\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Alignment - Around</h2>\n <div class = \"d-flex justify-content-around bg-info\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8801,
"s": 8762,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 8987,
"s": 8801,
"text": "The alignment of flex items (such as start, end, center, baseline and stretch) can be changed on the cross axis (y-axis to start) of the flexbox containers by using align-items utility."
},
{
"code": null,
"e": 9029,
"s": 8987,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 12117,
"s": 9029,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Align Items - Start</h2>\n <div class = \"d-flex align-items-start bg-info\" style = \"height: 100px\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Align Items - End</h2>\n <div class = \"d-flex align-items-end bg-info\" style = \"height: 100px\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Align Items - Center</h2>\n <div class = \"d-flex align-items-center bg-info\" style = \"height: 100px\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Align Items - Baseline</h2>\n <div class = \"d-flex align-items-baseline bg-info\" style = \"height: 100px\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Align Items - Stretch</h2>\n <div class = \"d-flex align-items-stretch bg-info\" style = \"height: 100px\">\n <div class = \"p-2 border border-dark\">Item 1</div>\n <div class = \"p-2 border border-dark\">Item 2</div>\n <div class = \"p-2 border border-dark\">Item 3</div>\n </div>\n <br>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 12156,
"s": 12117,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 12406,
"s": 12156,
"text": "The elements can be displayed into an equal widths on horizontal space by using .flex-fill class. The flex item will grow, if there is available space by using .flex-grow-* class and flex item will shrink, if necessary by using .flex-shrink-* class."
},
{
"code": null,
"e": 12468,
"s": 12406,
"text": "The following example demonstrates usage of above utilities −"
},
{
"code": null,
"e": 14676,
"s": 12468,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Fill</h2>\n <div class = \"d-flex bg-info\">\n <div class = \"p-2 flex-fill border border-dark\">Item 1</div>\n <div class = \"p-2 flex-fill border border-dark\">Item 2</div>\n <div class = \"p-2 flex-fill border border-dark\">Item 3</div>\n </div>\n <br>\n \n <h2>Grow</h2>\n <div class = \"d-flex bg-info\">\n <div class = \"p-2 flex-grow-1 bg-info\">Item 1 (Using class flex-grow-1)</div>\n <div class = \"p-2 bg-warning\">Item 2</div>\n <div class = \"p-2 bg-secondary\">Item 3</div>\n </div>\n <br>\n \n <h2>Shrink</h2>\n <div class = \"d-flex bg-info\">\n <div class = \"p-2 w-100 bg-info\">Item 1</div>\n <div class = \"p-2 flex-shrink-1 bg-warning\">Item 2 (Using class flex-shrink-1)</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 14715,
"s": 14676,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 14975,
"s": 14715,
"text": "The flex utility provides auto margin feature on the flex items by using the .mr-auto (pushes items to the right) and .ml-auto (pushes items to the left) classes. The flex items can be moved to top or bottom by using mt-auto or mb-auto classes on a container."
},
{
"code": null,
"e": 15035,
"s": 14975,
"text": "The following example demonstrates usage of above classes −"
},
{
"code": null,
"e": 17811,
"s": 15035,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Auto Margins</h2>\n <div class = \"d-flex bg-info mb-3\">\n <div class = \"p-2 bg-warning\">Item 1</div>\n <div class = \"p-2 bg-primary\">Item 2</div>\n <div class = \"p-2 bg-secondary\">Item 3</div>\n </div>\n <div class = \"d-flex bg-info mb-3\">\n <div class = \"mr-auto p-2 bg-warning\">mr-auto: Item 1</div>\n <div class = \"p-2 bg-primary\">Item 2</div>\n <div class = \"p-2 bg-secondary\">Item 3</div>\n </div>\n <div class = \"d-flex bg-info mb-3\">\n <div class = \"p-2 bg-secondary\">Item 1</div>\n <div class = \"p-2 bg-primary\">Item 2</div>\n <div class = \"ml-auto p-2 bg-warning\">ml-auto: Item 3</div>\n </div>\n \n <h2>With align-items</h2>\n <div class = \"d-flex align-items-start flex-column bg-info mb-3\" \n style = \"height: 200px;\">\n \n <div class = \"mb-auto p-2 bg-warning\">mb-auto: Item 1</div>\n <div class = \"p-2 bg-primary\">Item 2</div>\n <div class = \"p-2 bg-secondary\">Item 3</div>\n </div>\n <div class = \"d-flex align-items-end flex-column bg-info mb-3\" \n style = \"height: 200px;\">\n <div class = \"p-2 bg-secondary\">Item 1</div>\n <div class = \"p-2 bg-primary\">Item 2</div>\n <div class = \"mt-auto p-2 bg-warning\">mt-auto: Item 3</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 17850,
"s": 17811,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 17965,
"s": 17850,
"text": "The flex uses order utilities to change the order of flex items in a container as shown in the following example −"
},
{
"code": null,
"e": 19637,
"s": 17965,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Flex Items Order</h2>\n <div class = \"d-flex flex-nowrap bg-info\">\n <div class = \"order-3 p-2 bg-secondary\">'order-3': Item 1</div>\n <div class = \"order-1 p-2 bg-primary\">'order-1': Item 2</div>\n <div class = \"order-2 p-2 bg-warning\">'order-2': Item 3</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 19676,
"s": 19637,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 19822,
"s": 19676,
"text": "You can align (such as start, end, center, between and around) the flex items on the cross axis on the container by using align-content utility. "
},
{
"code": null,
"e": 19864,
"s": 19822,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 27011,
"s": 19864,
"text": "<html>\n <head>\n <!-- Meta tags -->\n <meta charset=\"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>align-content-start</h2>\n <div class = \"d-flex bg-info align-content-start flex-wrap\" style = \"height: 150px\">\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n </div>\n <br>\n \n <h2>align-content-end</h2>\n <div class = \"d-flex bg-info align-content-end flex-wrap\" style = \"height: 150px\">\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n </div>\n <br>\n \n <h2>align-content-center</h2>\n <div class = \"d-flex bg-info align-content-center flex-wrap\" style = \"height: 150px\">\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n </div>\n <br>\n \n <h2>align-content-between</h2>\n <div class = \"d-flex bg-info align-content-between flex-wrap\" style = \"height: 150px\">\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n </div>\n <br>\n \n <h2>align-content-around</h2>\n <div class = \"d-flex bg-info align-content-around flex-wrap\" style = \"height: 150px\">\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n <div class = \"p-2 border border-dark\">Demo Item</div>\n </div>\n <br>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Popper -->\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n </script>\n \n <!-- Latest compiled and minified Bootstrap JavaScript -->\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 27050,
"s": 27011,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 27083,
"s": 27050,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 27097,
"s": 27083,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 27132,
"s": 27097,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 27149,
"s": 27132,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 27186,
"s": 27149,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 27214,
"s": 27186,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 27247,
"s": 27214,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 27259,
"s": 27247,
"text": " Azaz Patel"
},
{
"code": null,
"e": 27294,
"s": 27259,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 27311,
"s": 27294,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 27344,
"s": 27311,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 27364,
"s": 27344,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 27371,
"s": 27364,
"text": " Print"
},
{
"code": null,
"e": 27382,
"s": 27371,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.