title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
JavaScript Course | Printing Hello World in JavaScript | 03 Jan, 2022
Previous article: JavaScript Course | What is JavaScript?
Whenever we write javascript we make use of the ‘script’ tag. We know what a normal HTML document is made up of. The ‘script’ tag is used to write javascript code and this ‘script’ tag is either placed inside the ‘head’ tag or inside the ‘body’ tag.
Example:
HTML
<!DOCTYPE HTML><html><head> <title></title> <!-- Script tag can also be placed here --></head><body> <p>Before the script...</p> <!-- Script tag inside the body --> <script> // write the javascript code inside it </script> <p>...After the script.</p> </body></html>
We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be noted that each choice of putting the ‘script’ tag has its own consequences. For now, you can put the script tag anywhere you want.
Printing Hello World In order to print the famous ‘Hello World’ sentence to the screen, we can make use of different methods that javascript provides. Most common are:
console.log()
document.write()
alert()
Each of the above method have different ways of outputting the content. Though ‘document.write()’ is used when we want to print the content onto the document which is the HTML Document. Also ‘console.log()’ is mainly used when we are debugging javascript code and same thing with ‘alert()’.
Example:
Javascript
<script>// using console.logconsole.log('Hello World');</script>
Hit Ctrl+Shift+J to see the output in the browser console.
Output:
Example:
Javascript
<script>// using document.writedocument.write('Hello World');</script>
Output:
Hello World
Example:
Javascript
<script>// using alertalert('Hello World');</script>
Output:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Next article: JavaScript Course | Understanding Code Structure in JavaScript
surinderdawra388
ysachin2314
JavaScript-Course
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
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
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": 52,
"s": 24,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 111,
"s": 52,
"text": "Previous article: JavaScript Course | What is JavaScript? "
},
{
"code": null,
"e": 362,
"s": 111,
"text": "Whenever we write javascript we make use of the ‘script’ tag. We know what a normal HTML document is made up of. The ‘script’ tag is used to write javascript code and this ‘script’ tag is either placed inside the ‘head’ tag or inside the ‘body’ tag. "
},
{
"code": null,
"e": 372,
"s": 362,
"text": "Example: "
},
{
"code": null,
"e": 377,
"s": 372,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html><head> <title></title> <!-- Script tag can also be placed here --></head><body> <p>Before the script...</p> <!-- Script tag inside the body --> <script> // write the javascript code inside it </script> <p>...After the script.</p> </body></html>",
"e": 674,
"s": 377,
"text": null
},
{
"code": null,
"e": 885,
"s": 674,
"text": "We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be noted that each choice of putting the ‘script’ tag has its own consequences. For now, you can put the script tag anywhere you want."
},
{
"code": null,
"e": 1054,
"s": 885,
"text": "Printing Hello World In order to print the famous ‘Hello World’ sentence to the screen, we can make use of different methods that javascript provides. Most common are: "
},
{
"code": null,
"e": 1068,
"s": 1054,
"text": "console.log()"
},
{
"code": null,
"e": 1085,
"s": 1068,
"text": "document.write()"
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "alert()"
},
{
"code": null,
"e": 1384,
"s": 1093,
"text": "Each of the above method have different ways of outputting the content. Though ‘document.write()’ is used when we want to print the content onto the document which is the HTML Document. Also ‘console.log()’ is mainly used when we are debugging javascript code and same thing with ‘alert()’."
},
{
"code": null,
"e": 1395,
"s": 1384,
"text": "Example: "
},
{
"code": null,
"e": 1406,
"s": 1395,
"text": "Javascript"
},
{
"code": "<script>// using console.logconsole.log('Hello World');</script>",
"e": 1471,
"s": 1406,
"text": null
},
{
"code": null,
"e": 1531,
"s": 1471,
"text": "Hit Ctrl+Shift+J to see the output in the browser console. "
},
{
"code": null,
"e": 1540,
"s": 1531,
"text": "Output: "
},
{
"code": null,
"e": 1550,
"s": 1540,
"text": "Example: "
},
{
"code": null,
"e": 1561,
"s": 1550,
"text": "Javascript"
},
{
"code": "<script>// using document.writedocument.write('Hello World');</script>",
"e": 1632,
"s": 1561,
"text": null
},
{
"code": null,
"e": 1641,
"s": 1632,
"text": "Output: "
},
{
"code": null,
"e": 1653,
"s": 1641,
"text": "Hello World"
},
{
"code": null,
"e": 1663,
"s": 1653,
"text": "Example: "
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": "Javascript"
},
{
"code": "<script>// using alertalert('Hello World');</script>",
"e": 1727,
"s": 1674,
"text": null
},
{
"code": null,
"e": 1736,
"s": 1727,
"text": "Output: "
},
{
"code": null,
"e": 1755,
"s": 1736,
"text": "Supported Browser:"
},
{
"code": null,
"e": 1769,
"s": 1755,
"text": "Google Chrome"
},
{
"code": null,
"e": 1784,
"s": 1769,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 1792,
"s": 1784,
"text": "Firefox"
},
{
"code": null,
"e": 1798,
"s": 1792,
"text": "Opera"
},
{
"code": null,
"e": 1805,
"s": 1798,
"text": "Safari"
},
{
"code": null,
"e": 1883,
"s": 1805,
"text": "Next article: JavaScript Course | Understanding Code Structure in JavaScript "
},
{
"code": null,
"e": 1900,
"s": 1883,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1912,
"s": 1900,
"text": "ysachin2314"
},
{
"code": null,
"e": 1930,
"s": 1912,
"text": "JavaScript-Course"
},
{
"code": null,
"e": 1941,
"s": 1930,
"text": "JavaScript"
},
{
"code": null,
"e": 1958,
"s": 1941,
"text": "Web Technologies"
},
{
"code": null,
"e": 2056,
"s": 1958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2117,
"s": 2056,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2189,
"s": 2117,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2229,
"s": 2189,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2281,
"s": 2229,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2322,
"s": 2281,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2384,
"s": 2322,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2417,
"s": 2384,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2478,
"s": 2417,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2528,
"s": 2478,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Java Program to Determine the Unicode Code Point at Given Index in String | 21 Apr, 2022
ASCII is a code that converts the English alphabets to numerics as numeric can convert to the assembly language which our computer understands. For that, we have assigned a number against each character ranging from 0 to 127. Alphabets are case-sensitive lowercase and uppercase are treated differently. Complete ASCII values table can be interpreted but better it is sticking to the table in the illustration below where no need arises to lean complete ASCII values in a table. Extremities are assigned as follows so as order to guess the Unicode value correctly with memorizing the complete table. With this table, one can extract all alphabets Unicode be it uppercase or lowercase.
illustration:
From this, one can get Unicode of other values such as B is 66 because lowercase starting is a for which is illustrated from the above table, its 65. For ‘b’ it’s 98. Similarly, for Unicode of ‘G’ is 71, ‘E’ is 69, ‘K’ is 75, and so on.
codePointAt() inbuilt method is used where the user wants to return the character at the specific index. The index refers to character values (Unicode units) and ranges from 0 to length()-1
Definition: This is an inbuilt function that Returns the character(Unicode point) at the specific index. The index refers to character values (Unicode units) and ranges from 0 to length()-1.
Syntax:
java.lang.String.codePointAt();
Parameter: The index to the character values.
Return Type: This method returns the Unicode value at the specified index. The index refers to char values (Unicode code units) and ranges from 0 to [length()-1]. Simply in layman language, the code point value of the character at the index.
Implementation: There are two examples being discussed for clear understanding considering both the cases where there is the involvement of exception with this function and another one simply depicting the internal use of the function.
Example 1: In this edge case of exception handling is not taken into consideration which above method do throws.
Java
// Importing Files and Classesimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Considering random string for input String str = "GEEKS"; // Unicode at index 0 // Input is a small string int result_1 = str.codePointAt(0); int result_2 = str.codePointAt(1); int result_3 = str.codePointAt(2); int result_4 = str.codePointAt(3); int result_5 = str.codePointAt(4); // Printing the input string System.out.println("Original String : " + str); // Prints unicode character at index 0 to 4 // in above input string // to show usage of codePointAt() System.out.println("unicode point at 0 = " + result_1); System.out.println("unicode point at 1 = " + result_2); System.out.println("unicode point at 2 = " + result_3); System.out.println("unicode point at 3 = " + result_4); System.out.println("unicode point at 4 = " + result_5); }}
Output:
Original String : GEEKS
unicode point at 0 = 71
unicode point at 1 = 69
unicode point at 2 = 69
unicode point at 3 = 75
unicode point at 4 = 83
Time Complexity O(n) of the above code.
Now considering the exception concept here in play, the exception is simply a problem that arises during runtime disrupting the normal flow of the program. They can be of two types checked exceptions and unchecked exceptions. Checked can be detected by our compiler where unchecked exceptions can not be detected by the compiler. For this sake, exception handling techniques in java to deal with the same. Now dealing with the exception in the function. Sometimes an exception is thrown when an index that is beyond memory is being tried to access. Below are the conceptual details about the exceptions in codePointAt() method. Likewise, discussing IndexOutOfbound exception downside and in order to deal with it try-catch technique.
Example 2: IndexOutOfBoundsException is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range is as follows. Below is the example to illustrate codeAtPoint() where the exception is thrown.
Java
import java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Try block to check exceptions try { // Input string String str = "Geeksforgeeks"; // unicode at index 0 // Storing it in integer variable int result_1 = str.codePointAt(0); // unicode at index 4 int result_2 = str.codePointAt(-4); // Printing input/original string System.out.println("Original String : " + str); // Prints unicode character at index 1 in string System.out.println("Character(unicode point) = " + result_1); // Prints unicode character at index 4 in string System.out.println("Character(unicode point) = " + result_2); } // Catch block to handle exception catch (IndexOutOfBoundsException e) { // Message printed if exception occurs System.out.println("Exception thrown :" + e); } }}
Exception thrown :java.lang.StringIndexOutOfBoundsException: index -4,length 13
GaneshNethula
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 713,
"s": 28,
"text": "ASCII is a code that converts the English alphabets to numerics as numeric can convert to the assembly language which our computer understands. For that, we have assigned a number against each character ranging from 0 to 127. Alphabets are case-sensitive lowercase and uppercase are treated differently. Complete ASCII values table can be interpreted but better it is sticking to the table in the illustration below where no need arises to lean complete ASCII values in a table. Extremities are assigned as follows so as order to guess the Unicode value correctly with memorizing the complete table. With this table, one can extract all alphabets Unicode be it uppercase or lowercase."
},
{
"code": null,
"e": 727,
"s": 713,
"text": "illustration:"
},
{
"code": null,
"e": 964,
"s": 727,
"text": "From this, one can get Unicode of other values such as B is 66 because lowercase starting is a for which is illustrated from the above table, its 65. For ‘b’ it’s 98. Similarly, for Unicode of ‘G’ is 71, ‘E’ is 69, ‘K’ is 75, and so on."
},
{
"code": null,
"e": 1155,
"s": 964,
"text": "codePointAt() inbuilt method is used where the user wants to return the character at the specific index. The index refers to character values (Unicode units) and ranges from 0 to length()-1"
},
{
"code": null,
"e": 1346,
"s": 1155,
"text": "Definition: This is an inbuilt function that Returns the character(Unicode point) at the specific index. The index refers to character values (Unicode units) and ranges from 0 to length()-1."
},
{
"code": null,
"e": 1354,
"s": 1346,
"text": "Syntax:"
},
{
"code": null,
"e": 1386,
"s": 1354,
"text": "java.lang.String.codePointAt();"
},
{
"code": null,
"e": 1432,
"s": 1386,
"text": "Parameter: The index to the character values."
},
{
"code": null,
"e": 1674,
"s": 1432,
"text": "Return Type: This method returns the Unicode value at the specified index. The index refers to char values (Unicode code units) and ranges from 0 to [length()-1]. Simply in layman language, the code point value of the character at the index."
},
{
"code": null,
"e": 1910,
"s": 1674,
"text": "Implementation: There are two examples being discussed for clear understanding considering both the cases where there is the involvement of exception with this function and another one simply depicting the internal use of the function."
},
{
"code": null,
"e": 2023,
"s": 1910,
"text": "Example 1: In this edge case of exception handling is not taken into consideration which above method do throws."
},
{
"code": null,
"e": 2028,
"s": 2023,
"text": "Java"
},
{
"code": "// Importing Files and Classesimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Considering random string for input String str = \"GEEKS\"; // Unicode at index 0 // Input is a small string int result_1 = str.codePointAt(0); int result_2 = str.codePointAt(1); int result_3 = str.codePointAt(2); int result_4 = str.codePointAt(3); int result_5 = str.codePointAt(4); // Printing the input string System.out.println(\"Original String : \" + str); // Prints unicode character at index 0 to 4 // in above input string // to show usage of codePointAt() System.out.println(\"unicode point at 0 = \" + result_1); System.out.println(\"unicode point at 1 = \" + result_2); System.out.println(\"unicode point at 2 = \" + result_3); System.out.println(\"unicode point at 3 = \" + result_4); System.out.println(\"unicode point at 4 = \" + result_5); }}",
"e": 3178,
"s": 2028,
"text": null
},
{
"code": null,
"e": 3186,
"s": 3178,
"text": "Output:"
},
{
"code": null,
"e": 3330,
"s": 3186,
"text": "Original String : GEEKS\nunicode point at 0 = 71\nunicode point at 1 = 69\nunicode point at 2 = 69\nunicode point at 3 = 75\nunicode point at 4 = 83"
},
{
"code": null,
"e": 3370,
"s": 3330,
"text": "Time Complexity O(n) of the above code."
},
{
"code": null,
"e": 4104,
"s": 3370,
"text": "Now considering the exception concept here in play, the exception is simply a problem that arises during runtime disrupting the normal flow of the program. They can be of two types checked exceptions and unchecked exceptions. Checked can be detected by our compiler where unchecked exceptions can not be detected by the compiler. For this sake, exception handling techniques in java to deal with the same. Now dealing with the exception in the function. Sometimes an exception is thrown when an index that is beyond memory is being tried to access. Below are the conceptual details about the exceptions in codePointAt() method. Likewise, discussing IndexOutOfbound exception downside and in order to deal with it try-catch technique."
},
{
"code": null,
"e": 4352,
"s": 4104,
"text": "Example 2: IndexOutOfBoundsException is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range is as follows. Below is the example to illustrate codeAtPoint() where the exception is thrown."
},
{
"code": null,
"e": 4357,
"s": 4352,
"text": "Java"
},
{
"code": "import java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Try block to check exceptions try { // Input string String str = \"Geeksforgeeks\"; // unicode at index 0 // Storing it in integer variable int result_1 = str.codePointAt(0); // unicode at index 4 int result_2 = str.codePointAt(-4); // Printing input/original string System.out.println(\"Original String : \" + str); // Prints unicode character at index 1 in string System.out.println(\"Character(unicode point) = \" + result_1); // Prints unicode character at index 4 in string System.out.println(\"Character(unicode point) = \" + result_2); } // Catch block to handle exception catch (IndexOutOfBoundsException e) { // Message printed if exception occurs System.out.println(\"Exception thrown :\" + e); } }}",
"e": 5443,
"s": 4357,
"text": null
},
{
"code": null,
"e": 5527,
"s": 5446,
"text": "Exception thrown :java.lang.StringIndexOutOfBoundsException: index -4,length 13"
},
{
"code": null,
"e": 5543,
"s": 5529,
"text": "GaneshNethula"
},
{
"code": null,
"e": 5564,
"s": 5543,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 5569,
"s": 5564,
"text": "Java"
},
{
"code": null,
"e": 5583,
"s": 5569,
"text": "Java Programs"
},
{
"code": null,
"e": 5588,
"s": 5583,
"text": "Java"
}
]
|
Python | Pandas dataframe.corrwith() | 16 May, 2020
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandasis one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.corrwith() is used to compute pairwise correlation between rows or columns of two DataFrame objects. If the shape of two dataframe object is not same then the corresponding correlation value will be a NaN value.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:other : DataFrameaxis : 0 or ‘index’ to compute column-wise, 1 or ‘columns’ for row-wisedrop : Drop missing indices from result, default returns union of all
Returns: correls : Series
Note: The correlation of a variable with itself is 1.
Example #1: Use corrwith() function to find the correlation among two dataframe objects along the column axis
# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({"A":[1, 5, 7, 8], "B":[5, 8, 4, 3], "C":[10, 4, 9, 3]}) # Creating the second dataframe df2 = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5]}) # Print the first dataframeprint(df1, "\n") # Print the second dataframeprint(df2)
Now find the correlation among the columns of the two data frames along the row axis.
# To find the correlation among the# columns of df1 and df2 along the column axisdf1.corrwith(df2, axis = 0)
Output :The output series contains the correlation between the three columns of two dataframe objects respectively. Example #2: Use corrwith() function to find the correlation among two dataframe objects along the row axis
# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({"A":[1, 5, 7, 8], "B":[5, 8, 4, 3], "C":[10, 4, 9, 3]}) # Creating the second dataframe df2 = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5]}) # To find the correlation among the# columns of df1 and df2 along the row axisdf1.corrwith(df2, axis = 1)
Output :
The output series contains the correlation between the four rows of two data frame objects respectively.
jaikishan6
AtharvaShirode
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
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2020"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandasis one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 470,
"s": 241,
"text": "Pandas dataframe.corrwith() is used to compute pairwise correlation between rows or columns of two DataFrame objects. If the shape of two dataframe object is not same then the corresponding correlation value will be a NaN value."
},
{
"code": null,
"e": 534,
"s": 470,
"text": "Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)"
},
{
"code": null,
"e": 703,
"s": 534,
"text": "Parameters:other : DataFrameaxis : 0 or ‘index’ to compute column-wise, 1 or ‘columns’ for row-wisedrop : Drop missing indices from result, default returns union of all"
},
{
"code": null,
"e": 729,
"s": 703,
"text": "Returns: correls : Series"
},
{
"code": null,
"e": 783,
"s": 729,
"text": "Note: The correlation of a variable with itself is 1."
},
{
"code": null,
"e": 893,
"s": 783,
"text": "Example #1: Use corrwith() function to find the correlation among two dataframe objects along the column axis"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({\"A\":[1, 5, 7, 8], \"B\":[5, 8, 4, 3], \"C\":[10, 4, 9, 3]}) # Creating the second dataframe df2 = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5]}) # Print the first dataframeprint(df1, \"\\n\") # Print the second dataframeprint(df2)",
"e": 1315,
"s": 893,
"text": null
},
{
"code": null,
"e": 1401,
"s": 1315,
"text": "Now find the correlation among the columns of the two data frames along the row axis."
},
{
"code": "# To find the correlation among the# columns of df1 and df2 along the column axisdf1.corrwith(df2, axis = 0)",
"e": 1510,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1510,
"text": "Output :The output series contains the correlation between the three columns of two dataframe objects respectively. Example #2: Use corrwith() function to find the correlation among two dataframe objects along the row axis"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({\"A\":[1, 5, 7, 8], \"B\":[5, 8, 4, 3], \"C\":[10, 4, 9, 3]}) # Creating the second dataframe df2 = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5]}) # To find the correlation among the# columns of df1 and df2 along the row axisdf1.corrwith(df2, axis = 1)",
"e": 2177,
"s": 1733,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2177,
"text": "Output :"
},
{
"code": null,
"e": 2291,
"s": 2186,
"text": "The output series contains the correlation between the four rows of two data frame objects respectively."
},
{
"code": null,
"e": 2302,
"s": 2291,
"text": "jaikishan6"
},
{
"code": null,
"e": 2317,
"s": 2302,
"text": "AtharvaShirode"
},
{
"code": null,
"e": 2341,
"s": 2317,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2373,
"s": 2341,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2387,
"s": 2373,
"text": "Python-pandas"
},
{
"code": null,
"e": 2394,
"s": 2387,
"text": "Python"
},
{
"code": null,
"e": 2492,
"s": 2394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2510,
"s": 2492,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2552,
"s": 2510,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2574,
"s": 2552,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2609,
"s": 2574,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2635,
"s": 2609,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2667,
"s": 2635,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2696,
"s": 2667,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2723,
"s": 2696,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2753,
"s": 2723,
"text": "Iterate over a list in Python"
}
]
|
Sorting 2D Vector of Pairs in C++ | 12 Jul, 2022
A 2D vector also known as vector of vectors is a vector in which each element is a vector on its own. In other words, It is a matrix implemented with the help of vectors.
What is a 2D vector of pairs?
A 2D vector of pairs is a vector in which each element is a vector of pairs on its own. In other words, It is a matrix implemented with the help of vectors of pairs.
Example: Below is the C++ program to implement a 2D vector of pairs.
C++
// C++ program to demonstrate the// working of vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > >& myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; vector<pair<int, int> > vect2 = {{9, 10}, {11, 12}, {13, 14}, {15, 16}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); print(myContainer); return 0;}
This article focuses on discussing different techniques used to sort a 2D vector of pairs.
Case 1: To sort a particular row of a 2D vector:
On the basis of the first values of pairs: This type of sorting arranges a selected row of a 2D vector in ascending order of the first value of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output:(1, 9) (4, 1) (7, 2) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Below is the implementation of the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << "Before sorting, "; print(myContainer); // Sorting the first row of 2D vector // of pairs on the basis of first // element of pairs sort(myContainer[0].begin(), myContainer[0].end()); cout << "\n\n After sorting the first row " << "on the basis of first element of pairs, "; print(myContainer); return 0;}
On the basis of the second value of pairs: This type of sorting arranges a selected row of a 2D vector in ascending order of the second value of the pair. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort on the basis of the second value of pairs.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output:(4, 1) (7, 2) (1, 9) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Below is the implementation of the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.second < pair2.second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << "Before sorting, "; print(myContainer); // Sorting first row of 2D vector of pairs // on the basis of second element of pairs // By passing a custom comparator as a // third argument sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << "\n\n After sorting the first row on " << "the basis of second element of pairs, "; print(myContainer); return 0;}
Case 2: To sort the entire 2D vector on basis of a particular column:
On the basis of the first values of pairs: In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest first value of pairs of the second column becomes the first row, the second smallest first value of pairs in the second column becomes the second row, and so on.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output:(4, 1) (1, 9) (7, 2) (1, 6) (3, 2) (1, 4) (3, 2) (4, 5) (8, 1)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].first < vector2[1].first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << "Before sorting, "; print(myContainer); // Sorting 2D vector of pairs on the basis // of first element of pairs of the second // column by passing a custom comparator // as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector on the " << "basis of first element of pairs of the second column, "; print(myContainer); return 0;}
On the basis of the second values of pairs: In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest second value of pairs of the second column becomes the first row, the second smallest second value of pairs in the second column becomes the second row, and so on.
For example, sorting the entire 2D vector on the basis of the second value of pairs of the second column would result into,
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output: (1, 6) (3, 2) (1, 4) (3, 2) (4, 5) (8, 1) (4, 1) (1, 9) (7, 2)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].second < vector2[1].second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << "Before sorting, "; print(myContainer); // Sorting 2D vector of pairs on the basis of // first element of pairs of the second column // By passing a custom comparator as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector on " << "the basis of first element of pairs of " << "the second column, "; print(myContainer); return 0;}
Case 3: To sort a particular row of a 2D vector of pairs in descending order
On the basis of the first values of pairs: This type of sorting arranges a selected row of a 2D vector in descending order by the first element of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort on the basis of the first element of pairs.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output:(7, 2) (4, 1) (1, 9) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.first > pair2.first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << "Before sorting, "; print(myContainer); // Sorting the first row of 2D vector // of pairs in descending order // of the first element of pairs sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << "\n\n After sorting the first row " << "in descending order of the first " << "element of pairs, "; print(myContainer); return 0;}
On the basis of the second values of pairs: This type of sorting arranges a selected row of a 2D vector in descending order by the second element of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the second element of pairs.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1) (1, 6) (3, 2) (1, 4)
Output:(1, 9) (7, 2) (4, 1) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.second > pair2.second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << "Before sorting, "; print(myContainer); // Sorting first row of 2D vector of pairs // in descending order of second element of pairs // By passing a custom comparator as a third argument sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << "\n\n After sorting the first row " << "in descending order of second element " << "of pairs, "; print(myContainer); return 0;}
Case 4: To sort the entire 2D vector on basis of a particular column in descending order:
On the basis of the first values of pairs: In this type of sorting, the 2D vector is entirely sorted on basis of the first value of pairs of the chosen column in descending order. For example, if the chosen column is second, the row with the greatest value of the first element of pairs in the second column becomes the first row, the second greatest value of the second element of pairs in the second column becomes the second row, and so on. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the first element of pairs.
Example:
Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)
Output:(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) (4, 1) (1, 9) (7, 2)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].first > vector2[1].first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << "Before sorting, "; print(myContainer); // Sorting 2D vector of pairs in descending // order of the first element of pairs of // the second column by passing a custom // comparator as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector in " << "descending order of the first element " << "of pairs of the second column, "; print(myContainer); return 0;}
On the basis of the second values of pairs: In this type of sorting, the 2D vector is entirely sorted on basis of the second element of pairs of the chosen column in descending order. For example, if the chosen column is second, the row with the greatest value of the second element of pairs in the second column becomes the first row, the second greatest value of the second element of pairs in the second column becomes the second row, and so on. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the second element of pairs.
Example:
Input:(4, 1) (1, 9) (7, 2) (3, 2) (4, 2) (8, 1) (1, 6) (3, 5) (1, 4)
Output:(4, 1) (1, 9) (7, 2) (1, 6) (3, 5) (1, 4) (3, 2) (4, 2) (8, 1)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].second > vector2[1].second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << "Before sorting, "; print(myContainer); // Sorting 2D vector of pairs in descending // order of second element of pairs of the // second column by passing a custom comparator // as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector " << "in descending order of second element " << "of pairs of the second column, "; print(myContainer); return 0;}
Case 5: Sorting a 2D Vector of pairs on the basis of the number of columns in a row in ascending order:
In this type of sorting, a 2D vector of pairs is sorted on basis of a number of the column in ascending order. This is achieved by passing a third argument, a custom comparator function to the “sort()” method.
Example:
Input:(4, 1) (1, 9) (7, 2)(8, 11)(1, 6) (3, 2)
Output:(8, 11) (1, 6) (3, 2)(4, 1) (1, 9) (7, 2)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting a 2D vector or// vector of vectors of pairs in// descending order of number of// columns in a row#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1.size() < vector2.size();} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}, {16, 18}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; vector<pair<int, int> > vect5 = {{7, 2}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); myContainer.push_back(vect5); // Print the vector elements // before sorting cout << "Before sorting, "; print(myContainer); // Sorting the 2D vector of pairs // in ascending order // of number of columns in a row sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector " << "in ascending order of the number of " << "columns in a row, "; print(myContainer); return 0;}
Case 6: Sorting a 2D Vector of pairs on basis of the number of columns in a row in descending order:
In this type of sorting, a 2D vector is sorted on basis of the number of columns in descending order. This is achieved by passing a third argument, a custom comparator to the “sort()” method.
Example:
Input:(4, 1) (1, 9) (7, 2)(8, 11)(1, 6) (3, 2)
Output:(4, 1) (1, 9) (7, 2)(1, 6) (3, 2)(8, 11)
Below is the C++ program to implement the above approach:
C++
// C++ program to demonstrate the// working of sorting a 2D vector or// vector of vectors of pairs in// descending order of number of// columns in a row #include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1.size() > vector2.size();} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << "[ "; for (auto pr : myVector) { // Print the element cout << "{"; cout << pr.first << ", " << pr.second; cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}, {16, 18}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; vector<pair<int, int> > vect5 = {{7, 2}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); myContainer.push_back(vect5); // Print the vector elements // before sorting cout << "Before sorting, "; print(myContainer); // Sorting the first row of 2D // vector of pairs in descending // order of the first element of pairs sort(myContainer.begin(), myContainer.end(), myComparator); cout << "\n\n After sorting the 2D vector " << "in descending order of the number " << "of columns in a row, "; print(myContainer); return 0;}
surinderdawra388
simmytarika5
cpp-pair
cpp-vector
STL
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 199,
"s": 28,
"text": "A 2D vector also known as vector of vectors is a vector in which each element is a vector on its own. In other words, It is a matrix implemented with the help of vectors."
},
{
"code": null,
"e": 229,
"s": 199,
"text": "What is a 2D vector of pairs?"
},
{
"code": null,
"e": 395,
"s": 229,
"text": "A 2D vector of pairs is a vector in which each element is a vector of pairs on its own. In other words, It is a matrix implemented with the help of vectors of pairs."
},
{
"code": null,
"e": 464,
"s": 395,
"text": "Example: Below is the C++ program to implement a 2D vector of pairs."
},
{
"code": null,
"e": 468,
"s": 464,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > >& myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; vector<pair<int, int> > vect2 = {{9, 10}, {11, 12}, {13, 14}, {15, 16}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); print(myContainer); return 0;}",
"e": 1948,
"s": 468,
"text": null
},
{
"code": null,
"e": 2039,
"s": 1948,
"text": "This article focuses on discussing different techniques used to sort a 2D vector of pairs."
},
{
"code": null,
"e": 2088,
"s": 2039,
"text": "Case 1: To sort a particular row of a 2D vector:"
},
{
"code": null,
"e": 2328,
"s": 2088,
"text": " On the basis of the first values of pairs: This type of sorting arranges a selected row of a 2D vector in ascending order of the first value of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments."
},
{
"code": null,
"e": 2337,
"s": 2328,
"text": "Example:"
},
{
"code": null,
"e": 2437,
"s": 2337,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 2519,
"s": 2437,
"text": "Output:(1, 9) (4, 1) (7, 2) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)"
},
{
"code": null,
"e": 2570,
"s": 2519,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2574,
"s": 2570,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting the first row of 2D vector // of pairs on the basis of first // element of pairs sort(myContainer[0].begin(), myContainer[0].end()); cout << \"\\n\\n After sorting the first row \" << \"on the basis of first element of pairs, \"; print(myContainer); return 0;}",
"e": 4449,
"s": 2574,
"text": null
},
{
"code": null,
"e": 4847,
"s": 4449,
"text": "On the basis of the second value of pairs: This type of sorting arranges a selected row of a 2D vector in ascending order of the second value of the pair. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort on the basis of the second value of pairs."
},
{
"code": null,
"e": 4856,
"s": 4847,
"text": "Example:"
},
{
"code": null,
"e": 4956,
"s": 4856,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 5038,
"s": 4956,
"text": "Output:(4, 1) (7, 2) (1, 9) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)"
},
{
"code": null,
"e": 5090,
"s": 5038,
"text": " Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5094,
"s": 5090,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.second < pair2.second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting first row of 2D vector of pairs // on the basis of second element of pairs // By passing a custom comparator as a // third argument sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << \"\\n\\n After sorting the first row on \" << \"the basis of second element of pairs, \"; print(myContainer); return 0;}",
"e": 7183,
"s": 5094,
"text": null
},
{
"code": null,
"e": 7253,
"s": 7183,
"text": "Case 2: To sort the entire 2D vector on basis of a particular column:"
},
{
"code": null,
"e": 7611,
"s": 7253,
"text": "On the basis of the first values of pairs: In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest first value of pairs of the second column becomes the first row, the second smallest first value of pairs in the second column becomes the second row, and so on."
},
{
"code": null,
"e": 7620,
"s": 7611,
"text": "Example:"
},
{
"code": null,
"e": 7720,
"s": 7620,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 7808,
"s": 7720,
"text": "Output:(4, 1) (1, 9) (7, 2) (1, 6) (3, 2) (1, 4) (3, 2) (4, 5) (8, 1) "
},
{
"code": null,
"e": 7866,
"s": 7808,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 7870,
"s": 7866,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].first < vector2[1].first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting 2D vector of pairs on the basis // of first element of pairs of the second // column by passing a custom comparator // as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector on the \" << \"basis of first element of pairs of the second column, \"; print(myContainer); return 0;}",
"e": 9999,
"s": 7870,
"text": null
},
{
"code": null,
"e": 10361,
"s": 9999,
"text": " On the basis of the second values of pairs: In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest second value of pairs of the second column becomes the first row, the second smallest second value of pairs in the second column becomes the second row, and so on."
},
{
"code": null,
"e": 10485,
"s": 10361,
"text": "For example, sorting the entire 2D vector on the basis of the second value of pairs of the second column would result into,"
},
{
"code": null,
"e": 10586,
"s": 10485,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 10672,
"s": 10586,
"text": "Output: (1, 6) (3, 2) (1, 4) (3, 2) (4, 5) (8, 1) (4, 1) (1, 9) (7, 2) "
},
{
"code": null,
"e": 10730,
"s": 10672,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 10734,
"s": 10730,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].second < vector2[1].second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting 2D vector of pairs on the basis of // first element of pairs of the second column // By passing a custom comparator as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector on \" << \"the basis of first element of pairs of \" << \"the second column, \"; print(myContainer); return 0;}",
"e": 12870,
"s": 10734,
"text": null
},
{
"code": null,
"e": 12947,
"s": 12870,
"text": "Case 3: To sort a particular row of a 2D vector of pairs in descending order"
},
{
"code": null,
"e": 13345,
"s": 12947,
"text": "On the basis of the first values of pairs: This type of sorting arranges a selected row of a 2D vector in descending order by the first element of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort on the basis of the first element of pairs."
},
{
"code": null,
"e": 13354,
"s": 13345,
"text": "Example:"
},
{
"code": null,
"e": 13454,
"s": 13354,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 13536,
"s": 13454,
"text": "Output:(7, 2) (4, 1) (1, 9) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)"
},
{
"code": null,
"e": 13594,
"s": 13536,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 13598,
"s": 13594,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.first > pair2.first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements // before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting the first row of 2D vector // of pairs in descending order // of the first element of pairs sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << \"\\n\\n After sorting the first row \" << \"in descending order of the first \" << \"element of pairs, \"; print(myContainer); return 0;}",
"e": 15695,
"s": 13598,
"text": null
},
{
"code": null,
"e": 16116,
"s": 15695,
"text": "On the basis of the second values of pairs: This type of sorting arranges a selected row of a 2D vector in descending order by the second element of pairs. This is achieved by using “sort()” and passing iterators of 1D vector as its arguments. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the second element of pairs."
},
{
"code": null,
"e": 16125,
"s": 16116,
"text": "Example:"
},
{
"code": null,
"e": 16239,
"s": 16125,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1) (1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 16321,
"s": 16239,
"text": "Output:(1, 9) (7, 2) (4, 1) (3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4)"
},
{
"code": null,
"e": 16379,
"s": 16321,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 16383,
"s": 16379,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(pair<int, int>& pair1, pair<int, int>& pair2){ return pair1.second > pair2.second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {1, 9}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}, {21, 22}, {23, 24}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting first row of 2D vector of pairs // in descending order of second element of pairs // By passing a custom comparator as a third argument sort(myContainer[0].begin(), myContainer[0].end(), myComparator); cout << \"\\n\\n After sorting the first row \" << \"in descending order of second element \" << \"of pairs, \"; print(myContainer); return 0;}",
"e": 18510,
"s": 16383,
"text": null
},
{
"code": null,
"e": 18600,
"s": 18510,
"text": "Case 4: To sort the entire 2D vector on basis of a particular column in descending order:"
},
{
"code": null,
"e": 19220,
"s": 18600,
"text": "On the basis of the first values of pairs: In this type of sorting, the 2D vector is entirely sorted on basis of the first value of pairs of the chosen column in descending order. For example, if the chosen column is second, the row with the greatest value of the first element of pairs in the second column becomes the first row, the second greatest value of the second element of pairs in the second column becomes the second row, and so on. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the first element of pairs."
},
{
"code": null,
"e": 19229,
"s": 19220,
"text": "Example:"
},
{
"code": null,
"e": 19330,
"s": 19229,
"text": "Input:(4, 1) (1, 9) (7, 2)(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) "
},
{
"code": null,
"e": 19412,
"s": 19330,
"text": "Output:(3, 2) (4, 5) (8, 1)(1, 6) (3, 2) (1, 4) (4, 1) (1, 9) (7, 2)"
},
{
"code": null,
"e": 19470,
"s": 19412,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 19474,
"s": 19470,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].first > vector2[1].first;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting 2D vector of pairs in descending // order of the first element of pairs of // the second column by passing a custom // comparator as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector in \" << \"descending order of the first element \" << \"of pairs of the second column, \"; print(myContainer); return 0;}",
"e": 21656,
"s": 19474,
"text": null
},
{
"code": null,
"e": 22282,
"s": 21656,
"text": "On the basis of the second values of pairs: In this type of sorting, the 2D vector is entirely sorted on basis of the second element of pairs of the chosen column in descending order. For example, if the chosen column is second, the row with the greatest value of the second element of pairs in the second column becomes the first row, the second greatest value of the second element of pairs in the second column becomes the second row, and so on. In this case, there is a need to pass a custom comparator as a third argument that implements the logic to sort in descending order on the basis of the second element of pairs."
},
{
"code": null,
"e": 22291,
"s": 22282,
"text": "Example:"
},
{
"code": null,
"e": 22419,
"s": 22291,
"text": "Input:(4, 1) (1, 9) (7, 2) (3, 2) (4, 2) (8, 1) (1, 6) (3, 5) (1, 4) "
},
{
"code": null,
"e": 22511,
"s": 22419,
"text": "Output:(4, 1) (1, 9) (7, 2) (1, 6) (3, 5) (1, 4) (3, 2) (4, 2) (8, 1) "
},
{
"code": null,
"e": 22569,
"s": 22511,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 22573,
"s": 22569,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting vector of vectors// of pairs in descending order#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1[1].second > vector2[1].second;} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{3, 5}, {10, 3}, {2, 1}, {3, 8}}; vector<pair<int, int> > vect2 = {{1, 6}, {9, 1}, {2, 5}, {1, 5}}; vector<pair<int, int> > vect3 = {{1, 5}, {2, 5}, {12, 12}, {1, 4}}; vector<pair<int, int> > vect4 = {{5, 2}, {1, 52}, {9, 3}, {3, 32}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Print the vector elements before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting 2D vector of pairs in descending // order of second element of pairs of the // second column by passing a custom comparator // as a third argument sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector \" << \"in descending order of second element \" << \"of pairs of the second column, \"; print(myContainer); return 0;}",
"e": 24751,
"s": 22573,
"text": null
},
{
"code": null,
"e": 24855,
"s": 24751,
"text": "Case 5: Sorting a 2D Vector of pairs on the basis of the number of columns in a row in ascending order:"
},
{
"code": null,
"e": 25065,
"s": 24855,
"text": "In this type of sorting, a 2D vector of pairs is sorted on basis of a number of the column in ascending order. This is achieved by passing a third argument, a custom comparator function to the “sort()” method."
},
{
"code": null,
"e": 25074,
"s": 25065,
"text": "Example:"
},
{
"code": null,
"e": 25148,
"s": 25074,
"text": "Input:(4, 1) (1, 9) (7, 2)(8, 11)(1, 6) (3, 2) "
},
{
"code": null,
"e": 25202,
"s": 25148,
"text": "Output:(8, 11) (1, 6) (3, 2)(4, 1) (1, 9) (7, 2)"
},
{
"code": null,
"e": 25260,
"s": 25202,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 25264,
"s": 25260,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting a 2D vector or// vector of vectors of pairs in// descending order of number of// columns in a row#include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1.size() < vector2.size();} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}, {16, 18}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; vector<pair<int, int> > vect5 = {{7, 2}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); myContainer.push_back(vect5); // Print the vector elements // before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting the 2D vector of pairs // in ascending order // of number of columns in a row sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector \" << \"in ascending order of the number of \" << \"columns in a row, \"; print(myContainer); return 0;}",
"e": 27484,
"s": 25264,
"text": null
},
{
"code": null,
"e": 27585,
"s": 27484,
"text": "Case 6: Sorting a 2D Vector of pairs on basis of the number of columns in a row in descending order:"
},
{
"code": null,
"e": 27777,
"s": 27585,
"text": "In this type of sorting, a 2D vector is sorted on basis of the number of columns in descending order. This is achieved by passing a third argument, a custom comparator to the “sort()” method."
},
{
"code": null,
"e": 27786,
"s": 27777,
"text": "Example:"
},
{
"code": null,
"e": 27870,
"s": 27786,
"text": "Input:(4, 1) (1, 9) (7, 2)(8, 11)(1, 6) (3, 2) "
},
{
"code": null,
"e": 27925,
"s": 27870,
"text": "Output:(4, 1) (1, 9) (7, 2)(1, 6) (3, 2)(8, 11) "
},
{
"code": null,
"e": 27983,
"s": 27925,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 27987,
"s": 27983,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// working of sorting a 2D vector or// vector of vectors of pairs in// descending order of number of// columns in a row #include <bits/stdc++.h>using namespace std; // Custom comparator functionbool myComparator(vector<pair<int, int> >& vector1, vector<pair<int, int> >& vector2){ return vector1.size() > vector2.size();} // Function to print 2D vector elementsvoid print(vector<vector<pair<int, int> > > & myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector is // a vector itself vector<pair<int, int> > myVector = currentVector; // Iterating over the vector // elements cout << \"[ \"; for (auto pr : myVector) { // Print the element cout << \"{\"; cout << pr.first << \", \" << pr.second; cout << \"} \"; } cout << \"]\\n\"; }} // Driver codeint main(){ // Declaring a 2D vector of pairs // Pairs are of type {char, bool} vector<vector<pair<int, int> > > myContainer; // Initializing vectors of pairs vector<pair<int, int> > vect1 = {{2, 1}, {4, 3}, {8, 1}}; vector<pair<int, int> > vect2 = {{19, 10}, {11, 2}, {12, 14}, {14, 6}, {16, 18}}; vector<pair<int, int> > vect3 = {{17, 18}, {19, 20}}; vector<pair<int, int> > vect4 = {{25, 26}, {27, 28}, {29, 30}, {31, 32}}; vector<pair<int, int> > vect5 = {{7, 2}}; // Inserting vectors in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); myContainer.push_back(vect5); // Print the vector elements // before sorting cout << \"Before sorting, \"; print(myContainer); // Sorting the first row of 2D // vector of pairs in descending // order of the first element of pairs sort(myContainer.begin(), myContainer.end(), myComparator); cout << \"\\n\\n After sorting the 2D vector \" << \"in descending order of the number \" << \"of columns in a row, \"; print(myContainer); return 0;}",
"e": 30221,
"s": 27987,
"text": null
},
{
"code": null,
"e": 30238,
"s": 30221,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30251,
"s": 30238,
"text": "simmytarika5"
},
{
"code": null,
"e": 30260,
"s": 30251,
"text": "cpp-pair"
},
{
"code": null,
"e": 30271,
"s": 30260,
"text": "cpp-vector"
},
{
"code": null,
"e": 30275,
"s": 30271,
"text": "STL"
},
{
"code": null,
"e": 30279,
"s": 30275,
"text": "C++"
},
{
"code": null,
"e": 30287,
"s": 30279,
"text": "Sorting"
},
{
"code": null,
"e": 30295,
"s": 30287,
"text": "Sorting"
},
{
"code": null,
"e": 30299,
"s": 30295,
"text": "STL"
},
{
"code": null,
"e": 30303,
"s": 30299,
"text": "CPP"
}
]
|
How to add/remove values in the array in PowerShell? | An array is always a fixed size. To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator.
For example, you have an existing array as given below.
$array = 1,2,3,4,5
To add value “Hello” to the array, we will use += sign.
$array += "Hello"
Now, we will check the output of the array.
We have another method to add value to the array. By Add() operation of the array.
$array.Add("Hi")
When you use the above method to add a variable in the given array, you will get below error.
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $array.Add("Hi")
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
This is because the array size is fixed. You can check if the array is a fixed size or not by using the below method.
$array.IsfixedSize
When you check the type of this array, it is an object, not the list.
To deal with the above problem, we need to use System.Collection.ArrayList instead.
When you check the type of this array, it will be an array list.
So from the array list, we can add or remove items.
$array.Add("Hello")
$array.Remove("Delta") | [
{
"code": null,
"e": 1232,
"s": 1062,
"text": "An array is always a fixed size. To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator."
},
{
"code": null,
"e": 1288,
"s": 1232,
"text": "For example, you have an existing array as given below."
},
{
"code": null,
"e": 1307,
"s": 1288,
"text": "$array = 1,2,3,4,5"
},
{
"code": null,
"e": 1363,
"s": 1307,
"text": "To add value “Hello” to the array, we will use += sign."
},
{
"code": null,
"e": 1381,
"s": 1363,
"text": "$array += \"Hello\""
},
{
"code": null,
"e": 1425,
"s": 1381,
"text": "Now, we will check the output of the array."
},
{
"code": null,
"e": 1508,
"s": 1425,
"text": "We have another method to add value to the array. By Add() operation of the array."
},
{
"code": null,
"e": 1525,
"s": 1508,
"text": "$array.Add(\"Hi\")"
},
{
"code": null,
"e": 1619,
"s": 1525,
"text": "When you use the above method to add a variable in the given array, you will get below error."
},
{
"code": null,
"e": 1864,
"s": 1619,
"text": "Exception calling \"Add\" with \"1\" argument(s): \"Collection was of a fixed size.\"\nAt line:1 char:1\n+ $array.Add(\"Hi\")\n+ ~~~~~~~~~~~~\n+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException\n+ FullyQualifiedErrorId : NotSupportedException\n"
},
{
"code": null,
"e": 1982,
"s": 1864,
"text": "This is because the array size is fixed. You can check if the array is a fixed size or not by using the below method."
},
{
"code": null,
"e": 2001,
"s": 1982,
"text": "$array.IsfixedSize"
},
{
"code": null,
"e": 2071,
"s": 2001,
"text": "When you check the type of this array, it is an object, not the list."
},
{
"code": null,
"e": 2155,
"s": 2071,
"text": "To deal with the above problem, we need to use System.Collection.ArrayList instead."
},
{
"code": null,
"e": 2220,
"s": 2155,
"text": "When you check the type of this array, it will be an array list."
},
{
"code": null,
"e": 2272,
"s": 2220,
"text": "So from the array list, we can add or remove items."
},
{
"code": null,
"e": 2292,
"s": 2272,
"text": "$array.Add(\"Hello\")"
},
{
"code": null,
"e": 2315,
"s": 2292,
"text": "$array.Remove(\"Delta\")"
}
]
|
Const member functions in C++ - GeeksforGeeks | 27 Mar, 2021
Like member functions and member function arguments, the objects of a class can also be declared as const. an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object. A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. Syntax:
const Class_Name Object_name;
When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
Whenever an object is declared as const, it needs to be initialized at the time of declaration. however, the object initialization while declaring is possible only with the help of constructors.
A function becomes const when the const keyword is used in the function’s declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.Following is a simple example of a const function.
CPP
#include <iostream>using namespace std; class Test { int value; public: Test(int v = 0) { value = v; } int getValue() const { return value; }}; int main(){ Test t(20); cout << t.getValue(); return 0;}
Output:
20
When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects. For example the following program has compiler errors.
CPP
#include<iostream>using namespace std; class Test { int value;public: Test(int v = 0) {value = v;} int getValue() {return value;}}; int main() { const Test t; cout << t.getValue(); return 0;}
Output:
passing 'const Test' as 'this' argument of 'int
Test::getValue()' discards qualifiers
Let’s look at another example:
CPP
// Demonstration of constant object,// show that constant object can only// call const member function#include<iostream>using namespace std;class Demo{ int value; public: Demo(int v = 0) {value = v;} void showMessage() { cout<<"Hello World We are Tushar, " "Ramswarup, Nilesh and Subhash Inside" " showMessage() Function"<<endl; } void display()const { cout<<"Hello world I'm Rancho " "Baba Inside display() Function"<<endl; }};int main(){ //Constant object are initialised at the time of declaration using constructor const Demo d1; //d1.showMessage();Error occurred if uncomment. d1.display(); return(0);}
OUTPUT : Hello world I'm Rancho Baba Inside display() Function
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ramswarup_kulhary
shubhra28
sangameshmath99
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Classes and Objects
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
rand() and srand() in C/C++
vector erase() and clear() in C++
unordered_map in C++ STL
Left Shift and Right Shift Operators in C/C++
C++ Data Types | [
{
"code": null,
"e": 23769,
"s": 23741,
"text": "\n27 Mar, 2021"
},
{
"code": null,
"e": 24210,
"s": 23769,
"text": "Like member functions and member function arguments, the objects of a class can also be declared as const. an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object. A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. Syntax: "
},
{
"code": null,
"e": 24241,
"s": 24210,
"text": "const Class_Name Object_name; "
},
{
"code": null,
"e": 24362,
"s": 24241,
"text": "When a function is declared as const, it can be called on any type of object, const object as well as non-const objects."
},
{
"code": null,
"e": 24557,
"s": 24362,
"text": "Whenever an object is declared as const, it needs to be initialized at the time of declaration. however, the object initialization while declaring is possible only with the help of constructors."
},
{
"code": null,
"e": 24917,
"s": 24557,
"text": "A function becomes const when the const keyword is used in the function’s declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.Following is a simple example of a const function. "
},
{
"code": null,
"e": 24921,
"s": 24917,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; class Test { int value; public: Test(int v = 0) { value = v; } int getValue() const { return value; }}; int main(){ Test t(20); cout << t.getValue(); return 0;}",
"e": 25141,
"s": 24921,
"text": null
},
{
"code": null,
"e": 25150,
"s": 25141,
"text": "Output: "
},
{
"code": null,
"e": 25153,
"s": 25150,
"text": "20"
},
{
"code": null,
"e": 25349,
"s": 25153,
"text": "When a function is declared as const, it can be called on any type of object. Non-const functions can only be called by non-const objects. For example the following program has compiler errors. "
},
{
"code": null,
"e": 25353,
"s": 25349,
"text": "CPP"
},
{
"code": "#include<iostream>using namespace std; class Test { int value;public: Test(int v = 0) {value = v;} int getValue() {return value;}}; int main() { const Test t; cout << t.getValue(); return 0;}",
"e": 25563,
"s": 25353,
"text": null
},
{
"code": null,
"e": 25572,
"s": 25563,
"text": "Output: "
},
{
"code": null,
"e": 25660,
"s": 25572,
"text": " passing 'const Test' as 'this' argument of 'int \nTest::getValue()' discards qualifiers"
},
{
"code": null,
"e": 25693,
"s": 25660,
"text": "Let’s look at another example: "
},
{
"code": null,
"e": 25697,
"s": 25693,
"text": "CPP"
},
{
"code": "// Demonstration of constant object,// show that constant object can only// call const member function#include<iostream>using namespace std;class Demo{ int value; public: Demo(int v = 0) {value = v;} void showMessage() { cout<<\"Hello World We are Tushar, \" \"Ramswarup, Nilesh and Subhash Inside\" \" showMessage() Function\"<<endl; } void display()const { cout<<\"Hello world I'm Rancho \" \"Baba Inside display() Function\"<<endl; }};int main(){ //Constant object are initialised at the time of declaration using constructor const Demo d1; //d1.showMessage();Error occurred if uncomment. d1.display(); return(0);}",
"e": 26381,
"s": 25697,
"text": null
},
{
"code": null,
"e": 26444,
"s": 26381,
"text": "OUTPUT : Hello world I'm Rancho Baba Inside display() Function"
},
{
"code": null,
"e": 26569,
"s": 26444,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26587,
"s": 26569,
"text": "ramswarup_kulhary"
},
{
"code": null,
"e": 26597,
"s": 26587,
"text": "shubhra28"
},
{
"code": null,
"e": 26613,
"s": 26597,
"text": "sangameshmath99"
},
{
"code": null,
"e": 26627,
"s": 26613,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26631,
"s": 26627,
"text": "C++"
},
{
"code": null,
"e": 26635,
"s": 26631,
"text": "CPP"
},
{
"code": null,
"e": 26733,
"s": 26635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26742,
"s": 26733,
"text": "Comments"
},
{
"code": null,
"e": 26755,
"s": 26742,
"text": "Old Comments"
},
{
"code": null,
"e": 26779,
"s": 26755,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26807,
"s": 26779,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26835,
"s": 26807,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26870,
"s": 26835,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26901,
"s": 26870,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 26929,
"s": 26901,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26963,
"s": 26929,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 26988,
"s": 26963,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 27034,
"s": 26988,
"text": "Left Shift and Right Shift Operators in C/C++"
}
]
|
Difference Between Virtual and Pure Virtual Function | In this post, we will understand the difference between virtual and pure virtual functions.
It has its own definition inside the class.
It has its own definition inside the class.
The base class can override a virtual function.
The base class can override a virtual function.
It doesn’t have a derived class.
It doesn’t have a derived class.
virtual funct_name(parameter_list) {. . . . .};
It doesn’t have a definition.
It doesn’t have a definition.
If a class has at least one virtual function, it can be declared abstract.
If a class has at least one virtual function, it can be declared abstract.
The derived class has to override the pure virtual function to use it.
The derived class has to override the pure virtual function to use it.
A pure virtual function is specified by placing "= 0" in its declaration
A pure virtual function is specified by placing "= 0" in its declaration
virtual funct_name(parameter_list)=0;
Following is an example −
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}; | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "In this post, we will understand the difference between virtual and pure virtual functions."
},
{
"code": null,
"e": 1198,
"s": 1154,
"text": "It has its own definition inside the class."
},
{
"code": null,
"e": 1242,
"s": 1198,
"text": "It has its own definition inside the class."
},
{
"code": null,
"e": 1290,
"s": 1242,
"text": "The base class can override a virtual function."
},
{
"code": null,
"e": 1338,
"s": 1290,
"text": "The base class can override a virtual function."
},
{
"code": null,
"e": 1371,
"s": 1338,
"text": "It doesn’t have a derived class."
},
{
"code": null,
"e": 1404,
"s": 1371,
"text": "It doesn’t have a derived class."
},
{
"code": null,
"e": 1452,
"s": 1404,
"text": "virtual funct_name(parameter_list) {. . . . .};"
},
{
"code": null,
"e": 1482,
"s": 1452,
"text": "It doesn’t have a definition."
},
{
"code": null,
"e": 1512,
"s": 1482,
"text": "It doesn’t have a definition."
},
{
"code": null,
"e": 1587,
"s": 1512,
"text": "If a class has at least one virtual function, it can be declared abstract."
},
{
"code": null,
"e": 1662,
"s": 1587,
"text": "If a class has at least one virtual function, it can be declared abstract."
},
{
"code": null,
"e": 1733,
"s": 1662,
"text": "The derived class has to override the pure virtual function to use it."
},
{
"code": null,
"e": 1804,
"s": 1733,
"text": "The derived class has to override the pure virtual function to use it."
},
{
"code": null,
"e": 1877,
"s": 1804,
"text": "A pure virtual function is specified by placing \"= 0\" in its declaration"
},
{
"code": null,
"e": 1950,
"s": 1877,
"text": "A pure virtual function is specified by placing \"= 0\" in its declaration"
},
{
"code": null,
"e": 1988,
"s": 1950,
"text": "virtual funct_name(parameter_list)=0;"
},
{
"code": null,
"e": 2014,
"s": 1988,
"text": "Following is an example −"
},
{
"code": null,
"e": 2228,
"s": 2014,
"text": "class Box {\n public:\n // pure virtual function\n virtual double getVolume() = 0;\n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};"
}
]
|
Aptitude - Speed and Distance | Speed = Distance⁄Time
Time = Distance⁄Speed
P km/hr = (P x 5⁄18)m/sec
P m/sec = (P x 18⁄5)km/hr
If the ratio of the speeds of P and Q is p:q, then the ratio of the times taken by them to cover the same distance is
1⁄p:1⁄q or q : p
The average speed of the journey is
(2pq⁄p+q)km/hr
if a man covers a certain distance at p km/hr and an equal distance at q km/hr
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3989,
"s": 3892,
"text": "Speed = Distance⁄Time\nTime = Distance⁄Speed\nP km/hr = (P x 5⁄18)m/sec\nP m/sec = (P x 18⁄5)km/hr\n"
},
{
"code": null,
"e": 4107,
"s": 3989,
"text": "If the ratio of the speeds of P and Q is p:q, then the ratio of the times taken by them to cover the same distance is"
},
{
"code": null,
"e": 4125,
"s": 4107,
"text": "1⁄p:1⁄q or q : p\n"
},
{
"code": null,
"e": 4163,
"s": 4125,
"text": "The average speed of the journey is \n"
},
{
"code": null,
"e": 4179,
"s": 4163,
"text": "(2pq⁄p+q)km/hr\n"
},
{
"code": null,
"e": 4258,
"s": 4179,
"text": "if a man covers a certain distance at p km/hr and an equal distance at q km/hr"
},
{
"code": null,
"e": 4294,
"s": 4258,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4312,
"s": 4294,
"text": " Programming Line"
},
{
"code": null,
"e": 4319,
"s": 4312,
"text": " Print"
},
{
"code": null,
"e": 4330,
"s": 4319,
"text": " Add Notes"
}
]
|
Data Structure and Algorithms Binary Search | Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.
For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the process of binary search with a pictorial example. The following is our sorted array and let us assume that we need to search the location of value 31 using binary search.
First, we shall determine half of the array by using this formula −
mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted array, so we also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the value must be in the lower part from this location.
Hence, we calculate the mid again. This time it is 5.
We compare the value stored at location 5 with our target value. We find that it is a match.
We conclude that the target value 31 is stored at location 5.
Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less numbers.
The pseudocode of binary search algorithms should look like this −
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
To know about binary search implementation using array in C programming language, please click here.
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2814,
"s": 2580,
"text": "Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form."
},
{
"code": null,
"e": 3266,
"s": 2814,
"text": "Binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero."
},
{
"code": null,
"e": 3537,
"s": 3266,
"text": "For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the process of binary search with a pictorial example. The following is our sorted array and let us assume that we need to search the location of value 31 using binary search."
},
{
"code": null,
"e": 3605,
"s": 3537,
"text": "First, we shall determine half of the array by using this formula −"
},
{
"code": null,
"e": 3635,
"s": 3605,
"text": "mid = low + (high - low) / 2\n"
},
{
"code": null,
"e": 3723,
"s": 3635,
"text": "Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array."
},
{
"code": null,
"e": 4017,
"s": 3723,
"text": "Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted array, so we also know that the target value must be in the upper portion of the array."
},
{
"code": null,
"e": 4080,
"s": 4017,
"text": "We change our low to mid + 1 and find the new mid value again."
},
{
"code": null,
"e": 4124,
"s": 4080,
"text": "low = mid + 1\nmid = low + (high - low) / 2\n"
},
{
"code": null,
"e": 4214,
"s": 4124,
"text": "Our new mid is 7 now. We compare the value stored at location 7 with our target value 31."
},
{
"code": null,
"e": 4369,
"s": 4214,
"text": "The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the value must be in the lower part from this location."
},
{
"code": null,
"e": 4423,
"s": 4369,
"text": "Hence, we calculate the mid again. This time it is 5."
},
{
"code": null,
"e": 4516,
"s": 4423,
"text": "We compare the value stored at location 5 with our target value. We find that it is a match."
},
{
"code": null,
"e": 4578,
"s": 4516,
"text": "We conclude that the target value 31 is stored at location 5."
},
{
"code": null,
"e": 4695,
"s": 4578,
"text": "Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less numbers."
},
{
"code": null,
"e": 4762,
"s": 4695,
"text": "The pseudocode of binary search algorithms should look like this −"
},
{
"code": null,
"e": 5309,
"s": 4762,
"text": "Procedure binary_search\n A ← sorted array\n n ← size of array\n x ← value to be searched\n\n Set lowerBound = 1\n Set upperBound = n \n\n while x not found\n if upperBound < lowerBound \n EXIT: x does not exists.\n \n set midPoint = lowerBound + ( upperBound - lowerBound ) / 2\n \n if A[midPoint] < x\n set lowerBound = midPoint + 1\n \n if A[midPoint] > x\n set upperBound = midPoint - 1 \n\n if A[midPoint] = x \n EXIT: x found at location midPoint\n end while\n \nend procedure"
},
{
"code": null,
"e": 5410,
"s": 5309,
"text": "To know about binary search implementation using array in C programming language, please click here."
},
{
"code": null,
"e": 5445,
"s": 5410,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5457,
"s": 5445,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5492,
"s": 5457,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5511,
"s": 5492,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5546,
"s": 5511,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5561,
"s": 5546,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5594,
"s": 5561,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5613,
"s": 5594,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5647,
"s": 5613,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5675,
"s": 5647,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5711,
"s": 5675,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5739,
"s": 5711,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5746,
"s": 5739,
"text": " Print"
},
{
"code": null,
"e": 5757,
"s": 5746,
"text": " Add Notes"
}
]
|
Binary Search - GeeksforGeeks | 25 Mar, 2022
Problem: Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
Examples:
Input: arr[] = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170}, x = 110Output: 6Explanation: Element x is present at index 6
Input: arr[] = {10, 20, 30, 40, 60, 110, 120, 130, 170}, x = 175Output: -1Explanation: Element x is not present in arr[].
Linear Search Approach: A simple approach is to do a linear search. The time complexity of the Linear search is O(n). Another approach to perform the same task is using Binary Search.
Binary Search Approach:
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
Binary Search Algorithm: The basic steps to perform Binary Search are:
Begin with an interval covering the whole array.
If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
Otherwise, narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty.
Illustration of Binary Search Algorithm:
Example of Binary Search Algorithm
Step-by-step Binary Search Algorithm: We basically ignore half of the elements just after one comparison.
Compare x with the middle element.
If x matches with the middle element, we return the mid index.
Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
Else (x is smaller) recur for the left half.
Compare x with the middle element.
If x matches with the middle element, we return the mid index.
Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
Else (x is smaller) recur for the left half.
Recursive implementation of Binary Search:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to implement recursive Binary Search
#include <bits/stdc++.h>
using namespace std;
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
// C program to implement recursive Binary Search
#include <stdio.h>
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
// Java implementation of recursive Binary Search
class BinarySearch {
// Returns index of x if it is present in arr[l..
// r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
// Driver method to test above
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "
+ result);
}
}
/* This code is contributed by Rajat Mishra */
# Python3 Program for recursive binary search.
# Returns index of x in arr if present, else -1
def binarySearch(arr, l, r, x):
# Check base case
if r >= l:
mid = l + (r - l) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
# Else the element can only be present
# in right subarray
else:
return binarySearch(arr, mid + 1, r, x)
else:
# Element is not present in the array
return -1
# Driver Code
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")
// C# implementation of recursive Binary Search
using System;
class GFG {
// Returns index of x if it is present in
// arr[l..r], else return -1
static int binarySearch(int[] arr, int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
// Driver method to test above
public static void Main()
{
int[] arr = { 2, 3, 4, 10, 40 };
int n = arr.Length;
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
Console.WriteLine("Element not present");
else
Console.WriteLine("Element found at index "
+ result);
}
}
// This code is contributed by Sam007.
<?php
// PHP program to implement
// recursive Binary Search
// A recursive binary search
// function. It returns location
// of x in given array arr[l..r]
// is present, otherwise -1
function binarySearch($arr, $l, $r, $x)
{
if ($r >= $l)
{
$mid = ceil($l + ($r - $l) / 2);
// If the element is present
// at the middle itself
if ($arr[$mid] == $x)
return floor($mid);
// If element is smaller than
// mid, then it can only be
// present in left subarray
if ($arr[$mid] > $x)
return binarySearch($arr, $l,
$mid - 1, $x);
// Else the element can only
// be present in right subarray
return binarySearch($arr, $mid + 1,
$r, $x);
}
// We reach here when element
// is not present in array
return -1;
}
// Driver Code
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = binarySearch($arr, 0, $n - 1, $x);
if(($result == -1))
echo "Element is not present in array";
else
echo "Element is present at index ",
$result;
// This code is contributed by anuj_67.
?>
<script>
// JavaScript program to implement recursive Binary Search
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
function binarySearch(arr, l, r, x){
if (r >= l) {
let mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
let arr = [ 2, 3, 4, 10, 40 ];
let x = 10;
let n = arr.length
let result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? document.write( "Element is not present in array")
: document.write("Element is present at index " +result);
</script>
Element is present at index 3
Iterative implementation of Binary Search
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to implement iterative Binary Search
#include <bits/stdc++.h>
using namespace std;
// A iterative binary search function. It returns
// location of x in given array arr[l..r] if present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
// C program to implement iterative Binary Search
#include <stdio.h>
// A iterative binary search function. It returns
// location of x in given array arr[l..r] if present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present"
" in array")
: printf("Element is present at "
"index %d",
result);
return 0;
}
// Java implementation of iterative Binary Search
class BinarySearch {
// Returns index of x if it is present in arr[],
// else return -1
int binarySearch(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
// Driver method to test above
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at "
+ "index " + result);
}
}
# Python3 code to implement iterative Binary
# Search.
# It returns location of x in given array arr
# if present, else returns -1
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) // 2
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
# Driver Code
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")
// C# implementation of iterative Binary Search
using System;
class GFG {
// Returns index of x if it is present in arr[],
// else return -1
static int binarySearch(int[] arr, int x)
{
int l = 0, r = arr.Length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
// Driver method to test above
public static void Main()
{
int[] arr = { 2, 3, 4, 10, 40 };
int n = arr.Length;
int x = 10;
int result = binarySearch(arr, x);
if (result == -1)
Console.WriteLine("Element not present");
else
Console.WriteLine("Element found at "
+ "index " + result);
}
}
// This code is contributed by Sam007
<?php
// PHP program to implement
// iterative Binary Search
// A iterative binary search
// function. It returns location
// of x in given array arr[l..r]
// if present, otherwise -1
function binarySearch($arr, $l,
$r, $x)
{
while ($l <= $r)
{
$m = $l + ($r - $l) / 2;
// Check if x is present at mid
if ($arr[$m] == $x)
return floor($m);
// If x greater, ignore
// left half
if ($arr[$m] < $x)
$l = $m + 1;
// If x is smaller,
// ignore right half
else
$r = $m - 1;
}
// if we reach here, then
// element was not present
return -1;
}
// Driver Code
$arr = array(2, 3, 4, 10, 40);
$n = count($arr);
$x = 10;
$result = binarySearch($arr, 0,
$n - 1, $x);
if(($result == -1))
echo "Element is not present in array";
else
echo "Element is present at index ",
$result;
// This code is contributed by anuj_67.
?>
<script>
// Program to implement iterative Binary Search
// A iterative binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
function binarySearch(arr, x)
{
let l = 0;
let r = arr.length - 1;
let mid;
while (r >= l) {
mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
r = mid - 1;
// Else the element can only be present
// in right subarray
else
l = mid + 1;
}
// We reach here when element is not
// present in array
return -1;
}
arr =new Array(2, 3, 4, 10, 40);
x = 10;
n = arr.length;
result = binarySearch(arr, x);
(result == -1) ? document.write("Element is not present in array")
: document.write ("Element is present at index " + result);
// This code is contributed by simranarora5sos and rshuklabbb
</script>
Element is present at index 3
Algorithmic Paradigm: Decrease and Conquer.
Note: Here we are using
int mid = low + (high – low)/2;
Maybe, you wonder why we are calculating the middle index this way, we can simply add the lower and higher index and divide it by 2.
int mid = (low + high)/2;
But if we calculate the middle index like this means our code is not 100% correct, it contains bugs.
That is, it fails for larger values of int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value(231 – 1 ).
The sum overflows to a negative value and the value stays negative when divided by 2. In java, it throws ArrayIndexOutOfBoundException.
int mid = low + (high – low)/2;
So it’s better to use it like this. This bug applies equally to merge sort and other divide and conquer algorithms.
YouTubeGeeksforGeeks500K subscribersDSA Online (Binary Search) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=p9FZlPxukVI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
1. Language Foundation Courses [C++ / JAVA / Python ] Learn any programming language from scratch and understand all its fundamentals concepts for a strong programming foundation in the easiest possible manner with help of GeeksforGeeks Language Foundation Courses – Java Foundation | Python Foundation | C++ Foundation2. Geeks Classes Live Get interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session3. Complete Interview Preparation Get fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices.4. DSA Self Paced Start learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience.5. Company Specific Courses – Amazon, Microsoft, TCS & Wipro Crack the interview of any product-based giant company by specifically preparing with the questions that these companies usually ask in their coding interview round. Refer GeeksforGeeks Company Specific Courses: Amazon SDE Test Series, etc.
vt_m
RishabhPrabhu
DhruvJain6
pallav945
moraliser
rohitsingh07052
hritikrommie
simranarora5sos
kashishsoda
rshuklabbb
davidgatea21
sweetyty
Rajput-Ji
sagar0719kumar
kirankumarambati
Accenture
Binary Search
Infosys
Oracle
Qualcomm
SAP Labs
TCS
Wipro
Divide and Conquer
Searching
Infosys
Oracle
Wipro
SAP Labs
Qualcomm
TCS
Accenture
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Quick Sort vs Merge Sort
Closest Pair of Points using Divide and Conquer algorithm
Maximum Subarray Sum using Divide and Conquer algorithm
Find a peak element
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find the Missing Number
Program to find largest element in an array
k largest(or smallest) elements in an array
Given an array of size n and a number k, find all elements that appear more than n/k times | [
{
"code": null,
"e": 24031,
"s": 24000,
"text": " \n25 Mar, 2022\n"
},
{
"code": null,
"e": 24137,
"s": 24031,
"text": "Problem: Given a sorted array arr[] of n elements, write a function to search a given element x in arr[]."
},
{
"code": null,
"e": 24148,
"s": 24137,
"text": "Examples: "
},
{
"code": null,
"e": 24270,
"s": 24148,
"text": "Input: arr[] = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170}, x = 110Output: 6Explanation: Element x is present at index 6"
},
{
"code": null,
"e": 24392,
"s": 24270,
"text": "Input: arr[] = {10, 20, 30, 40, 60, 110, 120, 130, 170}, x = 175Output: -1Explanation: Element x is not present in arr[]."
},
{
"code": null,
"e": 24578,
"s": 24392,
"text": "Linear Search Approach: A simple approach is to do a linear search. The time complexity of the Linear search is O(n). Another approach to perform the same task is using Binary Search. "
},
{
"code": null,
"e": 24603,
"s": 24578,
"text": "Binary Search Approach: "
},
{
"code": null,
"e": 24839,
"s": 24603,
"text": "Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n). "
},
{
"code": null,
"e": 24910,
"s": 24839,
"text": "Binary Search Algorithm: The basic steps to perform Binary Search are:"
},
{
"code": null,
"e": 24959,
"s": 24910,
"text": "Begin with an interval covering the whole array."
},
{
"code": null,
"e": 25082,
"s": 24959,
"text": "If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half."
},
{
"code": null,
"e": 25122,
"s": 25082,
"text": "Otherwise, narrow it to the upper half."
},
{
"code": null,
"e": 25191,
"s": 25122,
"text": "Repeatedly check until the value is found or the interval is empty. "
},
{
"code": null,
"e": 25233,
"s": 25191,
"text": "Illustration of Binary Search Algorithm: "
},
{
"code": null,
"e": 25268,
"s": 25233,
"text": "Example of Binary Search Algorithm"
},
{
"code": null,
"e": 25374,
"s": 25268,
"text": "Step-by-step Binary Search Algorithm: We basically ignore half of the elements just after one comparison."
},
{
"code": null,
"e": 25664,
"s": 25374,
"text": "\nCompare x with the middle element.\nIf x matches with the middle element, we return the mid index.\nElse If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.\nElse (x is smaller) recur for the left half.\n"
},
{
"code": null,
"e": 25699,
"s": 25664,
"text": "Compare x with the middle element."
},
{
"code": null,
"e": 25762,
"s": 25699,
"text": "If x matches with the middle element, we return the mid index."
},
{
"code": null,
"e": 25907,
"s": 25762,
"text": "Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half."
},
{
"code": null,
"e": 25952,
"s": 25907,
"text": "Else (x is smaller) recur for the left half."
},
{
"code": null,
"e": 25995,
"s": 25952,
"text": "Recursive implementation of Binary Search:"
},
{
"code": null,
"e": 25999,
"s": 25995,
"text": "C++"
},
{
"code": null,
"e": 26001,
"s": 25999,
"text": "C"
},
{
"code": null,
"e": 26006,
"s": 26001,
"text": "Java"
},
{
"code": null,
"e": 26014,
"s": 26006,
"text": "Python3"
},
{
"code": null,
"e": 26017,
"s": 26014,
"text": "C#"
},
{
"code": null,
"e": 26021,
"s": 26017,
"text": "PHP"
},
{
"code": null,
"e": 26032,
"s": 26021,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to implement recursive Binary Search\n#include <bits/stdc++.h>\nusing namespace std;\n \n// A recursive binary search function. It returns\n// location of x in given array arr[l..r] is present,\n// otherwise -1\nint binarySearch(int arr[], int l, int r, int x)\n{\n if (r >= l) {\n int mid = l + (r - l) / 2;\n \n // If the element is present at the middle\n // itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n return binarySearch(arr, l, mid - 1, x);\n \n // Else the element can only be present\n // in right subarray\n return binarySearch(arr, mid + 1, r, x);\n }\n \n // We reach here when element is not\n // present in array\n return -1;\n}\n \nint main(void)\n{\n int arr[] = { 2, 3, 4, 10, 40 };\n int x = 10;\n int n = sizeof(arr) / sizeof(arr[0]);\n int result = binarySearch(arr, 0, n - 1, x);\n (result == -1)\n ? cout << \"Element is not present in array\"\n : cout << \"Element is present at index \" << result;\n return 0;\n}\n\n\n\n\n\n",
"e": 27209,
"s": 26042,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C program to implement recursive Binary Search\n#include <stdio.h>\n \n// A recursive binary search function. It returns\n// location of x in given array arr[l..r] is present,\n// otherwise -1\nint binarySearch(int arr[], int l, int r, int x)\n{\n if (r >= l) {\n int mid = l + (r - l) / 2;\n \n // If the element is present at the middle\n // itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n return binarySearch(arr, l, mid - 1, x);\n \n // Else the element can only be present\n // in right subarray\n return binarySearch(arr, mid + 1, r, x);\n }\n \n // We reach here when element is not\n // present in array\n return -1;\n}\n \nint main(void)\n{\n int arr[] = { 2, 3, 4, 10, 40 };\n int n = sizeof(arr) / sizeof(arr[0]);\n int x = 10;\n int result = binarySearch(arr, 0, n - 1, x);\n (result == -1)\n ? printf(\"Element is not present in array\")\n : printf(\"Element is present at index %d\", result);\n return 0;\n}\n\n\n\n\n\n",
"e": 28357,
"s": 27219,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java implementation of recursive Binary Search\nclass BinarySearch {\n // Returns index of x if it is present in arr[l..\n // r], else return -1\n int binarySearch(int arr[], int l, int r, int x)\n {\n if (r >= l) {\n int mid = l + (r - l) / 2;\n \n // If the element is present at the\n // middle itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n return binarySearch(arr, l, mid - 1, x);\n \n // Else the element can only be present\n // in right subarray\n return binarySearch(arr, mid + 1, r, x);\n }\n \n // We reach here when element is not present\n // in array\n return -1;\n }\n \n // Driver method to test above\n public static void main(String args[])\n {\n BinarySearch ob = new BinarySearch();\n int arr[] = { 2, 3, 4, 10, 40 };\n int n = arr.length;\n int x = 10;\n int result = ob.binarySearch(arr, 0, n - 1, x);\n if (result == -1)\n System.out.println(\"Element not present\");\n else\n System.out.println(\"Element found at index \"\n + result);\n }\n}\n/* This code is contributed by Rajat Mishra */\n\n\n\n\n\n",
"e": 29760,
"s": 28367,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 Program for recursive binary search.\n \n# Returns index of x in arr if present, else -1\n \n \ndef binarySearch(arr, l, r, x):\n \n # Check base case\n if r >= l:\n \n mid = l + (r - l) // 2\n \n # If element is present at the middle itself\n if arr[mid] == x:\n return mid\n \n # If element is smaller than mid, then it\n # can only be present in left subarray\n elif arr[mid] > x:\n return binarySearch(arr, l, mid-1, x)\n \n # Else the element can only be present\n # in right subarray\n else:\n return binarySearch(arr, mid + 1, r, x)\n \n else:\n # Element is not present in the array\n return -1\n \n \n# Driver Code\narr = [2, 3, 4, 10, 40]\nx = 10\n \n# Function call\nresult = binarySearch(arr, 0, len(arr)-1, x)\n \nif result != -1:\n print(\"Element is present at index % d\" % result)\nelse:\n print(\"Element is not present in array\")\n\n\n\n\n\n",
"e": 30723,
"s": 29770,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# implementation of recursive Binary Search\nusing System;\n \nclass GFG {\n // Returns index of x if it is present in\n // arr[l..r], else return -1\n static int binarySearch(int[] arr, int l, int r, int x)\n {\n if (r >= l) {\n int mid = l + (r - l) / 2;\n \n // If the element is present at the\n // middle itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n return binarySearch(arr, l, mid - 1, x);\n \n // Else the element can only be present\n // in right subarray\n return binarySearch(arr, mid + 1, r, x);\n }\n \n // We reach here when element is not present\n // in array\n return -1;\n }\n \n // Driver method to test above\n public static void Main()\n {\n \n int[] arr = { 2, 3, 4, 10, 40 };\n int n = arr.Length;\n int x = 10;\n \n int result = binarySearch(arr, 0, n - 1, x);\n \n if (result == -1)\n Console.WriteLine(\"Element not present\");\n else\n Console.WriteLine(\"Element found at index \"\n + result);\n }\n}\n \n// This code is contributed by Sam007.\n\n\n\n\n\n",
"e": 32072,
"s": 30733,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<?php\n// PHP program to implement\n// recursive Binary Search\n \n// A recursive binary search\n// function. It returns location\n// of x in given array arr[l..r] \n// is present, otherwise -1\nfunction binarySearch($arr, $l, $r, $x)\n{\nif ($r >= $l)\n{\n $mid = ceil($l + ($r - $l) / 2);\n \n // If the element is present \n // at the middle itself\n if ($arr[$mid] == $x) \n return floor($mid);\n \n // If element is smaller than \n // mid, then it can only be \n // present in left subarray\n if ($arr[$mid] > $x) \n return binarySearch($arr, $l, \n $mid - 1, $x);\n \n // Else the element can only \n // be present in right subarray\n return binarySearch($arr, $mid + 1, \n $r, $x);\n}\n \n// We reach here when element \n// is not present in array\nreturn -1;\n}\n \n// Driver Code\n$arr = array(2, 3, 4, 10, 40);\n$n = count($arr);\n$x = 10;\n$result = binarySearch($arr, 0, $n - 1, $x);\nif(($result == -1))\necho \"Element is not present in array\";\nelse\necho \"Element is present at index \",\n $result;\n \n// This code is contributed by anuj_67.\n?>\n\n\n\n\n\n",
"e": 33319,
"s": 32082,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n// JavaScript program to implement recursive Binary Search\n \n// A recursive binary search function. It returns\n// location of x in given array arr[l..r] is present,\n// otherwise -1\nfunction binarySearch(arr, l, r, x){\n if (r >= l) {\n let mid = l + Math.floor((r - l) / 2);\n \n // If the element is present at the middle\n // itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n return binarySearch(arr, l, mid - 1, x);\n \n // Else the element can only be present\n // in right subarray\n return binarySearch(arr, mid + 1, r, x);\n }\n \n // We reach here when element is not\n // present in array\n return -1;\n}\n \nlet arr = [ 2, 3, 4, 10, 40 ];\nlet x = 10;\nlet n = arr.length\nlet result = binarySearch(arr, 0, n - 1, x);\n(result == -1) ? document.write( \"Element is not present in array\")\n : document.write(\"Element is present at index \" +result);\n</script>\n\n\n\n\n\n",
"e": 34418,
"s": 33329,
"text": null
},
{
"code": null,
"e": 34451,
"s": 34421,
"text": "Element is present at index 3"
},
{
"code": null,
"e": 34495,
"s": 34451,
"text": "Iterative implementation of Binary Search "
},
{
"code": null,
"e": 34499,
"s": 34495,
"text": "C++"
},
{
"code": null,
"e": 34501,
"s": 34499,
"text": "C"
},
{
"code": null,
"e": 34506,
"s": 34501,
"text": "Java"
},
{
"code": null,
"e": 34514,
"s": 34506,
"text": "Python3"
},
{
"code": null,
"e": 34517,
"s": 34514,
"text": "C#"
},
{
"code": null,
"e": 34521,
"s": 34517,
"text": "PHP"
},
{
"code": null,
"e": 34532,
"s": 34521,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to implement iterative Binary Search\n#include <bits/stdc++.h>\nusing namespace std;\n \n// A iterative binary search function. It returns\n// location of x in given array arr[l..r] if present,\n// otherwise -1\nint binarySearch(int arr[], int l, int r, int x)\n{\n while (l <= r) {\n int m = l + (r - l) / 2;\n \n // Check if x is present at mid\n if (arr[m] == x)\n return m;\n \n // If x greater, ignore left half\n if (arr[m] < x)\n l = m + 1;\n \n // If x is smaller, ignore right half\n else\n r = m - 1;\n }\n \n // if we reach here, then element was\n // not present\n return -1;\n}\n \nint main(void)\n{\n int arr[] = { 2, 3, 4, 10, 40 };\n int x = 10;\n int n = sizeof(arr) / sizeof(arr[0]);\n int result = binarySearch(arr, 0, n - 1, x);\n (result == -1)\n ? cout << \"Element is not present in array\"\n : cout << \"Element is present at index \" << result;\n return 0;\n}\n\n\n\n\n\n",
"e": 35540,
"s": 34542,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C program to implement iterative Binary Search\n#include <stdio.h>\n \n// A iterative binary search function. It returns\n// location of x in given array arr[l..r] if present,\n// otherwise -1\nint binarySearch(int arr[], int l, int r, int x)\n{\n while (l <= r) {\n int m = l + (r - l) / 2;\n \n // Check if x is present at mid\n if (arr[m] == x)\n return m;\n \n // If x greater, ignore left half\n if (arr[m] < x)\n l = m + 1;\n \n // If x is smaller, ignore right half\n else\n r = m - 1;\n }\n \n // if we reach here, then element was\n // not present\n return -1;\n}\n \nint main(void)\n{\n int arr[] = { 2, 3, 4, 10, 40 };\n int n = sizeof(arr) / sizeof(arr[0]);\n int x = 10;\n int result = binarySearch(arr, 0, n - 1, x);\n (result == -1) ? printf(\"Element is not present\"\n \" in array\")\n : printf(\"Element is present at \"\n \"index %d\",\n result);\n return 0;\n}\n\n\n\n\n\n",
"e": 36612,
"s": 35550,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java implementation of iterative Binary Search\nclass BinarySearch {\n // Returns index of x if it is present in arr[],\n // else return -1\n int binarySearch(int arr[], int x)\n {\n int l = 0, r = arr.length - 1;\n while (l <= r) {\n int m = l + (r - l) / 2;\n \n // Check if x is present at mid\n if (arr[m] == x)\n return m;\n \n // If x greater, ignore left half\n if (arr[m] < x)\n l = m + 1;\n \n // If x is smaller, ignore right half\n else\n r = m - 1;\n }\n \n // if we reach here, then element was\n // not present\n return -1;\n }\n \n // Driver method to test above\n public static void main(String args[])\n {\n BinarySearch ob = new BinarySearch();\n int arr[] = { 2, 3, 4, 10, 40 };\n int n = arr.length;\n int x = 10;\n int result = ob.binarySearch(arr, x);\n if (result == -1)\n System.out.println(\"Element not present\");\n else\n System.out.println(\"Element found at \"\n + \"index \" + result);\n }\n}\n\n\n\n\n\n",
"e": 37806,
"s": 36622,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 code to implement iterative Binary\n# Search.\n \n# It returns location of x in given array arr\n# if present, else returns -1\n \n \ndef binarySearch(arr, l, r, x):\n \n while l <= r:\n \n mid = l + (r - l) // 2\n \n # Check if x is present at mid\n if arr[mid] == x:\n return mid\n \n # If x is greater, ignore left half\n elif arr[mid] < x:\n l = mid + 1\n \n # If x is smaller, ignore right half\n else:\n r = mid - 1\n \n # If we reach here, then the element\n # was not present\n return -1\n \n \n# Driver Code\narr = [2, 3, 4, 10, 40]\nx = 10\n \n# Function call\nresult = binarySearch(arr, 0, len(arr)-1, x)\n \nif result != -1:\n print(\"Element is present at index % d\" % result)\nelse:\n print(\"Element is not present in array\")\n\n\n\n\n\n",
"e": 38638,
"s": 37816,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# implementation of iterative Binary Search\nusing System;\n \nclass GFG {\n // Returns index of x if it is present in arr[],\n // else return -1\n static int binarySearch(int[] arr, int x)\n {\n int l = 0, r = arr.Length - 1;\n while (l <= r) {\n int m = l + (r - l) / 2;\n \n // Check if x is present at mid\n if (arr[m] == x)\n return m;\n \n // If x greater, ignore left half\n if (arr[m] < x)\n l = m + 1;\n \n // If x is smaller, ignore right half\n else\n r = m - 1;\n }\n \n // if we reach here, then element was\n // not present\n return -1;\n }\n \n // Driver method to test above\n public static void Main()\n {\n int[] arr = { 2, 3, 4, 10, 40 };\n int n = arr.Length;\n int x = 10;\n int result = binarySearch(arr, x);\n if (result == -1)\n Console.WriteLine(\"Element not present\");\n else\n Console.WriteLine(\"Element found at \"\n + \"index \" + result);\n }\n}\n// This code is contributed by Sam007\n\n\n\n\n\n",
"e": 39817,
"s": 38648,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<?php\n// PHP program to implement\n// iterative Binary Search\n \n// A iterative binary search \n// function. It returns location \n// of x in given array arr[l..r] \n// if present, otherwise -1\nfunction binarySearch($arr, $l, \n $r, $x)\n{\n while ($l <= $r)\n {\n $m = $l + ($r - $l) / 2;\n \n // Check if x is present at mid\n if ($arr[$m] == $x)\n return floor($m);\n \n // If x greater, ignore\n // left half\n if ($arr[$m] < $x)\n $l = $m + 1;\n \n // If x is smaller, \n // ignore right half\n else\n $r = $m - 1;\n }\n \n // if we reach here, then \n // element was not present\n return -1;\n}\n \n// Driver Code\n$arr = array(2, 3, 4, 10, 40);\n$n = count($arr);\n$x = 10;\n$result = binarySearch($arr, 0, \n $n - 1, $x);\nif(($result == -1))\necho \"Element is not present in array\";\nelse\necho \"Element is present at index \", \n $result;\n \n// This code is contributed by anuj_67.\n?>\n\n\n\n\n\n",
"e": 40875,
"s": 39827,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script>\n// Program to implement iterative Binary Search\n \n \n// A iterative binary search function. It returns\n// location of x in given array arr[l..r] is present,\n// otherwise -1\n \n function binarySearch(arr, x)\n{ \n let l = 0;\n let r = arr.length - 1;\n let mid;\n while (r >= l) {\n mid = l + Math.floor((r - l) / 2);\n \n // If the element is present at the middle\n // itself\n if (arr[mid] == x)\n return mid;\n \n // If element is smaller than mid, then\n // it can only be present in left subarray\n if (arr[mid] > x)\n r = mid - 1;\n \n // Else the element can only be present\n // in right subarray\n else\n l = mid + 1;\n }\n \n // We reach here when element is not\n // present in array\n return -1;\n}\n \n arr =new Array(2, 3, 4, 10, 40);\n x = 10;\n n = arr.length;\n result = binarySearch(arr, x);\n \n(result == -1) ? document.write(\"Element is not present in array\")\n : document.write (\"Element is present at index \" + result);\n \n// This code is contributed by simranarora5sos and rshuklabbb\n</script>\n\n\n\n\n\n",
"e": 42079,
"s": 40885,
"text": null
},
{
"code": null,
"e": 42109,
"s": 42079,
"text": "Element is present at index 3"
},
{
"code": null,
"e": 42153,
"s": 42109,
"text": "Algorithmic Paradigm: Decrease and Conquer."
},
{
"code": null,
"e": 42178,
"s": 42153,
"text": "Note: Here we are using "
},
{
"code": null,
"e": 42210,
"s": 42178,
"text": "int mid = low + (high – low)/2;"
},
{
"code": null,
"e": 42343,
"s": 42210,
"text": "Maybe, you wonder why we are calculating the middle index this way, we can simply add the lower and higher index and divide it by 2."
},
{
"code": null,
"e": 42369,
"s": 42343,
"text": "int mid = (low + high)/2;"
},
{
"code": null,
"e": 42470,
"s": 42369,
"text": "But if we calculate the middle index like this means our code is not 100% correct, it contains bugs."
},
{
"code": null,
"e": 42645,
"s": 42470,
"text": "That is, it fails for larger values of int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value(231 – 1 )."
},
{
"code": null,
"e": 42781,
"s": 42645,
"text": "The sum overflows to a negative value and the value stays negative when divided by 2. In java, it throws ArrayIndexOutOfBoundException."
},
{
"code": null,
"e": 42813,
"s": 42781,
"text": "int mid = low + (high – low)/2;"
},
{
"code": null,
"e": 42929,
"s": 42813,
"text": "So it’s better to use it like this. This bug applies equally to merge sort and other divide and conquer algorithms."
},
{
"code": null,
"e": 43754,
"s": 42929,
"text": "YouTubeGeeksforGeeks500K subscribersDSA Online (Binary Search) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=p9FZlPxukVI\" 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": 45260,
"s": 43754,
"text": "1. Language Foundation Courses [C++ / JAVA / Python ] Learn any programming language from scratch and understand all its fundamentals concepts for a strong programming foundation in the easiest possible manner with help of GeeksforGeeks Language Foundation Courses – Java Foundation | Python Foundation | C++ Foundation2. Geeks Classes Live Get interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session3. Complete Interview Preparation Get fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices.4. DSA Self Paced Start learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience.5. Company Specific Courses – Amazon, Microsoft, TCS & Wipro Crack the interview of any product-based giant company by specifically preparing with the questions that these companies usually ask in their coding interview round. Refer GeeksforGeeks Company Specific Courses: Amazon SDE Test Series, etc. "
},
{
"code": null,
"e": 45265,
"s": 45260,
"text": "vt_m"
},
{
"code": null,
"e": 45279,
"s": 45265,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 45290,
"s": 45279,
"text": "DhruvJain6"
},
{
"code": null,
"e": 45300,
"s": 45290,
"text": "pallav945"
},
{
"code": null,
"e": 45310,
"s": 45300,
"text": "moraliser"
},
{
"code": null,
"e": 45326,
"s": 45310,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 45339,
"s": 45326,
"text": "hritikrommie"
},
{
"code": null,
"e": 45355,
"s": 45339,
"text": "simranarora5sos"
},
{
"code": null,
"e": 45367,
"s": 45355,
"text": "kashishsoda"
},
{
"code": null,
"e": 45378,
"s": 45367,
"text": "rshuklabbb"
},
{
"code": null,
"e": 45391,
"s": 45378,
"text": "davidgatea21"
},
{
"code": null,
"e": 45400,
"s": 45391,
"text": "sweetyty"
},
{
"code": null,
"e": 45410,
"s": 45400,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 45425,
"s": 45410,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 45442,
"s": 45425,
"text": "kirankumarambati"
},
{
"code": null,
"e": 45454,
"s": 45442,
"text": "\nAccenture\n"
},
{
"code": null,
"e": 45470,
"s": 45454,
"text": "\nBinary Search\n"
},
{
"code": null,
"e": 45480,
"s": 45470,
"text": "\nInfosys\n"
},
{
"code": null,
"e": 45489,
"s": 45480,
"text": "\nOracle\n"
},
{
"code": null,
"e": 45500,
"s": 45489,
"text": "\nQualcomm\n"
},
{
"code": null,
"e": 45511,
"s": 45500,
"text": "\nSAP Labs\n"
},
{
"code": null,
"e": 45517,
"s": 45511,
"text": "\nTCS\n"
},
{
"code": null,
"e": 45525,
"s": 45517,
"text": "\nWipro\n"
},
{
"code": null,
"e": 45546,
"s": 45525,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 45558,
"s": 45546,
"text": "\nSearching\n"
},
{
"code": null,
"e": 45566,
"s": 45558,
"text": "Infosys"
},
{
"code": null,
"e": 45573,
"s": 45566,
"text": "Oracle"
},
{
"code": null,
"e": 45579,
"s": 45573,
"text": "Wipro"
},
{
"code": null,
"e": 45588,
"s": 45579,
"text": "SAP Labs"
},
{
"code": null,
"e": 45597,
"s": 45588,
"text": "Qualcomm"
},
{
"code": null,
"e": 45601,
"s": 45597,
"text": "TCS"
},
{
"code": null,
"e": 45611,
"s": 45601,
"text": "Accenture"
},
{
"code": null,
"e": 45621,
"s": 45611,
"text": "Searching"
},
{
"code": null,
"e": 45640,
"s": 45621,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 45654,
"s": 45640,
"text": "Binary Search"
},
{
"code": null,
"e": 45859,
"s": 45654,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 45868,
"s": 45859,
"text": "Comments"
},
{
"code": null,
"e": 45881,
"s": 45868,
"text": "Old Comments"
},
{
"code": null,
"e": 45943,
"s": 45881,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 45968,
"s": 45943,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 46026,
"s": 45968,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 46082,
"s": 46026,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 46102,
"s": 46082,
"text": "Find a peak element"
},
{
"code": null,
"e": 46158,
"s": 46102,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 46182,
"s": 46158,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 46226,
"s": 46182,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 46270,
"s": 46226,
"text": "k largest(or smallest) elements in an array"
}
]
|
LESS - Import Directives | The @import directive is used to import the files in the code. It spreads the LESS code over different files and allows to maintain the structure of code easily. You can put the @import statements anywhere in the code.
For instance, you can import the file by using @import keyword as @import "file_name.less".
You can use the @import statements depending on the different file extensions such as −
If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is.
If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is.
If it contains any other extension, then it will be considered as LESS and will be imported.
If it contains any other extension, then it will be considered as LESS and will be imported.
If there is no LESS extension, then it will appended and included as imported LESS file.
If there is no LESS extension, then it will appended and included as imported LESS file.
@import "style"; // imports the style.less
@import "style.less"; // imports the style.less
@import "style.php"; // imports the style.php as a less file
@import "style.css"; // it will kept the statement as it is
The following example demonstrates the use of variable in the SCSS file −
<!doctype html>
<head>
<title>Import Directives</title>
<link rel = "stylesheet" href = "style.css" type = "text/css" />
</head>
<body>
<h2>Example of Import Directives</h2>
<p class = "myline">Welcome to Tutorialspoint...</p>
</body>
</html>
Next, create the import_dir.less file.
.myline {
font-size: 20px;
}
Now, create the style.less file.
@import "http://www.tutorialspoint.com/less/import_dir.less";
.myline {
color:#FF0000;
}
The import_dir.less file will get imported into style.less file from the path https://www.tutorialspoint.com/less/import_dir.less.
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myline {
font-size: 20px;
}
.myline {
color: #FF0000;
}
Follow these steps to see how the above code works −
Save the above html code in the import_directives.html file.
Save the above html code in the import_directives.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
20 Lectures
1 hours
Anadi Sharma
44 Lectures
7.5 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Zach Miller
23 Lectures
1.5 hours
Zach Miller
34 Lectures
4 hours
Syed Raza
31 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2769,
"s": 2550,
"text": "The @import directive is used to import the files in the code. It spreads the LESS code over different files and allows to maintain the structure of code easily. You can put the @import statements anywhere in the code."
},
{
"code": null,
"e": 2861,
"s": 2769,
"text": "For instance, you can import the file by using @import keyword as @import \"file_name.less\"."
},
{
"code": null,
"e": 2949,
"s": 2861,
"text": "You can use the @import statements depending on the different file extensions such as −"
},
{
"code": null,
"e": 3060,
"s": 2949,
"text": "If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is."
},
{
"code": null,
"e": 3171,
"s": 3060,
"text": "If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is."
},
{
"code": null,
"e": 3264,
"s": 3171,
"text": "If it contains any other extension, then it will be considered as LESS and will be imported."
},
{
"code": null,
"e": 3357,
"s": 3264,
"text": "If it contains any other extension, then it will be considered as LESS and will be imported."
},
{
"code": null,
"e": 3446,
"s": 3357,
"text": "If there is no LESS extension, then it will appended and included as imported LESS file."
},
{
"code": null,
"e": 3535,
"s": 3446,
"text": "If there is no LESS extension, then it will appended and included as imported LESS file."
},
{
"code": null,
"e": 3754,
"s": 3535,
"text": "@import \"style\"; // imports the style.less\n@import \"style.less\"; // imports the style.less\n@import \"style.php\"; // imports the style.php as a less file\n@import \"style.css\"; // it will kept the statement as it is"
},
{
"code": null,
"e": 3828,
"s": 3754,
"text": "The following example demonstrates the use of variable in the SCSS file −"
},
{
"code": null,
"e": 4108,
"s": 3828,
"text": "<!doctype html>\n <head>\n <title>Import Directives</title>\n <link rel = \"stylesheet\" href = \"style.css\" type = \"text/css\" />\n </head>\n\n <body>\n <h2>Example of Import Directives</h2>\n <p class = \"myline\">Welcome to Tutorialspoint...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4147,
"s": 4108,
"text": "Next, create the import_dir.less file."
},
{
"code": null,
"e": 4179,
"s": 4147,
"text": ".myline {\n font-size: 20px;\n}"
},
{
"code": null,
"e": 4212,
"s": 4179,
"text": "Now, create the style.less file."
},
{
"code": null,
"e": 4304,
"s": 4212,
"text": "@import \"http://www.tutorialspoint.com/less/import_dir.less\";\n.myline {\n color:#FF0000;\n}"
},
{
"code": null,
"e": 4435,
"s": 4304,
"text": "The import_dir.less file will get imported into style.less file from the path https://www.tutorialspoint.com/less/import_dir.less."
},
{
"code": null,
"e": 4512,
"s": 4435,
"text": "You can compile the style.less to style.css by using the following command −"
},
{
"code": null,
"e": 4540,
"s": 4512,
"text": "lessc style.less style.css\n"
},
{
"code": null,
"e": 4641,
"s": 4540,
"text": "Execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 4705,
"s": 4641,
"text": ".myline {\n font-size: 20px;\n}\n\n.myline {\n color: #FF0000;\n}"
},
{
"code": null,
"e": 4758,
"s": 4705,
"text": "Follow these steps to see how the above code works −"
},
{
"code": null,
"e": 4819,
"s": 4758,
"text": "Save the above html code in the import_directives.html file."
},
{
"code": null,
"e": 4880,
"s": 4819,
"text": "Save the above html code in the import_directives.html file."
},
{
"code": null,
"e": 4955,
"s": 4880,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 5030,
"s": 4955,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 5063,
"s": 5030,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5077,
"s": 5063,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5112,
"s": 5077,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5140,
"s": 5112,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5173,
"s": 5140,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5186,
"s": 5173,
"text": " Zach Miller"
},
{
"code": null,
"e": 5221,
"s": 5186,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5234,
"s": 5221,
"text": " Zach Miller"
},
{
"code": null,
"e": 5267,
"s": 5234,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5278,
"s": 5267,
"text": " Syed Raza"
},
{
"code": null,
"e": 5311,
"s": 5278,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5331,
"s": 5311,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5338,
"s": 5331,
"text": " Print"
},
{
"code": null,
"e": 5349,
"s": 5338,
"text": " Add Notes"
}
]
|
GDB - Quick Guide | A debugger is a program that runs other programs, allowing the user to exercise control over these programs, and to examine variables when problems arise.
GNU Debugger, which is also called gdb, is the most popular debugger for UNIX systems to debug C and C++ programs.
GNU Debugger helps you in getting information about the following:
If a core dump happened, then what statement or expression did the program crash on?
If a core dump happened, then what statement or expression did the program crash on?
If an error occurs while executing a function, what line of the program contains the call to that function, and what are the parameters?
If an error occurs while executing a function, what line of the program contains the call to that function, and what are the parameters?
What are the values of program variables at a particular point during execution of the program?
What are the values of program variables at a particular point during execution of the program?
What is the result of a particular expression in a program?
What is the result of a particular expression in a program?
GDB allows you to run the program up to a certain point, then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line.
GDB uses a simple command line interface.
Even though GDB can help you in finding out memory leakage related bugs, but it is not a tool to detect memory leakages.
Even though GDB can help you in finding out memory leakage related bugs, but it is not a tool to detect memory leakages.
GDB cannot be used for programs that compile with errors and it does not help in fixing those errors.
GDB cannot be used for programs that compile with errors and it does not help in fixing those errors.
Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command:
$gdb -help
If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation.
You can install GDB on your system by following the simple steps discussed below.
step 1: Make sure you have the prerequisites for installing gdb:
An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)
An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)
115 MB of free disk space is required on the partition on which you're going to build gdb.
115 MB of free disk space is required on the partition on which you're going to build gdb.
20 MB of free disk space is required on the partition on which you're going to install gdb.
20 MB of free disk space is required on the partition on which you're going to install gdb.
GNU's decompression program, gzip
GNU's decompression program, gzip
The make utility - the GNU version is known to work without a problem, others probably do as well.
The make utility - the GNU version is known to work without a problem, others probably do as well.
step 2: Download the gdb source distribution from ftp.gnu.org/gnu/gdb. (We used gdb-6.6.tar.gz for these instructions.) Place the distribution files in your build directory.
step 3: In your build directory, decompress gdb-6.6.tar.gz and extract the source files from the archive. Once the files have finished extracting, change your working directory to the gdb-6.6 directory that was automatically created in your build directory.
$ build> gzip -d gdb-6.6.tar.gz
$ build> tar xfv gdb-6.6.tar
$ build> cd gdb-6.6
step 4: Run the configure script to configure the source tree for your platform.
$ gdb-6.6> .⁄configure
step 5: Build gdb using the make utility.
$ gdb-6.6> make
step 6: Login as root and install gdb using the following command.
$ gdb-6.6> make install
step 7: If required, disk space can be reclaimed by deleting the gdb build directory and the archive file after the installation is complete.
$ gdb-6.6> cd ..
$ build> rm -r gdb-6.6
$ build> rm gdb-6.6.tar
You now have gdb installed on your system and it is ready to use.
A Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variable, function, or line in the source code. This mapping could be something like:
Program instruction ⇒ item name, item type, original file, line number defined.
Program instruction ⇒ item name, item type, original file, line number defined.
Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your program, then it is required to create a symbol table which will have the required information to debug the program.
We can infer the following facts about symbol tables:
A symbol table works for a particular version of the program – if the program changes, a new table must be created.
A symbol table works for a particular version of the program – if the program changes, a new table must be created.
Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information.
Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information.
If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author.
If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author.
To let GDB be able to read all that information line by line from the symbol table, we need to compile it a bit differently. Normally we compile our programs as:
gcc hello.cc -o hello
Instead of doing this, we need to compile with the -g flag as shown below:
gcc -g hello.cc -o hello
GDB offers a big list of commands, however the following commands are the ones used most frequently:
b main - Puts a breakpoint at the beginning of the program
b main - Puts a breakpoint at the beginning of the program
b - Puts a breakpoint at the current line
b - Puts a breakpoint at the current line
b N - Puts a breakpoint at line N
b N - Puts a breakpoint at line N
b +N - Puts a breakpoint N lines down from the current line
b +N - Puts a breakpoint N lines down from the current line
b fn - Puts a breakpoint at the beginning of function "fn"
b fn - Puts a breakpoint at the beginning of function "fn"
d N - Deletes breakpoint number N
d N - Deletes breakpoint number N
info break - list breakpoints
info break - list breakpoints
r - Runs the program until a breakpoint or error
r - Runs the program until a breakpoint or error
c - Continues running the program until the next breakpoint or error
c - Continues running the program until the next breakpoint or error
f - Runs until the current function is finished
f - Runs until the current function is finished
s - Runs the next line of the program
s - Runs the next line of the program
s N - Runs the next N lines of the program
s N - Runs the next N lines of the program
n - Like s, but it does not step into functions
n - Like s, but it does not step into functions
u N - Runs until you get N lines in front of the current line
u N - Runs until you get N lines in front of the current line
p var - Prints the current value of the variable "var"
p var - Prints the current value of the variable "var"
bt - Prints a stack trace
bt - Prints a stack trace
u - Goes up a level in the stack
u - Goes up a level in the stack
d - Goes down a level in the stack
d - Goes down a level in the stack
q - Quits gdb
q - Quits gdb
gcc -g myprogram.c
Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun).
gcc -g myprogram.c
Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun).
Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun).
gdb a.out
Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt.
gdb a.out
Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt.
Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt.
r
r
r arg1 arg2
r arg1 arg2
r < file1
Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running.
r < file1
Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running.
Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running.
help
help
h breakpoints
Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.
h breakpoints
Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.
Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.
q - Quit GDB
q - Quit GDB
Stepping lets you trace the path of your program, and zero in on the code that is crashing or returning invalid input.
l
l
l 50
l 50
l myfunction
Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction).
l myfunction
Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction).
Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction).
next
Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly.
next
Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly.
Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly.
step
Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code.
step
Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code.
Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code.
finish
Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function.
finish
Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function.
Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function.
Breakpoints play an important role in debugging. They pause (break) a program when it reaches a certain point. You can examine and change variables and resume execution. This is helpful when some input failure occurs, or inputs are to be tested.
break 45
break 45
break myfunction
Sets a breakpoint at line 45, or at myfunction. The program will pause when it reaches the breakpoint.
break myfunction
Sets a breakpoint at line 45, or at myfunction. The program will pause when it reaches the breakpoint.
watch x == 3
Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.
watch x == 3
Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.
Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.
continue
Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.
continue
Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.
Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.
delete N
Deletes breakpoint N (breakpoints are numbered when created).
delete N
Deletes breakpoint N (breakpoints are numbered when created).
Viewing and changing variables at runtime is a critical part of debugging. Try providing invalid inputs to functions or running other test cases to find the root cause of problems. Typically, you will view/set variables when the program is paused.
print x
Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.
print x
Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.
Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.
set x = 3
set x = 3
set x = y
Sets x to a set value (3) or to another variable (y)
set x = y
Sets x to a set value (3) or to another variable (y)
call myfunction()
call myfunction()
call myotherfunction(x)
call myotherfunction(x)
call strlen(mystring)
Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions.
call strlen(mystring)
Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions.
Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions.
display x
Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value.
display x
Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value.
Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value.
undisplay x
Removes the constant display of a variable displayed by display command.
undisplay x
Removes the constant display of a variable displayed by display command.
A stack is a list of the current function calls - it shows you where you are in the program. A frame stores the details of a single function call, such as the arguments.
bt
Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is
bt
Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is
Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is
c <= current location
b
a
main
up
up
down
Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.
down
Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.
Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.
return
Returns from current function.
return
Returns from current function.
Signals are messages thrown after certain events, such as a timer or error. GDB may pause when it encounters a signal; you may wish to ignore them instead.
handle [signalname] [action]
handle [signalname] [action]
handle SIGUSR1 nostop
handle SIGUSR1 nostop
handle SIGUSR1 noprint
handle SIGUSR1 noprint
handle SIGUSR1 ignore
Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.
handle SIGUSR1 ignore
Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.
Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.
Go through the following examples to understand the procedure of debugging a program and core dumped.
Debugging Example 1
This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero.
Debugging Example 1
This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero.
Debugging Example 2
This example demonstrates a program that can dump a core due to non-initialized memory.
Debugging Example 2
This example demonstrates a program that can dump a core due to non-initialized memory.
Both the programs are written in C++ and generate core dump due to different reasons. After going through these two examples, you should be in a position to debug your C or C++ programs generating core dumps.
After going through this tutorial, you must have gained a good understanding of debugging a C or C++ program using GNU Debugger. Now it should be very easy for you to learn the functionality of other debuggers because they are very similar to GDB. It is highly recommended that you go through other debuggers as well to become familiar with their features.
There are quite a few good debuggers available in the market:
DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbx, i.e., man dbx.
DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbx, i.e., man dbx.
DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detail, use the man page of ddd, i.e., man ddd.
DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detail, use the man page of ddd, i.e., man ddd.
You can get a comprehensive detail about GNU Debugger from the following link: Debugging with GDB
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1864,
"s": 1709,
"text": "A debugger is a program that runs other programs, allowing the user to exercise control over these programs, and to examine variables when problems arise."
},
{
"code": null,
"e": 1979,
"s": 1864,
"text": "GNU Debugger, which is also called gdb, is the most popular debugger for UNIX systems to debug C and C++ programs."
},
{
"code": null,
"e": 2046,
"s": 1979,
"text": "GNU Debugger helps you in getting information about the following:"
},
{
"code": null,
"e": 2131,
"s": 2046,
"text": "If a core dump happened, then what statement or expression did the program crash on?"
},
{
"code": null,
"e": 2216,
"s": 2131,
"text": "If a core dump happened, then what statement or expression did the program crash on?"
},
{
"code": null,
"e": 2353,
"s": 2216,
"text": "If an error occurs while executing a function, what line of the program contains the call to that function, and what are the parameters?"
},
{
"code": null,
"e": 2490,
"s": 2353,
"text": "If an error occurs while executing a function, what line of the program contains the call to that function, and what are the parameters?"
},
{
"code": null,
"e": 2586,
"s": 2490,
"text": "What are the values of program variables at a particular point during execution of the program?"
},
{
"code": null,
"e": 2682,
"s": 2586,
"text": "What are the values of program variables at a particular point during execution of the program?"
},
{
"code": null,
"e": 2742,
"s": 2682,
"text": "What is the result of a particular expression in a program?"
},
{
"code": null,
"e": 2802,
"s": 2742,
"text": "What is the result of a particular expression in a program?"
},
{
"code": null,
"e": 3046,
"s": 2802,
"text": "GDB allows you to run the program up to a certain point, then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line."
},
{
"code": null,
"e": 3088,
"s": 3046,
"text": "GDB uses a simple command line interface."
},
{
"code": null,
"e": 3209,
"s": 3088,
"text": "Even though GDB can help you in finding out memory leakage related bugs, but it is not a tool to detect memory leakages."
},
{
"code": null,
"e": 3330,
"s": 3209,
"text": "Even though GDB can help you in finding out memory leakage related bugs, but it is not a tool to detect memory leakages."
},
{
"code": null,
"e": 3432,
"s": 3330,
"text": "GDB cannot be used for programs that compile with errors and it does not help in fixing those errors."
},
{
"code": null,
"e": 3534,
"s": 3432,
"text": "GDB cannot be used for programs that compile with errors and it does not help in fixing those errors."
},
{
"code": null,
"e": 3660,
"s": 3534,
"text": "Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command:"
},
{
"code": null,
"e": 3673,
"s": 3660,
"text": "$gdb -help \n"
},
{
"code": null,
"e": 3822,
"s": 3673,
"text": "If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation."
},
{
"code": null,
"e": 3904,
"s": 3822,
"text": "You can install GDB on your system by following the simple steps discussed below."
},
{
"code": null,
"e": 3969,
"s": 3904,
"text": "step 1: Make sure you have the prerequisites for installing gdb:"
},
{
"code": null,
"e": 4080,
"s": 3969,
"text": "An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)"
},
{
"code": null,
"e": 4191,
"s": 4080,
"text": "An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)"
},
{
"code": null,
"e": 4282,
"s": 4191,
"text": "115 MB of free disk space is required on the partition on which you're going to build gdb."
},
{
"code": null,
"e": 4373,
"s": 4282,
"text": "115 MB of free disk space is required on the partition on which you're going to build gdb."
},
{
"code": null,
"e": 4465,
"s": 4373,
"text": "20 MB of free disk space is required on the partition on which you're going to install gdb."
},
{
"code": null,
"e": 4557,
"s": 4465,
"text": "20 MB of free disk space is required on the partition on which you're going to install gdb."
},
{
"code": null,
"e": 4591,
"s": 4557,
"text": "GNU's decompression program, gzip"
},
{
"code": null,
"e": 4625,
"s": 4591,
"text": "GNU's decompression program, gzip"
},
{
"code": null,
"e": 4724,
"s": 4625,
"text": "The make utility - the GNU version is known to work without a problem, others probably do as well."
},
{
"code": null,
"e": 4823,
"s": 4724,
"text": "The make utility - the GNU version is known to work without a problem, others probably do as well."
},
{
"code": null,
"e": 4997,
"s": 4823,
"text": "step 2: Download the gdb source distribution from ftp.gnu.org/gnu/gdb. (We used gdb-6.6.tar.gz for these instructions.) Place the distribution files in your build directory."
},
{
"code": null,
"e": 5255,
"s": 4997,
"text": "step 3: In your build directory, decompress gdb-6.6.tar.gz and extract the source files from the archive. Once the files have finished extracting, change your working directory to the gdb-6.6 directory that was automatically created in your build directory."
},
{
"code": null,
"e": 5340,
"s": 5255,
"text": "$ build> gzip -d gdb-6.6.tar.gz \n$ build> tar xfv gdb-6.6.tar \n$ build> cd gdb-6.6 \n"
},
{
"code": null,
"e": 5421,
"s": 5340,
"text": "step 4: Run the configure script to configure the source tree for your platform."
},
{
"code": null,
"e": 5446,
"s": 5421,
"text": "$ gdb-6.6> .⁄configure \n"
},
{
"code": null,
"e": 5488,
"s": 5446,
"text": "step 5: Build gdb using the make utility."
},
{
"code": null,
"e": 5506,
"s": 5488,
"text": "$ gdb-6.6> make \n"
},
{
"code": null,
"e": 5573,
"s": 5506,
"text": "step 6: Login as root and install gdb using the following command."
},
{
"code": null,
"e": 5599,
"s": 5573,
"text": "$ gdb-6.6> make install \n"
},
{
"code": null,
"e": 5741,
"s": 5599,
"text": "step 7: If required, disk space can be reclaimed by deleting the gdb build directory and the archive file after the installation is complete."
},
{
"code": null,
"e": 5809,
"s": 5741,
"text": "$ gdb-6.6> cd .. \n$ build> rm -r gdb-6.6 \n$ build> rm gdb-6.6.tar \n"
},
{
"code": null,
"e": 5875,
"s": 5809,
"text": "You now have gdb installed on your system and it is ready to use."
},
{
"code": null,
"e": 6058,
"s": 5875,
"text": "A Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variable, function, or line in the source code. This mapping could be something like:"
},
{
"code": null,
"e": 6138,
"s": 6058,
"text": "Program instruction ⇒ item name, item type, original file, line number defined."
},
{
"code": null,
"e": 6218,
"s": 6138,
"text": "Program instruction ⇒ item name, item type, original file, line number defined."
},
{
"code": null,
"e": 6441,
"s": 6218,
"text": "Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your program, then it is required to create a symbol table which will have the required information to debug the program."
},
{
"code": null,
"e": 6495,
"s": 6441,
"text": "We can infer the following facts about symbol tables:"
},
{
"code": null,
"e": 6611,
"s": 6495,
"text": "A symbol table works for a particular version of the program – if the program changes, a new table must be created."
},
{
"code": null,
"e": 6727,
"s": 6611,
"text": "A symbol table works for a particular version of the program – if the program changes, a new table must be created."
},
{
"code": null,
"e": 6871,
"s": 6727,
"text": "Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information."
},
{
"code": null,
"e": 7015,
"s": 6871,
"text": "Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information."
},
{
"code": null,
"e": 7131,
"s": 7015,
"text": "If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author."
},
{
"code": null,
"e": 7247,
"s": 7131,
"text": "If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author."
},
{
"code": null,
"e": 7409,
"s": 7247,
"text": "To let GDB be able to read all that information line by line from the symbol table, we need to compile it a bit differently. Normally we compile our programs as:"
},
{
"code": null,
"e": 7433,
"s": 7409,
"text": "gcc hello.cc -o hello \n"
},
{
"code": null,
"e": 7508,
"s": 7433,
"text": "Instead of doing this, we need to compile with the -g flag as shown below:"
},
{
"code": null,
"e": 7535,
"s": 7508,
"text": "gcc -g hello.cc -o hello \n"
},
{
"code": null,
"e": 7636,
"s": 7535,
"text": "GDB offers a big list of commands, however the following commands are the ones used most frequently:"
},
{
"code": null,
"e": 7695,
"s": 7636,
"text": "b main - Puts a breakpoint at the beginning of the program"
},
{
"code": null,
"e": 7754,
"s": 7695,
"text": "b main - Puts a breakpoint at the beginning of the program"
},
{
"code": null,
"e": 7796,
"s": 7754,
"text": "b - Puts a breakpoint at the current line"
},
{
"code": null,
"e": 7838,
"s": 7796,
"text": "b - Puts a breakpoint at the current line"
},
{
"code": null,
"e": 7872,
"s": 7838,
"text": "b N - Puts a breakpoint at line N"
},
{
"code": null,
"e": 7906,
"s": 7872,
"text": "b N - Puts a breakpoint at line N"
},
{
"code": null,
"e": 7966,
"s": 7906,
"text": "b +N - Puts a breakpoint N lines down from the current line"
},
{
"code": null,
"e": 8026,
"s": 7966,
"text": "b +N - Puts a breakpoint N lines down from the current line"
},
{
"code": null,
"e": 8085,
"s": 8026,
"text": "b fn - Puts a breakpoint at the beginning of function \"fn\""
},
{
"code": null,
"e": 8144,
"s": 8085,
"text": "b fn - Puts a breakpoint at the beginning of function \"fn\""
},
{
"code": null,
"e": 8178,
"s": 8144,
"text": "d N - Deletes breakpoint number N"
},
{
"code": null,
"e": 8212,
"s": 8178,
"text": "d N - Deletes breakpoint number N"
},
{
"code": null,
"e": 8242,
"s": 8212,
"text": "info break - list breakpoints"
},
{
"code": null,
"e": 8272,
"s": 8242,
"text": "info break - list breakpoints"
},
{
"code": null,
"e": 8321,
"s": 8272,
"text": "r - Runs the program until a breakpoint or error"
},
{
"code": null,
"e": 8370,
"s": 8321,
"text": "r - Runs the program until a breakpoint or error"
},
{
"code": null,
"e": 8439,
"s": 8370,
"text": "c - Continues running the program until the next breakpoint or error"
},
{
"code": null,
"e": 8508,
"s": 8439,
"text": "c - Continues running the program until the next breakpoint or error"
},
{
"code": null,
"e": 8556,
"s": 8508,
"text": "f - Runs until the current function is finished"
},
{
"code": null,
"e": 8604,
"s": 8556,
"text": "f - Runs until the current function is finished"
},
{
"code": null,
"e": 8642,
"s": 8604,
"text": "s - Runs the next line of the program"
},
{
"code": null,
"e": 8680,
"s": 8642,
"text": "s - Runs the next line of the program"
},
{
"code": null,
"e": 8723,
"s": 8680,
"text": "s N - Runs the next N lines of the program"
},
{
"code": null,
"e": 8766,
"s": 8723,
"text": "s N - Runs the next N lines of the program"
},
{
"code": null,
"e": 8814,
"s": 8766,
"text": "n - Like s, but it does not step into functions"
},
{
"code": null,
"e": 8862,
"s": 8814,
"text": "n - Like s, but it does not step into functions"
},
{
"code": null,
"e": 8924,
"s": 8862,
"text": "u N - Runs until you get N lines in front of the current line"
},
{
"code": null,
"e": 8986,
"s": 8924,
"text": "u N - Runs until you get N lines in front of the current line"
},
{
"code": null,
"e": 9041,
"s": 8986,
"text": "p var - Prints the current value of the variable \"var\""
},
{
"code": null,
"e": 9096,
"s": 9041,
"text": "p var - Prints the current value of the variable \"var\""
},
{
"code": null,
"e": 9122,
"s": 9096,
"text": "bt - Prints a stack trace"
},
{
"code": null,
"e": 9148,
"s": 9122,
"text": "bt - Prints a stack trace"
},
{
"code": null,
"e": 9181,
"s": 9148,
"text": "u - Goes up a level in the stack"
},
{
"code": null,
"e": 9214,
"s": 9181,
"text": "u - Goes up a level in the stack"
},
{
"code": null,
"e": 9249,
"s": 9214,
"text": "d - Goes down a level in the stack"
},
{
"code": null,
"e": 9284,
"s": 9249,
"text": "d - Goes down a level in the stack"
},
{
"code": null,
"e": 9298,
"s": 9284,
"text": "q - Quits gdb"
},
{
"code": null,
"e": 9312,
"s": 9298,
"text": "q - Quits gdb"
},
{
"code": null,
"e": 9552,
"s": 9312,
"text": "gcc -g myprogram.c\n\nCompiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun).\n\n"
},
{
"code": null,
"e": 9571,
"s": 9552,
"text": "gcc -g myprogram.c"
},
{
"code": null,
"e": 9789,
"s": 9571,
"text": "Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun)."
},
{
"code": null,
"e": 10007,
"s": 9789,
"text": "Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun)."
},
{
"code": null,
"e": 10140,
"s": 10007,
"text": "gdb a.out\n\nOpens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt.\n\n"
},
{
"code": null,
"e": 10150,
"s": 10140,
"text": "gdb a.out"
},
{
"code": null,
"e": 10270,
"s": 10150,
"text": "Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt."
},
{
"code": null,
"e": 10390,
"s": 10270,
"text": "Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt."
},
{
"code": null,
"e": 10392,
"s": 10390,
"text": "r"
},
{
"code": null,
"e": 10394,
"s": 10392,
"text": "r"
},
{
"code": null,
"e": 10406,
"s": 10394,
"text": "r arg1 arg2"
},
{
"code": null,
"e": 10418,
"s": 10406,
"text": "r arg1 arg2"
},
{
"code": null,
"e": 10604,
"s": 10418,
"text": "r < file1\n\nThree ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running.\n\n"
},
{
"code": null,
"e": 10614,
"s": 10604,
"text": "r < file1"
},
{
"code": null,
"e": 10787,
"s": 10614,
"text": "Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running."
},
{
"code": null,
"e": 10960,
"s": 10787,
"text": "Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running."
},
{
"code": null,
"e": 10965,
"s": 10960,
"text": "help"
},
{
"code": null,
"e": 10970,
"s": 10965,
"text": "help"
},
{
"code": null,
"e": 11086,
"s": 10970,
"text": "h breakpoints\n\nLists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.\n\n"
},
{
"code": null,
"e": 11100,
"s": 11086,
"text": "h breakpoints"
},
{
"code": null,
"e": 11199,
"s": 11100,
"text": "Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented."
},
{
"code": null,
"e": 11298,
"s": 11199,
"text": "Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented."
},
{
"code": null,
"e": 11311,
"s": 11298,
"text": "q - Quit GDB"
},
{
"code": null,
"e": 11324,
"s": 11311,
"text": "q - Quit GDB"
},
{
"code": null,
"e": 11443,
"s": 11324,
"text": "Stepping lets you trace the path of your program, and zero in on the code that is crashing or returning invalid input."
},
{
"code": null,
"e": 11445,
"s": 11443,
"text": "l"
},
{
"code": null,
"e": 11447,
"s": 11445,
"text": "l"
},
{
"code": null,
"e": 11452,
"s": 11447,
"text": "l 50"
},
{
"code": null,
"e": 11457,
"s": 11452,
"text": "l 50"
},
{
"code": null,
"e": 11583,
"s": 11457,
"text": "l myfunction\n\nLists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction).\n\n"
},
{
"code": null,
"e": 11596,
"s": 11583,
"text": "l myfunction"
},
{
"code": null,
"e": 11706,
"s": 11596,
"text": "Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction)."
},
{
"code": null,
"e": 11816,
"s": 11706,
"text": "Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction)."
},
{
"code": null,
"e": 12004,
"s": 11816,
"text": "next\n\nRuns the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly.\n\n"
},
{
"code": null,
"e": 12009,
"s": 12004,
"text": "next"
},
{
"code": null,
"e": 12189,
"s": 12009,
"text": "Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly."
},
{
"code": null,
"e": 12369,
"s": 12189,
"text": "Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly."
},
{
"code": null,
"e": 12636,
"s": 12369,
"text": "step\n\nRuns the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code.\n\n"
},
{
"code": null,
"e": 12641,
"s": 12636,
"text": "step"
},
{
"code": null,
"e": 12900,
"s": 12641,
"text": "Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code."
},
{
"code": null,
"e": 13159,
"s": 12900,
"text": "Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code."
},
{
"code": null,
"e": 13297,
"s": 13159,
"text": "finish\n\nFinishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function.\n\n"
},
{
"code": null,
"e": 13304,
"s": 13297,
"text": "finish"
},
{
"code": null,
"e": 13432,
"s": 13304,
"text": "Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function."
},
{
"code": null,
"e": 13560,
"s": 13432,
"text": "Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function."
},
{
"code": null,
"e": 13806,
"s": 13560,
"text": "Breakpoints play an important role in debugging. They pause (break) a program when it reaches a certain point. You can examine and change variables and resume execution. This is helpful when some input failure occurs, or inputs are to be tested."
},
{
"code": null,
"e": 13815,
"s": 13806,
"text": "break 45"
},
{
"code": null,
"e": 13824,
"s": 13815,
"text": "break 45"
},
{
"code": null,
"e": 13947,
"s": 13824,
"text": "break myfunction\n\nSets a breakpoint at line 45, or at myfunction. The program will pause when it reaches the breakpoint.\n\n"
},
{
"code": null,
"e": 13964,
"s": 13947,
"text": "break myfunction"
},
{
"code": null,
"e": 14067,
"s": 13964,
"text": "Sets a breakpoint at line 45, or at myfunction. The program will pause when it reaches the breakpoint."
},
{
"code": null,
"e": 14280,
"s": 14067,
"text": "watch x == 3\n\nSets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.\n\n"
},
{
"code": null,
"e": 14293,
"s": 14280,
"text": "watch x == 3"
},
{
"code": null,
"e": 14490,
"s": 14293,
"text": "Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call."
},
{
"code": null,
"e": 14687,
"s": 14490,
"text": "Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call."
},
{
"code": null,
"e": 14836,
"s": 14687,
"text": "continue\n\nResumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.\n\n"
},
{
"code": null,
"e": 14845,
"s": 14836,
"text": "continue"
},
{
"code": null,
"e": 14982,
"s": 14845,
"text": "Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint."
},
{
"code": null,
"e": 15119,
"s": 14982,
"text": "Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint."
},
{
"code": null,
"e": 15193,
"s": 15119,
"text": "delete N\n\nDeletes breakpoint N (breakpoints are numbered when created).\n\n"
},
{
"code": null,
"e": 15202,
"s": 15193,
"text": "delete N"
},
{
"code": null,
"e": 15264,
"s": 15202,
"text": "Deletes breakpoint N (breakpoints are numbered when created)."
},
{
"code": null,
"e": 15512,
"s": 15264,
"text": "Viewing and changing variables at runtime is a critical part of debugging. Try providing invalid inputs to functions or running other test cases to find the root cause of problems. Typically, you will view/set variables when the program is paused."
},
{
"code": null,
"e": 15696,
"s": 15512,
"text": "print x\n\nPrints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.\n\n"
},
{
"code": null,
"e": 15704,
"s": 15696,
"text": "print x"
},
{
"code": null,
"e": 15877,
"s": 15704,
"text": "Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed."
},
{
"code": null,
"e": 16050,
"s": 15877,
"text": "Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed."
},
{
"code": null,
"e": 16060,
"s": 16050,
"text": "set x = 3"
},
{
"code": null,
"e": 16070,
"s": 16060,
"text": "set x = 3"
},
{
"code": null,
"e": 16136,
"s": 16070,
"text": "set x = y\n\nSets x to a set value (3) or to another variable (y)\n\n"
},
{
"code": null,
"e": 16146,
"s": 16136,
"text": "set x = y"
},
{
"code": null,
"e": 16199,
"s": 16146,
"text": "Sets x to a set value (3) or to another variable (y)"
},
{
"code": null,
"e": 16217,
"s": 16199,
"text": "call myfunction()"
},
{
"code": null,
"e": 16235,
"s": 16217,
"text": "call myfunction()"
},
{
"code": null,
"e": 16259,
"s": 16235,
"text": "call myotherfunction(x)"
},
{
"code": null,
"e": 16283,
"s": 16259,
"text": "call myotherfunction(x)"
},
{
"code": null,
"e": 16413,
"s": 16283,
"text": "call strlen(mystring)\n\nCalls user-defined or system functions. This is extremely useful, but beware of calling buggy functions.\n\n"
},
{
"code": null,
"e": 16435,
"s": 16413,
"text": "call strlen(mystring)"
},
{
"code": null,
"e": 16540,
"s": 16435,
"text": "Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions."
},
{
"code": null,
"e": 16645,
"s": 16540,
"text": "Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions."
},
{
"code": null,
"e": 16804,
"s": 16645,
"text": "display x\n\nConstantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value.\n\n"
},
{
"code": null,
"e": 16814,
"s": 16804,
"text": "display x"
},
{
"code": null,
"e": 16960,
"s": 16814,
"text": "Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value."
},
{
"code": null,
"e": 17106,
"s": 16960,
"text": "Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value."
},
{
"code": null,
"e": 17194,
"s": 17106,
"text": "undisplay x\n\nRemoves the constant display of a variable displayed by display command.\n\n"
},
{
"code": null,
"e": 17206,
"s": 17194,
"text": "undisplay x"
},
{
"code": null,
"e": 17279,
"s": 17206,
"text": "Removes the constant display of a variable displayed by display command."
},
{
"code": null,
"e": 17449,
"s": 17279,
"text": "A stack is a list of the current function calls - it shows you where you are in the program. A frame stores the details of a single function call, such as the arguments."
},
{
"code": null,
"e": 17628,
"s": 17449,
"text": "bt\n\nBacktraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is\n\n"
},
{
"code": null,
"e": 17631,
"s": 17628,
"text": "bt"
},
{
"code": null,
"e": 17804,
"s": 17631,
"text": "Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is"
},
{
"code": null,
"e": 17977,
"s": 17804,
"text": "Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is"
},
{
"code": null,
"e": 18013,
"s": 17977,
"text": "c <= current location \nb \na \nmain \n"
},
{
"code": null,
"e": 18016,
"s": 18013,
"text": "up"
},
{
"code": null,
"e": 18019,
"s": 18016,
"text": "up"
},
{
"code": null,
"e": 18152,
"s": 18019,
"text": "down\n\nMove to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.\n\n"
},
{
"code": null,
"e": 18157,
"s": 18152,
"text": "down"
},
{
"code": null,
"e": 18282,
"s": 18157,
"text": "Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables."
},
{
"code": null,
"e": 18407,
"s": 18282,
"text": "Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables."
},
{
"code": null,
"e": 18448,
"s": 18407,
"text": "return\n\nReturns from current function.\n\n"
},
{
"code": null,
"e": 18455,
"s": 18448,
"text": "return"
},
{
"code": null,
"e": 18486,
"s": 18455,
"text": "Returns from current function."
},
{
"code": null,
"e": 18642,
"s": 18486,
"text": "Signals are messages thrown after certain events, such as a timer or error. GDB may pause when it encounters a signal; you may wish to ignore them instead."
},
{
"code": null,
"e": 18671,
"s": 18642,
"text": "handle [signalname] [action]"
},
{
"code": null,
"e": 18700,
"s": 18671,
"text": "handle [signalname] [action]"
},
{
"code": null,
"e": 18722,
"s": 18700,
"text": "handle SIGUSR1 nostop"
},
{
"code": null,
"e": 18744,
"s": 18722,
"text": "handle SIGUSR1 nostop"
},
{
"code": null,
"e": 18767,
"s": 18744,
"text": "handle SIGUSR1 noprint"
},
{
"code": null,
"e": 18790,
"s": 18767,
"text": "handle SIGUSR1 noprint"
},
{
"code": null,
"e": 18919,
"s": 18790,
"text": "handle SIGUSR1 ignore\n\nInstruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.\n\n"
},
{
"code": null,
"e": 18941,
"s": 18919,
"text": "handle SIGUSR1 ignore"
},
{
"code": null,
"e": 19045,
"s": 18941,
"text": "Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring."
},
{
"code": null,
"e": 19149,
"s": 19045,
"text": "Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring."
},
{
"code": null,
"e": 19251,
"s": 19149,
"text": "Go through the following examples to understand the procedure of debugging a program and core dumped."
},
{
"code": null,
"e": 19397,
"s": 19251,
"text": "Debugging Example 1\nThis example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero."
},
{
"code": null,
"e": 19417,
"s": 19397,
"text": "Debugging Example 1"
},
{
"code": null,
"e": 19543,
"s": 19417,
"text": "This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero."
},
{
"code": null,
"e": 19651,
"s": 19543,
"text": "Debugging Example 2\nThis example demonstrates a program that can dump a core due to non-initialized memory."
},
{
"code": null,
"e": 19671,
"s": 19651,
"text": "Debugging Example 2"
},
{
"code": null,
"e": 19759,
"s": 19671,
"text": "This example demonstrates a program that can dump a core due to non-initialized memory."
},
{
"code": null,
"e": 19968,
"s": 19759,
"text": "Both the programs are written in C++ and generate core dump due to different reasons. After going through these two examples, you should be in a position to debug your C or C++ programs generating core dumps."
},
{
"code": null,
"e": 20325,
"s": 19968,
"text": "After going through this tutorial, you must have gained a good understanding of debugging a C or C++ program using GNU Debugger. Now it should be very easy for you to learn the functionality of other debuggers because they are very similar to GDB. It is highly recommended that you go through other debuggers as well to become familiar with their features."
},
{
"code": null,
"e": 20387,
"s": 20325,
"text": "There are quite a few good debuggers available in the market:"
},
{
"code": null,
"e": 20544,
"s": 20387,
"text": "DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbx, i.e., man dbx."
},
{
"code": null,
"e": 20701,
"s": 20544,
"text": "DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbx, i.e., man dbx."
},
{
"code": null,
"e": 20849,
"s": 20701,
"text": "DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detail, use the man page of ddd, i.e., man ddd."
},
{
"code": null,
"e": 20997,
"s": 20849,
"text": "DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detail, use the man page of ddd, i.e., man ddd."
},
{
"code": null,
"e": 21095,
"s": 20997,
"text": "You can get a comprehensive detail about GNU Debugger from the following link: Debugging with GDB"
},
{
"code": null,
"e": 21102,
"s": 21095,
"text": " Print"
},
{
"code": null,
"e": 21113,
"s": 21102,
"text": " Add Notes"
}
]
|
CSS | translate3d() Function - GeeksforGeeks | 07 Aug, 2019
The translate3d() function is an inbuilt function which is used to reposition an element in 3D space.
Syntax:
translate3d( tx, ty, tz )
Parameters: This function accepts three parameters as mentioned above and described below:
tx: This parameter holds the length of translation corresponding to x-axis. This parameter holds the value in form of number or percentage.
ty: This parameter holds the length of translation corresponding to y-axis. This parameter holds the value in form of number or percentage.
tz: This parameter holds the length of translation corresponding to z-axis. This parameter holds the value in form of numbers only.
Below examples illustrate the translate3d() function in CSS:
Example 1:
<!DOCTYPE html><html> <head> <title> CSS translate3d() function </title> <style> body { text-align: center; } h1 { color: green; } .translate3d_image { transform: translate3d(100px, 0, 0); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translate3d() function</h2> <h4>Original Image</h4> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> <br> <h4>Translated image</h4> <img class="translate3d_image" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"></body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title>CSS translate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; } .geeks { transform: translate3d(100px, 20px, 0); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translate3d() function</h2> <h4>Original Element</h4> <div class="GFG">Welcome to GeeksforGeeks</div> <h4>Translated Element</h4> <div class="GFG geeks">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by translate3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to fetch data from localserver database and display on HTML table using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n07 Aug, 2019"
},
{
"code": null,
"e": 25398,
"s": 25296,
"text": "The translate3d() function is an inbuilt function which is used to reposition an element in 3D space."
},
{
"code": null,
"e": 25406,
"s": 25398,
"text": "Syntax:"
},
{
"code": null,
"e": 25432,
"s": 25406,
"text": "translate3d( tx, ty, tz )"
},
{
"code": null,
"e": 25523,
"s": 25432,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25663,
"s": 25523,
"text": "tx: This parameter holds the length of translation corresponding to x-axis. This parameter holds the value in form of number or percentage."
},
{
"code": null,
"e": 25803,
"s": 25663,
"text": "ty: This parameter holds the length of translation corresponding to y-axis. This parameter holds the value in form of number or percentage."
},
{
"code": null,
"e": 25935,
"s": 25803,
"text": "tz: This parameter holds the length of translation corresponding to z-axis. This parameter holds the value in form of numbers only."
},
{
"code": null,
"e": 25996,
"s": 25935,
"text": "Below examples illustrate the translate3d() function in CSS:"
},
{
"code": null,
"e": 26007,
"s": 25996,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS translate3d() function </title> <style> body { text-align: center; } h1 { color: green; } .translate3d_image { transform: translate3d(100px, 0, 0); } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translate3d() function</h2> <h4>Original Image</h4> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> <br> <h4>Translated image</h4> <img class=\"translate3d_image\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"></body> </html>",
"e": 26783,
"s": 26007,
"text": null
},
{
"code": null,
"e": 26791,
"s": 26783,
"text": "Output:"
},
{
"code": null,
"e": 26802,
"s": 26791,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS translate3d() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; } .geeks { transform: translate3d(100px, 20px, 0); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS translate3d() function</h2> <h4>Original Element</h4> <div class=\"GFG\">Welcome to GeeksforGeeks</div> <h4>Translated Element</h4> <div class=\"GFG geeks\">Welcome to GeeksforGeeks</div> </body> </html>",
"e": 27459,
"s": 26802,
"text": null
},
{
"code": null,
"e": 27467,
"s": 27459,
"text": "Output:"
},
{
"code": null,
"e": 27554,
"s": 27467,
"text": "Supported Browsers: The browsers supported by translate3d() function are listed below:"
},
{
"code": null,
"e": 27568,
"s": 27554,
"text": "Google Chrome"
},
{
"code": null,
"e": 27586,
"s": 27568,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27594,
"s": 27586,
"text": "Firefox"
},
{
"code": null,
"e": 27601,
"s": 27594,
"text": "Safari"
},
{
"code": null,
"e": 27607,
"s": 27601,
"text": "Opera"
},
{
"code": null,
"e": 27621,
"s": 27607,
"text": "CSS-Functions"
},
{
"code": null,
"e": 27625,
"s": 27621,
"text": "CSS"
},
{
"code": null,
"e": 27642,
"s": 27625,
"text": "Web Technologies"
},
{
"code": null,
"e": 27740,
"s": 27642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27749,
"s": 27740,
"text": "Comments"
},
{
"code": null,
"e": 27762,
"s": 27749,
"text": "Old Comments"
},
{
"code": null,
"e": 27799,
"s": 27762,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27828,
"s": 27799,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27870,
"s": 27828,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 27905,
"s": 27870,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 27987,
"s": 27905,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28029,
"s": 27987,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28062,
"s": 28029,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28105,
"s": 28062,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28149,
"s": 28105,
"text": "Top 10 Angular Libraries For Web Developers"
}
]
|
Apache Presto - split(string,delimiter) | presto:default> select split('apache presto','e') as string_split;
string_split
-------------------
[apach, pr, sto]
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2074,
"s": 2006,
"text": "presto:default> select split('apache presto','e') as string_split; "
},
{
"code": null,
"e": 2133,
"s": 2074,
"text": " string_split \n------------------- \n [apach, pr, sto] \n"
},
{
"code": null,
"e": 2168,
"s": 2133,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2187,
"s": 2168,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2222,
"s": 2187,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2243,
"s": 2222,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 2276,
"s": 2243,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2289,
"s": 2276,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 2324,
"s": 2289,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2342,
"s": 2324,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2375,
"s": 2342,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2393,
"s": 2375,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2426,
"s": 2393,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2444,
"s": 2426,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2451,
"s": 2444,
"text": " Print"
},
{
"code": null,
"e": 2462,
"s": 2451,
"text": " Add Notes"
}
]
|
Find the first repeated word in a string - GeeksforGeeks | 22 Apr, 2022
Given a string, Find the 1st repeated word in a stringExamples:
Input : "Ravi had been saying that he had been there"
Output : had
Input : "Ravi had been saying that"
Output : No Repetition
Input : "he had had he"
Output : he
question source : https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-internship/
Simple Approach : Start iterating from back and for every new word , store it in unordered map . For every word which has occurred more than one , update ans to be that word , at last reverse ans and print it.
C++
Python3
Javascript
// Cpp program to find first repeated word in a string#include<bits/stdc++.h>using namespace std;void solve(string s){ unordered_map<string,int> mp; // to store occurrences of word string t="",ans=""; // traversing from back makes sure that we get the word which repeats first as ans for(int i=s.length()-1;i>=0;i--) { // if char present , then add that in temp word string t if(s[i]!=' ') { t+=s[i]; } // if space is there then this word t needs to stored in map else { mp[t]++; // if that string t has occurred previously then it is a possible ans if(mp[t]>1) ans=t; // set t as empty for again new word t=""; } } // first word like "he" needs to be mapped mp[t]++; if(mp[t]>1) ans=t; if(ans!="") { // reverse ans string as it has characters in reverse order reverse(ans.begin(),ans.end()); cout<<ans<<'\n'; } else cout<<"No Repetition\n";}int main(){ string u="Ravi had been saying that he had been there"; string v="Ravi had been saying that"; string w="he had had he"; solve(u); solve(v); solve(w); return 0; }
# Python program to find first repeated word in a stringdef solve(s): mp = {} # to store occurrences of word t = "" ans = "" # traversing from back makes sure that we get the word which repeats first as ans for i in range(len(s) - 1,-1,-1): # if char present , then add that in temp word string t if(s[i] != ' '): t += s[i] # if space is there then this word t needs to stored in map else: # if that string t has occurred previously then it is a possible ans if(t in mp): ans = t else: mp[t] = 1 # set t as empty for again new word t = "" # first word like "he" needs to be mapped if(t in mp): ans=t if(ans!=""): # reverse ans string as it has characters in reverse order ans = ans[::-1] print(ans) else: print("No Repetition") # driver codeu = "Ravi had been saying that he had been there"v = "Ravi had been saying that"w = "he had had he"solve(u)solve(v)solve(w) # This code is contributed by shinjanpatra
<script>// JavaScript program to find first repeated word in a string function solve(s){ let mp = new Map(); // to store occurrences of word let t = ""; let ans = ""; // traversing from back makes sure that we get the word which repeats first as ans for(let i = s.length - 1; i >= 0; i--) { // if char present , then add that in temp word string t if(s[i] != ' ') { t += s[i]; } // if space is there then this word t needs to stored in map else { // if that string t has occurred previously then it is a possible ans if(mp.has(t)) ans = t; else mp.set(t, 1) // set t as empty for again new word t = ""; } } // first word like "he" needs to be mapped if(mp.has(t)) ans=t; if(ans!="") { // reverse ans string as it has characters in reverse order ans = [...ans].reverse().join(""); document.write(ans); } else document.write("No Repetition");} // driver codeconst u = "Ravi had been saying that he had been there";const v = "Ravi had been saying that";const w = "he had had he";solve(u);solve(v);solve(w); // This code is contributed by shinjanpatra</script>
had
No Repetition
he
Another Approach: The idea is to tokenize the string and store each word and its count in hashmap. Then traverse the string again and for each word of string, check its count in created hashmap.
CPP
Java
// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring findFirstRepeated(string s){ // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break istringstream iss(s); string token; // hashmap for storing word and its count // in sentence unordered_map<string, int> setOfWords; // store all the words of string // and the count of word in hashmap while (getline(iss, token, ' ')) { if (setOfWords.find(token) != setOfWords.end()) setOfWords[token] += 1; // word exists else // insert new word to set setOfWords.insert(make_pair(token, 1)); } // traverse again from first word of string s // to check if count of word is greater than 1 // either take a new stream or store the words // in vector of strings in previous loop istringstream iss2(s); while (getline(iss2, token, ' ')) { int count = setOfWords[token]; if (count > 1) { return token; } } return "NoRepetition";} // driver programint main(){ string s("Ravi had been saying that he had been there"); string firstWord = findFirstRepeated(s); if (firstWord != "NoRepetition") cout << "First repeated word :: " << firstWord << endl; else cout << "No Repetitionn"; return 0;}
// Java program for finding first repeated// word in a stringimport java.util.*; class GFG{ // returns first repeated word static String findFirstRepeated(String s) { // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break String token[] = s.split(" "); // hashmap for storing word and its count // in sentence HashMap<String, Integer> setOfWords = new HashMap<String, Integer>(); // store all the words of string // and the count of word in hashmap for (int i=0; i<token.length; i++) { if (setOfWords.containsKey(token[i])) setOfWords.put(token[i], setOfWords.get(token[i]) + 1); // word exists else // insert new word to set setOfWords.put(token[i], 1); } // traverse again from first word of string s // to check if count of word is greater than 1 // either take a new stream or store the words // in vector of strings in previous loop for (int i=0; i<token.length; i++) { int count = setOfWords.get(token[i]); if (count > 1) { return token[i]; } } return "NoRepetition"; } // driver program public static void main(String args[]) { String s = "Ravi had been saying that he had been there"; String firstWord = findFirstRepeated(s); if (!firstWord.equals("NoRepetition")) System.out.println("First repeated word :: " + firstWord); else System.out.println("No Repetitionn"); }}
First repeated word :: had
As all the words in a sentence are separated by spaces.
We have to split the sentence by spaces using split().
We split all the words by spaces and store them in a list.
Use Counter function to count frequency of words
Traverse the list and check if any word has frequency greater than 1
If it is present then print the word and break the loop
Below is the implementation:
Python3
# Python program for the above approachfrom collections import Counter # Python program to find the first# repeated character in a stringdef firstRepeatedWord(sentence): # splitting the string lis = list(sentence.split(" ")) # Calculating frequency of every word frequency = Counter(lis) # Traversing the list of words for i in lis: # checking if frequency is greater than 1 if(frequency[i] > 1): # return the word return i # Driver codesentence = "Vikram had been saying that he had been there"print(firstRepeatedWord(sentence))# this code is contributed by vikkycirus
had
Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is number of words, we can stop when the count of any word becomes 2. That is no need to iterate through all the words in string.
Let’s say our first repeated word is present at Mth index, then
By using this approach, space and time complexity reduced from O(N) to O(M).
Where,
N: number of words in a string.
M: Index at which first repeating word is present
However, Worst case( When no word is being repeated or the word being repeated is present at last) time and space complexity will still be O(N).
Steps:
Create a default dictionary with an initial value of 0, to keep track count of words.
Iterate through each word in a sentence and increment the count of that word by 1.
If (count of the word) > 1, return the word.
If the count of none of the words is greater than 1 then that is we are outside our loop then return “No word is being repeated”.
Python3
Javascript
# Import defaultdict from Collections modulefrom collections import defaultdict def first_repeating_word(s): # Creating a defaultdict with # default values as 0. # Every word will have an # initial count of 0 word_count = defaultdict(lambda: 0) # Iterating through all words in string. for i in s.split(): # Increment the word count of # the word we encounter by 1 word_count[i] += 1 # If word_count of current word # is more than 1, we got our answer, return it. if word_count[i] > 1: return i # If program has reached here that # means no word is being repeated return 'No word is being repeated' # Driver Codeif __name__ == '__main__': s = "Ravi had been saying that he had been there" print(first_repeating_word(s)) # This code is contributed by Anurag Mishra
<script> function first_repeating_word(s){ // Creating a defaultdict with // default values as 0. // Every word will have an // initial count of 0 let word_count = new Map() // Iterating through all words in string. for(let i of s.split(' ')){ // Increment the word count of // the word we encounter by 1 if(word_count.has(i)){ word_count.set(i,word_count.get(i) + 1); } else word_count.set(i,1); // If word_count of current word // is more than 1, we got our answer, return it. if(word_count.get(i) > 1) return i } // If program has reached here that // means no word is being repeated return 'No word is being repeated'} // Driver Codelet s = "Ravi had been saying that he had been there"document.write(first_repeating_word(s)) // This code is contributed by shinjanpatra </script>
had
Time complexity: O(M)
Space Complexity: O(M)
Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is a number of words, we can just store words in a HashSet, and as soon as we reach a word that is already present in the HashSet we can return.
C++
Java
// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring findFirstRepeated(string s){ // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break istringstream iss(s); string token; // hashset for storing word and its count // in sentence set<string> setOfWords; // store all the words of string // and the count of word in hashset while (getline(iss, token, ' ')) { // if word exists return if (setOfWords.find(token) != setOfWords.end()) { return token; } // insert new word to set setOfWords.insert(token); } return "NoRepetition";} // driver programint main(){ string s("Ravi had been saying that he had been there"); string firstWord = findFirstRepeated(s); if (firstWord != "NoRepetition") cout << "First repeated word :: " << firstWord << endl; else cout << "No Repetitionn"; return 0;}
// Java program for finding first repeated// word in a stringimport java.util.*; public class GFG{ // returns first repeated word static String findFirstRepeated(String s) { // break string into tokens String token[] = s.split(" "); // hashset for storing words HashSet<String> set = new HashSet<String>(); // store the words of string in hashset for(int i=0; i<token.length; i++){ // if word exists return if(set.contains(token[i])){ return token[i]; } // insert new word to set set.add(token[i]); } return "NoRepetition"; } // driver program public static void main(String args[]) { String s = "Ravi had been saying that he had been there"; String firstWord = findFirstRepeated(s); if (!firstWord.equals("NoRepetition")) System.out.println("First repeated word :: " + firstWord); else System.out.println("No Repetitionn"); }}
First repeated word :: had
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vikkycirus
anurag2311
adityapande88
nayanmanojgupta
varshagumber28
shinjanpatra
surinderdawra388
rkbhola5
Amazon
cpp-stringstream
cpp-unordered_map
Goldman Sachs
Strings
Amazon
Goldman Sachs
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different methods to reverse a string in C/C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Array of Strings in C++ (5 Different Ways to Create)
Reverse words in a given string
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 24934,
"s": 24906,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 24999,
"s": 24934,
"text": "Given a string, Find the 1st repeated word in a stringExamples: "
},
{
"code": null,
"e": 25163,
"s": 24999,
"text": "Input : \"Ravi had been saying that he had been there\"\nOutput : had\n\nInput : \"Ravi had been saying that\"\nOutput : No Repetition\n\nInput : \"he had had he\"\nOutput : he"
},
{
"code": null,
"e": 25265,
"s": 25163,
"text": "question source : https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-internship/"
},
{
"code": null,
"e": 25476,
"s": 25265,
"text": "Simple Approach : Start iterating from back and for every new word , store it in unordered map . For every word which has occurred more than one , update ans to be that word , at last reverse ans and print it."
},
{
"code": null,
"e": 25480,
"s": 25476,
"text": "C++"
},
{
"code": null,
"e": 25488,
"s": 25480,
"text": "Python3"
},
{
"code": null,
"e": 25499,
"s": 25488,
"text": "Javascript"
},
{
"code": "// Cpp program to find first repeated word in a string#include<bits/stdc++.h>using namespace std;void solve(string s){ unordered_map<string,int> mp; // to store occurrences of word string t=\"\",ans=\"\"; // traversing from back makes sure that we get the word which repeats first as ans for(int i=s.length()-1;i>=0;i--) { // if char present , then add that in temp word string t if(s[i]!=' ') { t+=s[i]; } // if space is there then this word t needs to stored in map else { mp[t]++; // if that string t has occurred previously then it is a possible ans if(mp[t]>1) ans=t; // set t as empty for again new word t=\"\"; } } // first word like \"he\" needs to be mapped mp[t]++; if(mp[t]>1) ans=t; if(ans!=\"\") { // reverse ans string as it has characters in reverse order reverse(ans.begin(),ans.end()); cout<<ans<<'\\n'; } else cout<<\"No Repetition\\n\";}int main(){ string u=\"Ravi had been saying that he had been there\"; string v=\"Ravi had been saying that\"; string w=\"he had had he\"; solve(u); solve(v); solve(w); return 0; }",
"e": 26840,
"s": 25499,
"text": null
},
{
"code": "# Python program to find first repeated word in a stringdef solve(s): mp = {} # to store occurrences of word t = \"\" ans = \"\" # traversing from back makes sure that we get the word which repeats first as ans for i in range(len(s) - 1,-1,-1): # if char present , then add that in temp word string t if(s[i] != ' '): t += s[i] # if space is there then this word t needs to stored in map else: # if that string t has occurred previously then it is a possible ans if(t in mp): ans = t else: mp[t] = 1 # set t as empty for again new word t = \"\" # first word like \"he\" needs to be mapped if(t in mp): ans=t if(ans!=\"\"): # reverse ans string as it has characters in reverse order ans = ans[::-1] print(ans) else: print(\"No Repetition\") # driver codeu = \"Ravi had been saying that he had been there\"v = \"Ravi had been saying that\"w = \"he had had he\"solve(u)solve(v)solve(w) # This code is contributed by shinjanpatra",
"e": 28017,
"s": 26840,
"text": null
},
{
"code": "<script>// JavaScript program to find first repeated word in a string function solve(s){ let mp = new Map(); // to store occurrences of word let t = \"\"; let ans = \"\"; // traversing from back makes sure that we get the word which repeats first as ans for(let i = s.length - 1; i >= 0; i--) { // if char present , then add that in temp word string t if(s[i] != ' ') { t += s[i]; } // if space is there then this word t needs to stored in map else { // if that string t has occurred previously then it is a possible ans if(mp.has(t)) ans = t; else mp.set(t, 1) // set t as empty for again new word t = \"\"; } } // first word like \"he\" needs to be mapped if(mp.has(t)) ans=t; if(ans!=\"\") { // reverse ans string as it has characters in reverse order ans = [...ans].reverse().join(\"\"); document.write(ans); } else document.write(\"No Repetition\");} // driver codeconst u = \"Ravi had been saying that he had been there\";const v = \"Ravi had been saying that\";const w = \"he had had he\";solve(u);solve(v);solve(w); // This code is contributed by shinjanpatra</script>",
"e": 29370,
"s": 28017,
"text": null
},
{
"code": null,
"e": 29391,
"s": 29370,
"text": "had\nNo Repetition\nhe"
},
{
"code": null,
"e": 29590,
"s": 29394,
"text": "Another Approach: The idea is to tokenize the string and store each word and its count in hashmap. Then traverse the string again and for each word of string, check its count in created hashmap. "
},
{
"code": null,
"e": 29594,
"s": 29590,
"text": "CPP"
},
{
"code": null,
"e": 29599,
"s": 29594,
"text": "Java"
},
{
"code": "// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring findFirstRepeated(string s){ // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break istringstream iss(s); string token; // hashmap for storing word and its count // in sentence unordered_map<string, int> setOfWords; // store all the words of string // and the count of word in hashmap while (getline(iss, token, ' ')) { if (setOfWords.find(token) != setOfWords.end()) setOfWords[token] += 1; // word exists else // insert new word to set setOfWords.insert(make_pair(token, 1)); } // traverse again from first word of string s // to check if count of word is greater than 1 // either take a new stream or store the words // in vector of strings in previous loop istringstream iss2(s); while (getline(iss2, token, ' ')) { int count = setOfWords[token]; if (count > 1) { return token; } } return \"NoRepetition\";} // driver programint main(){ string s(\"Ravi had been saying that he had been there\"); string firstWord = findFirstRepeated(s); if (firstWord != \"NoRepetition\") cout << \"First repeated word :: \" << firstWord << endl; else cout << \"No Repetitionn\"; return 0;}",
"e": 31098,
"s": 29599,
"text": null
},
{
"code": "// Java program for finding first repeated// word in a stringimport java.util.*; class GFG{ // returns first repeated word static String findFirstRepeated(String s) { // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break String token[] = s.split(\" \"); // hashmap for storing word and its count // in sentence HashMap<String, Integer> setOfWords = new HashMap<String, Integer>(); // store all the words of string // and the count of word in hashmap for (int i=0; i<token.length; i++) { if (setOfWords.containsKey(token[i])) setOfWords.put(token[i], setOfWords.get(token[i]) + 1); // word exists else // insert new word to set setOfWords.put(token[i], 1); } // traverse again from first word of string s // to check if count of word is greater than 1 // either take a new stream or store the words // in vector of strings in previous loop for (int i=0; i<token.length; i++) { int count = setOfWords.get(token[i]); if (count > 1) { return token[i]; } } return \"NoRepetition\"; } // driver program public static void main(String args[]) { String s = \"Ravi had been saying that he had been there\"; String firstWord = findFirstRepeated(s); if (!firstWord.equals(\"NoRepetition\")) System.out.println(\"First repeated word :: \" + firstWord); else System.out.println(\"No Repetitionn\"); }}",
"e": 32836,
"s": 31098,
"text": null
},
{
"code": null,
"e": 32863,
"s": 32836,
"text": "First repeated word :: had"
},
{
"code": null,
"e": 32919,
"s": 32863,
"text": "As all the words in a sentence are separated by spaces."
},
{
"code": null,
"e": 32974,
"s": 32919,
"text": "We have to split the sentence by spaces using split()."
},
{
"code": null,
"e": 33033,
"s": 32974,
"text": "We split all the words by spaces and store them in a list."
},
{
"code": null,
"e": 33082,
"s": 33033,
"text": "Use Counter function to count frequency of words"
},
{
"code": null,
"e": 33151,
"s": 33082,
"text": "Traverse the list and check if any word has frequency greater than 1"
},
{
"code": null,
"e": 33207,
"s": 33151,
"text": "If it is present then print the word and break the loop"
},
{
"code": null,
"e": 33236,
"s": 33207,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 33244,
"s": 33236,
"text": "Python3"
},
{
"code": "# Python program for the above approachfrom collections import Counter # Python program to find the first# repeated character in a stringdef firstRepeatedWord(sentence): # splitting the string lis = list(sentence.split(\" \")) # Calculating frequency of every word frequency = Counter(lis) # Traversing the list of words for i in lis: # checking if frequency is greater than 1 if(frequency[i] > 1): # return the word return i # Driver codesentence = \"Vikram had been saying that he had been there\"print(firstRepeatedWord(sentence))# this code is contributed by vikkycirus",
"e": 33896,
"s": 33244,
"text": null
},
{
"code": null,
"e": 33900,
"s": 33896,
"text": "had"
},
{
"code": null,
"e": 34143,
"s": 33900,
"text": "Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is number of words, we can stop when the count of any word becomes 2. That is no need to iterate through all the words in string."
},
{
"code": null,
"e": 34207,
"s": 34143,
"text": "Let’s say our first repeated word is present at Mth index, then"
},
{
"code": null,
"e": 34284,
"s": 34207,
"text": "By using this approach, space and time complexity reduced from O(N) to O(M)."
},
{
"code": null,
"e": 34291,
"s": 34284,
"text": "Where,"
},
{
"code": null,
"e": 34323,
"s": 34291,
"text": "N: number of words in a string."
},
{
"code": null,
"e": 34373,
"s": 34323,
"text": "M: Index at which first repeating word is present"
},
{
"code": null,
"e": 34518,
"s": 34373,
"text": "However, Worst case( When no word is being repeated or the word being repeated is present at last) time and space complexity will still be O(N)."
},
{
"code": null,
"e": 34525,
"s": 34518,
"text": "Steps:"
},
{
"code": null,
"e": 34611,
"s": 34525,
"text": "Create a default dictionary with an initial value of 0, to keep track count of words."
},
{
"code": null,
"e": 34694,
"s": 34611,
"text": "Iterate through each word in a sentence and increment the count of that word by 1."
},
{
"code": null,
"e": 34739,
"s": 34694,
"text": "If (count of the word) > 1, return the word."
},
{
"code": null,
"e": 34869,
"s": 34739,
"text": "If the count of none of the words is greater than 1 then that is we are outside our loop then return “No word is being repeated”."
},
{
"code": null,
"e": 34877,
"s": 34869,
"text": "Python3"
},
{
"code": null,
"e": 34888,
"s": 34877,
"text": "Javascript"
},
{
"code": "# Import defaultdict from Collections modulefrom collections import defaultdict def first_repeating_word(s): # Creating a defaultdict with # default values as 0. # Every word will have an # initial count of 0 word_count = defaultdict(lambda: 0) # Iterating through all words in string. for i in s.split(): # Increment the word count of # the word we encounter by 1 word_count[i] += 1 # If word_count of current word # is more than 1, we got our answer, return it. if word_count[i] > 1: return i # If program has reached here that # means no word is being repeated return 'No word is being repeated' # Driver Codeif __name__ == '__main__': s = \"Ravi had been saying that he had been there\" print(first_repeating_word(s)) # This code is contributed by Anurag Mishra",
"e": 35751,
"s": 34888,
"text": null
},
{
"code": "<script> function first_repeating_word(s){ // Creating a defaultdict with // default values as 0. // Every word will have an // initial count of 0 let word_count = new Map() // Iterating through all words in string. for(let i of s.split(' ')){ // Increment the word count of // the word we encounter by 1 if(word_count.has(i)){ word_count.set(i,word_count.get(i) + 1); } else word_count.set(i,1); // If word_count of current word // is more than 1, we got our answer, return it. if(word_count.get(i) > 1) return i } // If program has reached here that // means no word is being repeated return 'No word is being repeated'} // Driver Codelet s = \"Ravi had been saying that he had been there\"document.write(first_repeating_word(s)) // This code is contributed by shinjanpatra </script>",
"e": 36651,
"s": 35751,
"text": null
},
{
"code": null,
"e": 36655,
"s": 36651,
"text": "had"
},
{
"code": null,
"e": 36677,
"s": 36655,
"text": "Time complexity: O(M)"
},
{
"code": null,
"e": 36700,
"s": 36677,
"text": "Space Complexity: O(M)"
},
{
"code": null,
"e": 36958,
"s": 36700,
"text": "Instead of counting a number of occurrences of each word which will have O(N) time and space complexity, where N is a number of words, we can just store words in a HashSet, and as soon as we reach a word that is already present in the HashSet we can return."
},
{
"code": null,
"e": 36962,
"s": 36958,
"text": "C++"
},
{
"code": null,
"e": 36967,
"s": 36962,
"text": "Java"
},
{
"code": "// CPP program for finding first repeated// word in a string#include <bits/stdc++.h>using namespace std; // returns first repeated wordstring findFirstRepeated(string s){ // break string into tokens // and then each string into set // if a word appeared before appears // again, return the word and break istringstream iss(s); string token; // hashset for storing word and its count // in sentence set<string> setOfWords; // store all the words of string // and the count of word in hashset while (getline(iss, token, ' ')) { // if word exists return if (setOfWords.find(token) != setOfWords.end()) { return token; } // insert new word to set setOfWords.insert(token); } return \"NoRepetition\";} // driver programint main(){ string s(\"Ravi had been saying that he had been there\"); string firstWord = findFirstRepeated(s); if (firstWord != \"NoRepetition\") cout << \"First repeated word :: \" << firstWord << endl; else cout << \"No Repetitionn\"; return 0;}",
"e": 38055,
"s": 36967,
"text": null
},
{
"code": "// Java program for finding first repeated// word in a stringimport java.util.*; public class GFG{ // returns first repeated word static String findFirstRepeated(String s) { // break string into tokens String token[] = s.split(\" \"); // hashset for storing words HashSet<String> set = new HashSet<String>(); // store the words of string in hashset for(int i=0; i<token.length; i++){ // if word exists return if(set.contains(token[i])){ return token[i]; } // insert new word to set set.add(token[i]); } return \"NoRepetition\"; } // driver program public static void main(String args[]) { String s = \"Ravi had been saying that he had been there\"; String firstWord = findFirstRepeated(s); if (!firstWord.equals(\"NoRepetition\")) System.out.println(\"First repeated word :: \" + firstWord); else System.out.println(\"No Repetitionn\"); }}",
"e": 39142,
"s": 38055,
"text": null
},
{
"code": null,
"e": 39169,
"s": 39142,
"text": "First repeated word :: had"
},
{
"code": null,
"e": 39595,
"s": 39169,
"text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39606,
"s": 39595,
"text": "vikkycirus"
},
{
"code": null,
"e": 39617,
"s": 39606,
"text": "anurag2311"
},
{
"code": null,
"e": 39631,
"s": 39617,
"text": "adityapande88"
},
{
"code": null,
"e": 39647,
"s": 39631,
"text": "nayanmanojgupta"
},
{
"code": null,
"e": 39662,
"s": 39647,
"text": "varshagumber28"
},
{
"code": null,
"e": 39675,
"s": 39662,
"text": "shinjanpatra"
},
{
"code": null,
"e": 39692,
"s": 39675,
"text": "surinderdawra388"
},
{
"code": null,
"e": 39701,
"s": 39692,
"text": "rkbhola5"
},
{
"code": null,
"e": 39708,
"s": 39701,
"text": "Amazon"
},
{
"code": null,
"e": 39725,
"s": 39708,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 39743,
"s": 39725,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 39757,
"s": 39743,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 39765,
"s": 39757,
"text": "Strings"
},
{
"code": null,
"e": 39772,
"s": 39765,
"text": "Amazon"
},
{
"code": null,
"e": 39786,
"s": 39772,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 39794,
"s": 39786,
"text": "Strings"
},
{
"code": null,
"e": 39892,
"s": 39794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39901,
"s": 39892,
"text": "Comments"
},
{
"code": null,
"e": 39914,
"s": 39901,
"text": "Old Comments"
},
{
"code": null,
"e": 39961,
"s": 39914,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 40018,
"s": 39961,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 40093,
"s": 40018,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 40129,
"s": 40093,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 40165,
"s": 40129,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 40203,
"s": 40165,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 40233,
"s": 40203,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 40286,
"s": 40233,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 40318,
"s": 40286,
"text": "Reverse words in a given string"
}
]
|
Create an ordered list in HTML | The HTML <ol> tag is used for creating an ordered list. You can try to run the following code to create an ordered list using the <ol> tag −
The HTML <ol> tag supports the following additional attributes −
You can try to run the following code to create an ordered list using the <ol> tag −
<!DOCTYPE html>
<html>
<head>
<title>HTML ol Tag</title>
</head>
<body>
<p>Programming Languages:</p>
<ol>
<li>Java</li>
<li>C++</li>
<li>C</li>
</ol>
</body>
</html> | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "The HTML <ol> tag is used for creating an ordered list. You can try to run the following code to create an ordered list using the <ol> tag −"
},
{
"code": null,
"e": 1268,
"s": 1203,
"text": "The HTML <ol> tag supports the following additional attributes −"
},
{
"code": null,
"e": 1353,
"s": 1268,
"text": "You can try to run the following code to create an ordered list using the <ol> tag −"
},
{
"code": null,
"e": 1583,
"s": 1353,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML ol Tag</title>\n </head>\n <body>\n <p>Programming Languages:</p>\n <ol>\n <li>Java</li>\n <li>C++</li>\n <li>C</li>\n </ol>\n </body>\n</html>"
}
]
|
Python | Pandas series.cummax() to find Cumulative maximum of a series - GeeksforGeeks | 20 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 Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as input series and every element is equal to the greater one between current element and previous element.
Syntax: Series.cummax(axis=None, skipna=True)
Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation.skipna: Skips NaN addition for elements after the very next one if True.
Return type: Series
Example #1:In this example, a series is created from a Python list. The list also contains a Null value and the skipna parameter is kept default, that is True.
# importing pandas module import pandas as pd # importing numpy module import numpy as np # making list of values values = [3, 4, np.nan, 7, 2, 0] # making series from list series = pd.Series(values) # calling method cummax = series.cummax() # display cummax
Output:
0 3.0
1 4.0
2 NaN
3 7.0
4 7.0
5 7.0
dtype: float64
Explanation: Cummax is comparison of current value with previous value. The first element is always equal to first of caller series.
3
4 (4>3)
NaN (Since NaN cannot be compared to integer values)
7 (7>4)
7 (7>2)
7 (7>0)
Example #2: Keeping skipna = False
In this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be compared every time on it’s occurrence.
# importing pandas module import pandas as pd # importing numpy module import numpy as np # making list of values values = [9, 4, 33, np.nan, 0, 1, 76, 5] # making series from list series = pd.Series(values) # calling method cummax = series.cummax(skipna = False) # display cummax
Output:
0 9.0
1 9.0
2 33.0
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
dtype: float64
Explanation: Just like in the above example, maximum of current and previous values were stored at every position until NaN occurred. Since NaN compared with anything returns NaN and skipna parameter is kept False, the cumulative maximum after its occurrence is NaN due to comparison of all the values with NaN.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24230,
"s": 24202,
"text": "\n20 Nov, 2018"
},
{
"code": null,
"e": 24444,
"s": 24230,
"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": 24684,
"s": 24444,
"text": "Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as input series and every element is equal to the greater one between current element and previous element."
},
{
"code": null,
"e": 24730,
"s": 24684,
"text": "Syntax: Series.cummax(axis=None, skipna=True)"
},
{
"code": null,
"e": 24901,
"s": 24730,
"text": "Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation.skipna: Skips NaN addition for elements after the very next one if True."
},
{
"code": null,
"e": 24921,
"s": 24901,
"text": "Return type: Series"
},
{
"code": null,
"e": 25081,
"s": 24921,
"text": "Example #1:In this example, a series is created from a Python list. The list also contains a Null value and the skipna parameter is kept default, that is True."
},
{
"code": "# importing pandas module import pandas as pd # importing numpy module import numpy as np # making list of values values = [3, 4, np.nan, 7, 2, 0] # making series from list series = pd.Series(values) # calling method cummax = series.cummax() # display cummax",
"e": 25360,
"s": 25081,
"text": null
},
{
"code": null,
"e": 25368,
"s": 25360,
"text": "Output:"
},
{
"code": null,
"e": 25437,
"s": 25368,
"text": "0 3.0\n1 4.0\n2 NaN\n3 7.0\n4 7.0\n5 7.0\ndtype: float64"
},
{
"code": null,
"e": 25570,
"s": 25437,
"text": "Explanation: Cummax is comparison of current value with previous value. The first element is always equal to first of caller series."
},
{
"code": null,
"e": 25662,
"s": 25570,
"text": "3\n4 (4>3)\nNaN (Since NaN cannot be compared to integer values)\n7 (7>4)\n7 (7>2)\n7 (7>0)\n"
},
{
"code": null,
"e": 25698,
"s": 25662,
"text": " Example #2: Keeping skipna = False"
},
{
"code": null,
"e": 25898,
"s": 25698,
"text": "In this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be compared every time on it’s occurrence."
},
{
"code": "# importing pandas module import pandas as pd # importing numpy module import numpy as np # making list of values values = [9, 4, 33, np.nan, 0, 1, 76, 5] # making series from list series = pd.Series(values) # calling method cummax = series.cummax(skipna = False) # display cummax ",
"e": 26200,
"s": 25898,
"text": null
},
{
"code": null,
"e": 26208,
"s": 26200,
"text": "Output:"
},
{
"code": null,
"e": 26303,
"s": 26208,
"text": "0 9.0\n1 9.0\n2 33.0\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\ndtype: float64"
},
{
"code": null,
"e": 26615,
"s": 26303,
"text": "Explanation: Just like in the above example, maximum of current and previous values were stored at every position until NaN occurred. Since NaN compared with anything returns NaN and skipna parameter is kept False, the cumulative maximum after its occurrence is NaN due to comparison of all the values with NaN."
},
{
"code": null,
"e": 26636,
"s": 26615,
"text": "Python pandas-series"
},
{
"code": null,
"e": 26665,
"s": 26636,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 26679,
"s": 26665,
"text": "Python-pandas"
},
{
"code": null,
"e": 26686,
"s": 26679,
"text": "Python"
},
{
"code": null,
"e": 26784,
"s": 26686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26793,
"s": 26784,
"text": "Comments"
},
{
"code": null,
"e": 26806,
"s": 26793,
"text": "Old Comments"
},
{
"code": null,
"e": 26824,
"s": 26806,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26859,
"s": 26824,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26881,
"s": 26859,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26913,
"s": 26881,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26943,
"s": 26913,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26985,
"s": 26943,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27028,
"s": 26985,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27054,
"s": 27028,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27098,
"s": 27054,
"text": "Reading and Writing to text files in Python"
}
]
|
Solidity – While, Do-While, and For Loop | 11 May, 2022
Loops are used when we have to perform an action over and over again. While writing a contract there may be a situation when we have to do some action repeatedly, In this situation, loops are implemented to reduce the number of lines of the statements. Solidity supports following loops too ease down the programming pressure.
This is the most basic loop in solidity, Its purpose is to execute a statement or block of statements repeatedly as far as the condition is true and once the condition becomes false the loop terminates.
Syntax:
while (condition) {
statement or block of code to be executed if the condition is True
}
Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop.
Solidity
// Solidity program to // demonstrate the use// of 'While loop'pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring a dynamic array uint[] data; // Declaring state variable uint8 j = 0; // Defining a function to // demonstrate While loop' function loop( ) public returns(uint[] memory){ while(j < 5) { j++; data.push(j); } return data; }}
Output :
This loop is very similar to while loop except that there is a condition check which happens at the end of loop i.e. the loop will always execute at least one time even if the condition is false.
Syntax:
do
{
block of statements to be executed
} while (condition);
Example: In the below example, the contract Types demonstrate the execution of a do-while loop and how an array can be initialized using the do-while loop.
Solidity
// Solidity program to // demonstrate the use of// 'Do-While loop'pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring a dynamic array uint[] data; // Declaring state variable uint8 j = 0; // Defining function to demonstrate // 'Do-While loop' function loop( ) public returns(uint[] memory){ do{ j++; data.push(j); }while(j < 5) ; return data; }}
Output :
This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The first one is ‘loop initialization’ where the iterator is initialized with starting value, this statement is executed before the loop starts. Second is ‘test statement’ which checks whether the condition is true or not, if the condition is true the loop executes else terminates. The third one is the ‘iteration statement’ where the iterator is increased or decreased. Below is the syntax of for loop :
Syntax:
for (initialization; test condition; iteration statement) {
statement or block of code to be executed if the condition is True
}
Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop.
Solidity
// Solidity program to // demonstrate the use// of 'For loop'pragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Defining a function // to demonstrate 'For loop' function loop( ) public returns(uint[] memory){ for(uint i=0; i<5; i++){ data.push(i); } return data; }}
Output :
Solidity Control-Flow
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "Loops are used when we have to perform an action over and over again. While writing a contract there may be a situation when we have to do some action repeatedly, In this situation, loops are implemented to reduce the number of lines of the statements. Solidity supports following loops too ease down the programming pressure."
},
{
"code": null,
"e": 559,
"s": 355,
"text": "This is the most basic loop in solidity, Its purpose is to execute a statement or block of statements repeatedly as far as the condition is true and once the condition becomes false the loop terminates. "
},
{
"code": null,
"e": 567,
"s": 559,
"text": "Syntax:"
},
{
"code": null,
"e": 661,
"s": 567,
"text": "while (condition) {\n statement or block of code to be executed if the condition is True\n}\n"
},
{
"code": null,
"e": 811,
"s": 661,
"text": "Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop."
},
{
"code": null,
"e": 820,
"s": 811,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate the use// of 'While loop'pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring a dynamic array uint[] data; // Declaring state variable uint8 j = 0; // Defining a function to // demonstrate While loop' function loop( ) public returns(uint[] memory){ while(j < 5) { j++; data.push(j); } return data; }}",
"e": 1256,
"s": 820,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1256,
"text": "Output : "
},
{
"code": null,
"e": 1464,
"s": 1267,
"text": "This loop is very similar to while loop except that there is a condition check which happens at the end of loop i.e. the loop will always execute at least one time even if the condition is false. "
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Syntax:"
},
{
"code": null,
"e": 1538,
"s": 1472,
"text": "do \n{\n block of statements to be executed\n} while (condition);\n"
},
{
"code": null,
"e": 1694,
"s": 1538,
"text": "Example: In the below example, the contract Types demonstrate the execution of a do-while loop and how an array can be initialized using the do-while loop."
},
{
"code": null,
"e": 1703,
"s": 1694,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate the use of// 'Do-While loop'pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring a dynamic array uint[] data; // Declaring state variable uint8 j = 0; // Defining function to demonstrate // 'Do-While loop' function loop( ) public returns(uint[] memory){ do{ j++; data.push(j); }while(j < 5) ; return data; }}",
"e": 2144,
"s": 1703,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2144,
"text": "Output : "
},
{
"code": null,
"e": 2661,
"s": 2155,
"text": "This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The first one is ‘loop initialization’ where the iterator is initialized with starting value, this statement is executed before the loop starts. Second is ‘test statement’ which checks whether the condition is true or not, if the condition is true the loop executes else terminates. The third one is the ‘iteration statement’ where the iterator is increased or decreased. Below is the syntax of for loop :"
},
{
"code": null,
"e": 2669,
"s": 2661,
"text": "Syntax:"
},
{
"code": null,
"e": 2806,
"s": 2669,
"text": "for (initialization; test condition; iteration statement) {\n statement or block of code to be executed if the condition is True\n}\n"
},
{
"code": null,
"e": 2956,
"s": 2806,
"text": "Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop."
},
{
"code": null,
"e": 2965,
"s": 2956,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate the use// of 'For loop'pragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring a dynamic array uint[] data; // Defining a function // to demonstrate 'For loop' function loop( ) public returns(uint[] memory){ for(uint i=0; i<5; i++){ data.push(i); } return data; }}",
"e": 3342,
"s": 2965,
"text": null
},
{
"code": null,
"e": 3353,
"s": 3342,
"text": "Output : "
},
{
"code": null,
"e": 3375,
"s": 3353,
"text": "Solidity Control-Flow"
},
{
"code": null,
"e": 3386,
"s": 3375,
"text": "Blockchain"
},
{
"code": null,
"e": 3395,
"s": 3386,
"text": "Solidity"
}
]
|
How to handle the modal closing event in Twitter Bootstrap? | 03 Jun, 2020
Modal Closing Event in Twitter Bootstrap | Set 1
Prerequisite Knowledge: Bootstrap 4 | Modal
Twitter Bootstrap’s modal class offer a few events that are fired at the standard Bootstrap modal class. Bootstrap Modals offer a lightweight, multi-purpose JavaScript popup that is customizable and responsive. They can be used to display alert popups, videos, and images in a website. Bootstrap Modals are divided into three primary sections: header, body, and footer.
The Bootstrap Events are: show.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal etc. Out of all these events, we are interested in the hide.bs.modal and hidden.bs.modal events.
hide.bs.modal: This event is fired immediately when the hide instance method has been called.
hidden.bs.modal: This event is fired when the modal has finished being hidden from the user and will then wait for CSS transitions to complete.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- link to Bootstrap CSS CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title> Modal closing event in Bootstrap </title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#gfgModal"> Launch Modal </button> <!-- Modal --> <div class="modal fade" id="gfgModal" tabindex="-1" role="dialog" aria-labelledby="gfgModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title" id="gfgModalLabel" style="color:green;"> GeeksforGeeks </h6> <!-- The title of the modal --> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- The content inside the modal box --> <p> Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formating style, coding style, and try to make your close to them. </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <!-- The close button in the bottom of the modal --> <button type="button" class="btn btn-primary"> okay </button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- 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> <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> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> </center> <!-- Modal JQUERY logic --> <script type="text/javascript"> $('#gfgModal').on('hidden.bs.modal', function (e) { // Fire a function in the console console.log('Function executed when gfgModal closed'); // Alert the user alert('Alert fired when gfgModal closed') }) </script></body> </html>
Output:
Before Clicking the Button:
After Clicking the Button:
On closing modal, observe the console:
So when modal is closed, we successfully handle it using
Fire an output in the console
Alert the user
Bootstrap-4
Bootstrap-Misc
Bootstrap
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
How to Add Image into Dropdown List for each items ?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 103,
"s": 54,
"text": "Modal Closing Event in Twitter Bootstrap | Set 1"
},
{
"code": null,
"e": 147,
"s": 103,
"text": "Prerequisite Knowledge: Bootstrap 4 | Modal"
},
{
"code": null,
"e": 517,
"s": 147,
"text": "Twitter Bootstrap’s modal class offer a few events that are fired at the standard Bootstrap modal class. Bootstrap Modals offer a lightweight, multi-purpose JavaScript popup that is customizable and responsive. They can be used to display alert popups, videos, and images in a website. Bootstrap Modals are divided into three primary sections: header, body, and footer."
},
{
"code": null,
"e": 702,
"s": 517,
"text": "The Bootstrap Events are: show.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal etc. Out of all these events, we are interested in the hide.bs.modal and hidden.bs.modal events."
},
{
"code": null,
"e": 796,
"s": 702,
"text": "hide.bs.modal: This event is fired immediately when the hide instance method has been called."
},
{
"code": null,
"e": 940,
"s": 796,
"text": "hidden.bs.modal: This event is fired when the modal has finished being hidden from the user and will then wait for CSS transitions to complete."
},
{
"code": null,
"e": 949,
"s": 940,
"text": "Example:"
},
{
"code": null,
"e": 954,
"s": 949,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- link to Bootstrap CSS CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <title> Modal closing event in Bootstrap </title> <style> h1, h6 { margin: 2%; } .btn { margin-left: 2%; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#gfgModal\"> Launch Modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"gfgModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"gfgModalLabel\" aria-hidden=\"true\"> <div class=\"modal-dialog\" role=\"document\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h6 class=\"modal-title\" id=\"gfgModalLabel\" style=\"color:green;\"> GeeksforGeeks </h6> <!-- The title of the modal --> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> <!-- The content inside the modal box --> <p> Articles that need little modification/ improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formating style, coding style, and try to make your close to them. </p> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Close</button> <!-- The close button in the bottom of the modal --> <button type=\"button\" class=\"btn btn-primary\"> okay </button> <!-- The save changes button in the bottom of the modal --> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- 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> <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> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> </center> <!-- Modal JQUERY logic --> <script type=\"text/javascript\"> $('#gfgModal').on('hidden.bs.modal', function (e) { // Fire a function in the console console.log('Function executed when gfgModal closed'); // Alert the user alert('Alert fired when gfgModal closed') }) </script></body> </html>",
"e": 5224,
"s": 954,
"text": null
},
{
"code": null,
"e": 5232,
"s": 5224,
"text": "Output:"
},
{
"code": null,
"e": 5260,
"s": 5232,
"text": "Before Clicking the Button:"
},
{
"code": null,
"e": 5287,
"s": 5260,
"text": "After Clicking the Button:"
},
{
"code": null,
"e": 5326,
"s": 5287,
"text": "On closing modal, observe the console:"
},
{
"code": null,
"e": 5383,
"s": 5326,
"text": "So when modal is closed, we successfully handle it using"
},
{
"code": null,
"e": 5413,
"s": 5383,
"text": "Fire an output in the console"
},
{
"code": null,
"e": 5428,
"s": 5413,
"text": "Alert the user"
},
{
"code": null,
"e": 5440,
"s": 5428,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 5455,
"s": 5440,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 5465,
"s": 5455,
"text": "Bootstrap"
},
{
"code": null,
"e": 5472,
"s": 5465,
"text": "JQuery"
},
{
"code": null,
"e": 5489,
"s": 5472,
"text": "Web Technologies"
},
{
"code": null,
"e": 5587,
"s": 5489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5628,
"s": 5587,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5691,
"s": 5628,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 5724,
"s": 5691,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 5771,
"s": 5724,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 5824,
"s": 5771,
"text": "How to Add Image into Dropdown List for each items ?"
},
{
"code": null,
"e": 5870,
"s": 5824,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 5933,
"s": 5870,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 5986,
"s": 5933,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 6020,
"s": 5986,
"text": "jQuery | children() with Examples"
}
]
|
Rotate a Linked List | 24 Jun, 2022
Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in a linked list.
Method-1:To rotate the linked list, we need to change the next pointer of kth node to NULL, the next pointer of the last node should point to previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node. Traverse the list from the beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till the end and store a pointer to the last node also. Finally, change pointers as stated above.
Below image shows how to rotate function works in the code :
C++
C
Java
Python
C#
Javascript
// C++ program to rotate// a linked list counter clock wise #include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.// It doesn't modify the list if// k is greater than or equal to sizevoid rotate(Node** head_ref, int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10->20->30->40->50->60. Node* current = *head_ref; // current will either point to // kth or NULL after this loop. // current will point to node // 40 in the above example int count = 1; while (count < k && current != NULL) { current = current->next; count++; } // If current is NULL, k is greater than // or equal to count of nodes in linked list. // Don't change the list in this case if (current == NULL) return; // current points to kth node. // Store it in a variable. kthNode // points to node 40 in the above example Node* kthNode = current; // current will point to // last node after this loop // current will point to // node 60 in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current->next = *head_ref; // Change head to (k+1)th node // head is now changed to node 50 *head_ref = kthNode->next; // change next of kth node to NULL // next of 40 is now NULL kthNode->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void 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 off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} /* Driver code*/int main(void){ /* Start with the empty list */ Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); cout << "Given linked list \n"; printList(head); rotate(&head, 4); cout << "\nRotated Linked list \n"; printList(head); return (0);} // This code is contributed by rathbhupendra
// C program to rotate a linked list counter clock wise #include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; // This function rotates a linked list counter-clockwise and// updates the head. The function assumes that k is smaller// than size of linked list. It doesn't modify the list if// k is greater than or equal to sizevoid rotate(struct Node** head_ref, int k){ if (k == 0) return; // Let us understand the below code for example k = 4 and // list = 10->20->30->40->50->60. struct Node* current = *head_ref; // current will either point to kth or NULL after this loop. // current will point to node 40 in the above example int count = 1; while (count < k && current != NULL) { current = current->next; count++; } // If current is NULL, k is greater than or equal to count // of nodes in linked list. Don't change the list in this case if (current == NULL) return; // current points to kth node. Store it in a variable. // kthNode points to node 40 in the above example struct Node* kthNode = current; // current will point to last node after this loop // current will point to node 60 in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current->next = *head_ref; // Change head to (k+1)th node // head is now changed to node 50 *head_ref = kthNode->next; // change next of kth node to NULL // next of 40 is now NULL kthNode->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); printf("Given linked list \n"); printList(head); rotate(&head, 4); printf("\nRotated Linked list \n"); printList(head); return (0);}
// Java program to rotate a linked list class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } // This function rotates a linked list counter-clockwise // and updates the head. The function assumes that k is // smaller than size of linked list. It doesn't modify // the list if k is greater than or equal to size void rotate(int k) { if (k == 0) return; // Let us understand the below code for example k = 4 // and list = 10->20->30->40->50->60. Node current = head; // current will either point to kth or NULL after this // loop. current will point to node 40 in the above example int count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater than or equal to count // of nodes in linked list. Don't change the list in this case if (current == null) return; // current points to kth node. Store it in a variable. // kthNode points to node 40 in the above example Node kthNode = current; // current will point to last node after this loop // current will point to node 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); // create a list 10->20->30->40->50->60 for (int i = 60; i >= 10; i -= 10) llist.push(i); System.out.println("Given list"); llist.printList(); llist.rotate(4); System.out.println("Rotated Linked List"); llist.printList(); }} /* This code is contributed by Rajat Mishra */
# Python program to rotate a linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): # allocate node and put the data new_node = Node(new_data) # Make next of new node as head new_node.next = self.head # move the head to point to the new Node self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # This function rotates a linked list counter-clockwise and # updates the head. The function assumes that k is smaller # than size of linked list. It doesn't modify the list if # k is greater than of equal to size def rotate(self, k): if k == 0: return # Let us understand the below code for example k = 4 # and list = 10->20->30->40->50->60 current = self.head # current will either point to kth or NULL after # this loop # current will point to node 40 in the above example count = 1 while(count <k and current is not None): current = current.next count += 1 # If current is None, k is greater than or equal # to count of nodes in linked list. Don't change # the list in this case if current is None: return # current points to kth node. Store it in a variable # kth node points to node 40 in the above example kthNode = current # current will point to last node after this loop # current will point to node 60 in above example while(current.next is not None): current = current.next # Change next of last node to previous head # Next of 60 is now changed to node 10 current.next = self.head # Change head to (k + 1)th node # head is not changed to node 50 self.head = kthNode.next # change next of kth node to NULL # next of 40 is not NULL kthNode.next = None # Driver program to test above functionllist = LinkedList() # Create a list 10->20->30->40->50->60for i in range(60, 0, -10): llist.push(i) print "Given linked list"llist.printList()llist.rotate(4) print "\nRotated Linked list"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to rotate a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // This function rotates a linked list // counter-clockwise and updates the head. // The function assumes that k is smaller // than size of linked list. It doesn't modify // the list if k is greater than or equal to size void rotate(int k) { if (k == 0) return; // Let us understand the below // code for example k = 4 // and list = 10->20->30->40->50->60. Node current = head; // current will either point to kth // or NULL after this loop. current // will point to node 40 in the above example int count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater than // or equal to count of nodes in linked list. // Don't change the list in this case if (current == null) return; // current points to kth node. // Store it in a variable. // kthNode points to node // 40 in the above example Node kthNode = current; // current will point to // last node after this loop // current will point to // node 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main() { LinkedList llist = new LinkedList(); // create a list 10->20->30->40->50->60 for (int i = 60; i >= 10; i -= 10) llist.push(i); Console.WriteLine("Given list"); llist.printList(); llist.rotate(4); Console.WriteLine("Rotated Linked List"); llist.printList(); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to rotate a linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } // This function rotates a linked // list counter-clockwise // and updates the head. // The function assumes that k is // smaller than size of linked list. // It doesn't modify // the list if k is greater than or equal to size function rotate(k) { if (k == 0) return; // Let us understand the // below code for example k = 4 // and list = 10->20->30->40->50->60. var current = head; // current will either point to kth // or NULL after this // loop. current will point to node // 40 in the above example var count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater // than or equal to count // of nodes in linked list. // Don't change the list in this case if (current == null) return; // current points to kth node. // Store it in a variable. // kthNode points to node 40 // in the above example var kthNode = current; // current will point to last // node after this loop // current will point to node // 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* * Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(new_data) { /* 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ // create a list 10->20->30->40->50->60 for (i = 60; i >= 10; i -= 10) push(i); document.write("Given list<br/>"); printList(); rotate(4); document.write("Rotated Linked List<br/>"); printList(); // This code is contributed by todaysgaurav </script>
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses the linked list only once.
Auxiliary Space : O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Method-2:To rotate a linked list by k, we can first make the linked list circular and then moving k-1 steps forward from head node, making (k-1)th node’s next to null and make kth node as head.
C++
Java
Python3
C#
Javascript
// C++ program to rotate// a linked list counter clock wise #include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.void rotate(Node** head_ref, int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10->20->30->40->50->60. Node* current = *head_ref; // Traverse till the end. while (current->next != NULL) current = current->next; current->next = *head_ref; current = *head_ref; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current->next; // update the head_ref and last element pointer to NULL *head_ref = current->next; current->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void 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 off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} /* Driver code*/int main(void){ /* Start with the empty list */ Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); cout << "Given linked list \n"; printList(head); rotate(&head, 4); cout << "\nRotated Linked list \n"; printList(head); return (0);} // This code is contributed by pkurada
// Java program to rotate// a linked list counter clock wiseimport java.util.*; class GFG{ /* Link list node */static class Node { int data; Node next;};static Node head = null; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.static void rotate( int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. Node current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last element pointer to null head = current.next; current.next = null;} /* UTILITY FUNCTIONS *//* Function to push a node */static void push(int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node;} /* Function to print linked list */static void printList(Node node){ while (node != null) { System.out.print(node.data + " "); node = node.next; }} /* Driver code*/public static void main(String[] args){ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (int i = 60; i > 0; i -= 10) push( i); System.out.print("Given linked list \n"); printList(head); rotate( 4); System.out.print("\nRotated Linked list \n"); printList(head);}} // This code IS contributed by gauravrajput1
# Python3 program to rotate# a linked list counter clock wise # Link list node class Node: def __init__(self): self.data = 0 self.next = None # This function rotates a linked list# counter-clockwise and updates the# head. The function assumes that k is# smaller than size of linked list.def rotate(head_ref, k): if (k == 0): return # Let us understand the below # code for example k = 4 and # list = 10.20.30.40.50.60. current = head_ref # Traverse till the end. while (current.next != None): current = current.next current.next = head_ref current = head_ref # Traverse the linked list to k-1 # position which will be last element # for rotated array. for i in range(k - 1): current = current.next # Update the head_ref and last # element pointer to None head_ref = current.next current.next = None return head_ref # UTILITY FUNCTIONS # Function to push a node def push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list off # the new node new_node.next = (head_ref) # Move the head to point # to the new node (head_ref) = new_node return head_ref # Function to print linked list def printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Driver codeif __name__=='__main__': # Start with the empty list head = None # Create a list 10.20.30.40.50.60 for i in range(60, 0, -10): head = push(head, i) print("Given linked list ") printList(head) head = rotate(head, 4) print("\nRotated Linked list ") printList(head) # This code is contributed by rutvik_56
// C# program to rotate// a linked list counter clock wiseusing System; class GFG{ /* Link list node */public class Node { public int data; public Node next;};static Node head = null; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.static void rotate( int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. Node current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last element pointer to null head = current.next; current.next = null;} /* UTILITY FUNCTIONS *//* Function to push a node */static void push(int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node;} /* Function to print linked list */static void printList(Node node){ while (node != null) { Console.Write(node.data + " "); node = node.next; }} /* Driver code*/public static void Main(String[] args){ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (int i = 60; i > 0; i -= 10) push( i); Console.Write("Given linked list \n"); printList(head); rotate( 4); Console.Write("\nRotated Linked list \n"); printList(head);}} // This code contributed by shikhasingrajput
<script> // Javascript program to rotate// a linked list counter clock wise /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }} var head = null; // This function rotates a linked list // counter-clockwise and updates the // head. The function assumes that k is // smaller than size of linked list. function rotate(k) { if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. var current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list // to k-1 position which // will be last element for rotated array. for (i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last // element pointer to null head = current.next; current.next = null; } /* UTILITY FUNCTIONS */ /* Function to push a node */ function push(new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */ function printList( node) { while (node != null) { document.write(node.data + " "); node = node.next; } } /* Driver code */ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (i = 60; i > 0; i -= 10) push(i); document.write("Given linked list <br/>"); printList(head); rotate(4); document.write("<br/>Rotated Linked list <br/>"); printList(head); // This code contributed by aashish1995 </script>
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List.
Auxiliary Space : O(1)
Add 1 to a number represented as linked list | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAdd 1 to a number represented as linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=utc8bwTDjLk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
princiraj1992
rathbhupendra
nidhi_biet
pkurada
shrayansh95
GauravRajput1
shikhasingrajput
rutvik_56
aashish1995
todaysgaurav
skc161931
simranarora5sos
surinderdawra388
codewithmini
vijayalakshmivenkataraman
Accolite
MakeMyTrip
rotation
Linked List
Accolite
MakeMyTrip
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Add two numbers represented by linked lists | Set 1
Detect and Remove Loop in a Linked List
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Implement a stack using singly linked list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 368,
"s": 52,
"text": "Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in a linked list."
},
{
"code": null,
"e": 899,
"s": 368,
"text": "Method-1:To rotate the linked list, we need to change the next pointer of kth node to NULL, the next pointer of the last node should point to previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node. Traverse the list from the beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till the end and store a pointer to the last node also. Finally, change pointers as stated above."
},
{
"code": null,
"e": 960,
"s": 899,
"text": "Below image shows how to rotate function works in the code :"
},
{
"code": null,
"e": 964,
"s": 960,
"text": "C++"
},
{
"code": null,
"e": 966,
"s": 964,
"text": "C"
},
{
"code": null,
"e": 971,
"s": 966,
"text": "Java"
},
{
"code": null,
"e": 978,
"s": 971,
"text": "Python"
},
{
"code": null,
"e": 981,
"s": 978,
"text": "C#"
},
{
"code": null,
"e": 992,
"s": 981,
"text": "Javascript"
},
{
"code": "// C++ program to rotate// a linked list counter clock wise #include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.// It doesn't modify the list if// k is greater than or equal to sizevoid rotate(Node** head_ref, int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10->20->30->40->50->60. Node* current = *head_ref; // current will either point to // kth or NULL after this loop. // current will point to node // 40 in the above example int count = 1; while (count < k && current != NULL) { current = current->next; count++; } // If current is NULL, k is greater than // or equal to count of nodes in linked list. // Don't change the list in this case if (current == NULL) return; // current points to kth node. // Store it in a variable. kthNode // points to node 40 in the above example Node* kthNode = current; // current will point to // last node after this loop // current will point to // node 60 in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current->next = *head_ref; // Change head to (k+1)th node // head is now changed to node 50 *head_ref = kthNode->next; // change next of kth node to NULL // next of 40 is now NULL kthNode->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void 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 off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} /* Driver code*/int main(void){ /* Start with the empty list */ Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); cout << \"Given linked list \\n\"; printList(head); rotate(&head, 4); cout << \"\\nRotated Linked list \\n\"; printList(head); return (0);} // This code is contributed by rathbhupendra",
"e": 3589,
"s": 992,
"text": null
},
{
"code": "// C program to rotate a linked list counter clock wise #include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; // This function rotates a linked list counter-clockwise and// updates the head. The function assumes that k is smaller// than size of linked list. It doesn't modify the list if// k is greater than or equal to sizevoid rotate(struct Node** head_ref, int k){ if (k == 0) return; // Let us understand the below code for example k = 4 and // list = 10->20->30->40->50->60. struct Node* current = *head_ref; // current will either point to kth or NULL after this loop. // current will point to node 40 in the above example int count = 1; while (count < k && current != NULL) { current = current->next; count++; } // If current is NULL, k is greater than or equal to count // of nodes in linked list. Don't change the list in this case if (current == NULL) return; // current points to kth node. Store it in a variable. // kthNode points to node 40 in the above example struct Node* kthNode = current; // current will point to last node after this loop // current will point to node 60 in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current->next = *head_ref; // Change head to (k+1)th node // head is now changed to node 50 *head_ref = kthNode->next; // change next of kth node to NULL // next of 40 is now NULL kthNode->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function*/int main(void){ /* Start with the empty list */ struct Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); printf(\"Given linked list \\n\"); printList(head); rotate(&head, 4); printf(\"\\nRotated Linked list \\n\"); printList(head); return (0);}",
"e": 6191,
"s": 3589,
"text": null
},
{
"code": "// Java program to rotate a linked list class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } // This function rotates a linked list counter-clockwise // and updates the head. The function assumes that k is // smaller than size of linked list. It doesn't modify // the list if k is greater than or equal to size void rotate(int k) { if (k == 0) return; // Let us understand the below code for example k = 4 // and list = 10->20->30->40->50->60. Node current = head; // current will either point to kth or NULL after this // loop. current will point to node 40 in the above example int count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater than or equal to count // of nodes in linked list. Don't change the list in this case if (current == null) return; // current points to kth node. Store it in a variable. // kthNode points to node 40 in the above example Node kthNode = current; // current will point to last node after this loop // current will point to node 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); // create a list 10->20->30->40->50->60 for (int i = 60; i >= 10; i -= 10) llist.push(i); System.out.println(\"Given list\"); llist.printList(); llist.rotate(4); System.out.println(\"Rotated Linked List\"); llist.printList(); }} /* This code is contributed by Rajat Mishra */",
"e": 9119,
"s": 6191,
"text": null
},
{
"code": "# Python program to rotate a linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): # allocate node and put the data new_node = Node(new_data) # Make next of new node as head new_node.next = self.head # move the head to point to the new Node self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # This function rotates a linked list counter-clockwise and # updates the head. The function assumes that k is smaller # than size of linked list. It doesn't modify the list if # k is greater than of equal to size def rotate(self, k): if k == 0: return # Let us understand the below code for example k = 4 # and list = 10->20->30->40->50->60 current = self.head # current will either point to kth or NULL after # this loop # current will point to node 40 in the above example count = 1 while(count <k and current is not None): current = current.next count += 1 # If current is None, k is greater than or equal # to count of nodes in linked list. Don't change # the list in this case if current is None: return # current points to kth node. Store it in a variable # kth node points to node 40 in the above example kthNode = current # current will point to last node after this loop # current will point to node 60 in above example while(current.next is not None): current = current.next # Change next of last node to previous head # Next of 60 is now changed to node 10 current.next = self.head # Change head to (k + 1)th node # head is not changed to node 50 self.head = kthNode.next # change next of kth node to NULL # next of 40 is not NULL kthNode.next = None # Driver program to test above functionllist = LinkedList() # Create a list 10->20->30->40->50->60for i in range(60, 0, -10): llist.push(i) print \"Given linked list\"llist.printList()llist.rotate(4) print \"\\nRotated Linked list\"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 11818,
"s": 9119,
"text": null
},
{
"code": "// C# program to rotate a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // This function rotates a linked list // counter-clockwise and updates the head. // The function assumes that k is smaller // than size of linked list. It doesn't modify // the list if k is greater than or equal to size void rotate(int k) { if (k == 0) return; // Let us understand the below // code for example k = 4 // and list = 10->20->30->40->50->60. Node current = head; // current will either point to kth // or NULL after this loop. current // will point to node 40 in the above example int count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater than // or equal to count of nodes in linked list. // Don't change the list in this case if (current == null) return; // current points to kth node. // Store it in a variable. // kthNode points to node // 40 in the above example Node kthNode = current; // current will point to // last node after this loop // current will point to // node 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main() { LinkedList llist = new LinkedList(); // create a list 10->20->30->40->50->60 for (int i = 60; i >= 10; i -= 10) llist.push(i); Console.WriteLine(\"Given list\"); llist.printList(); llist.rotate(4); Console.WriteLine(\"Rotated Linked List\"); llist.printList(); }} /* This code contributed by PrinciRaj1992 */",
"e": 14818,
"s": 11818,
"text": null
},
{
"code": "<script> // Javascript program to rotate a linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } // This function rotates a linked // list counter-clockwise // and updates the head. // The function assumes that k is // smaller than size of linked list. // It doesn't modify // the list if k is greater than or equal to size function rotate(k) { if (k == 0) return; // Let us understand the // below code for example k = 4 // and list = 10->20->30->40->50->60. var current = head; // current will either point to kth // or NULL after this // loop. current will point to node // 40 in the above example var count = 1; while (count < k && current != null) { current = current.next; count++; } // If current is NULL, k is greater // than or equal to count // of nodes in linked list. // Don't change the list in this case if (current == null) return; // current points to kth node. // Store it in a variable. // kthNode points to node 40 // in the above example var kthNode = current; // current will point to last // node after this loop // current will point to node // 60 in the above example while (current.next != null) current = current.next; // Change next of last node to previous head // Next of 60 is now changed to node 10 current.next = head; // Change head to (k+1)th node // head is now changed to node 50 head = kthNode.next; // change next of kth node to null kthNode.next = null; } /* * Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(new_data) { /* 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ // create a list 10->20->30->40->50->60 for (i = 60; i >= 10; i -= 10) push(i); document.write(\"Given list<br/>\"); printList(); rotate(4); document.write(\"Rotated Linked List<br/>\"); printList(); // This code is contributed by todaysgaurav </script>",
"e": 17714,
"s": 14818,
"text": null
},
{
"code": null,
"e": 17723,
"s": 17714,
"text": "Output: "
},
{
"code": null,
"e": 17807,
"s": 17723,
"text": "Given linked list\n10 20 30 40 50 60\nRotated Linked list\n50 60 10 20 30 40"
},
{
"code": null,
"e": 17922,
"s": 17807,
"text": "Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses the linked list only once."
},
{
"code": null,
"e": 17945,
"s": 17922,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 18071,
"s": 17945,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 18265,
"s": 18071,
"text": "Method-2:To rotate a linked list by k, we can first make the linked list circular and then moving k-1 steps forward from head node, making (k-1)th node’s next to null and make kth node as head."
},
{
"code": null,
"e": 18269,
"s": 18265,
"text": "C++"
},
{
"code": null,
"e": 18274,
"s": 18269,
"text": "Java"
},
{
"code": null,
"e": 18282,
"s": 18274,
"text": "Python3"
},
{
"code": null,
"e": 18285,
"s": 18282,
"text": "C#"
},
{
"code": null,
"e": 18296,
"s": 18285,
"text": "Javascript"
},
{
"code": "// C++ program to rotate// a linked list counter clock wise #include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.void rotate(Node** head_ref, int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10->20->30->40->50->60. Node* current = *head_ref; // Traverse till the end. while (current->next != NULL) current = current->next; current->next = *head_ref; current = *head_ref; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current->next; // update the head_ref and last element pointer to NULL *head_ref = current->next; current->next = NULL;} /* UTILITY FUNCTIONS *//* Function to push a node */void 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 off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} /* Driver code*/int main(void){ /* Start with the empty list */ Node* head = NULL; // create a list 10->20->30->40->50->60 for (int i = 60; i > 0; i -= 10) push(&head, i); cout << \"Given linked list \\n\"; printList(head); rotate(&head, 4); cout << \"\\nRotated Linked list \\n\"; printList(head); return (0);} // This code is contributed by pkurada",
"e": 20174,
"s": 18296,
"text": null
},
{
"code": "// Java program to rotate// a linked list counter clock wiseimport java.util.*; class GFG{ /* Link list node */static class Node { int data; Node next;};static Node head = null; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.static void rotate( int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. Node current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last element pointer to null head = current.next; current.next = null;} /* UTILITY FUNCTIONS *//* Function to push a node */static void push(int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node;} /* Function to print linked list */static void printList(Node node){ while (node != null) { System.out.print(node.data + \" \"); node = node.next; }} /* Driver code*/public static void main(String[] args){ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (int i = 60; i > 0; i -= 10) push( i); System.out.print(\"Given linked list \\n\"); printList(head); rotate( 4); System.out.print(\"\\nRotated Linked list \\n\"); printList(head);}} // This code IS contributed by gauravrajput1 ",
"e": 22022,
"s": 20174,
"text": null
},
{
"code": "# Python3 program to rotate# a linked list counter clock wise # Link list node class Node: def __init__(self): self.data = 0 self.next = None # This function rotates a linked list# counter-clockwise and updates the# head. The function assumes that k is# smaller than size of linked list.def rotate(head_ref, k): if (k == 0): return # Let us understand the below # code for example k = 4 and # list = 10.20.30.40.50.60. current = head_ref # Traverse till the end. while (current.next != None): current = current.next current.next = head_ref current = head_ref # Traverse the linked list to k-1 # position which will be last element # for rotated array. for i in range(k - 1): current = current.next # Update the head_ref and last # element pointer to None head_ref = current.next current.next = None return head_ref # UTILITY FUNCTIONS # Function to push a node def push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list off # the new node new_node.next = (head_ref) # Move the head to point # to the new node (head_ref) = new_node return head_ref # Function to print linked list def printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Driver codeif __name__=='__main__': # Start with the empty list head = None # Create a list 10.20.30.40.50.60 for i in range(60, 0, -10): head = push(head, i) print(\"Given linked list \") printList(head) head = rotate(head, 4) print(\"\\nRotated Linked list \") printList(head) # This code is contributed by rutvik_56",
"e": 23833,
"s": 22022,
"text": null
},
{
"code": "// C# program to rotate// a linked list counter clock wiseusing System; class GFG{ /* Link list node */public class Node { public int data; public Node next;};static Node head = null; // This function rotates a linked list// counter-clockwise and updates the// head. The function assumes that k is// smaller than size of linked list.static void rotate( int k){ if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. Node current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list to k-1 position which // will be last element for rotated array. for (int i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last element pointer to null head = current.next; current.next = null;} /* UTILITY FUNCTIONS *//* Function to push a node */static void push(int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node;} /* Function to print linked list */static void printList(Node node){ while (node != null) { Console.Write(node.data + \" \"); node = node.next; }} /* Driver code*/public static void Main(String[] args){ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (int i = 60; i > 0; i -= 10) push( i); Console.Write(\"Given linked list \\n\"); printList(head); rotate( 4); Console.Write(\"\\nRotated Linked list \\n\"); printList(head);}} // This code contributed by shikhasingrajput",
"e": 25675,
"s": 23833,
"text": null
},
{
"code": "<script> // Javascript program to rotate// a linked list counter clock wise /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }} var head = null; // This function rotates a linked list // counter-clockwise and updates the // head. The function assumes that k is // smaller than size of linked list. function rotate(k) { if (k == 0) return; // Let us understand the below // code for example k = 4 and // list = 10.20.30.40.50.60. var current = head; // Traverse till the end. while (current.next != null) current = current.next; current.next = head; current = head; // traverse the linked list // to k-1 position which // will be last element for rotated array. for (i = 0; i < k - 1; i++) current = current.next; // update the head_ref and last // element pointer to null head = current.next; current.next = null; } /* UTILITY FUNCTIONS */ /* Function to push a node */ function push(new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } /* Function to print linked list */ function printList( node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } /* Driver code */ /* Start with the empty list */ // create a list 10.20.30.40.50.60 for (i = 60; i > 0; i -= 10) push(i); document.write(\"Given linked list <br/>\"); printList(head); rotate(4); document.write(\"<br/>Rotated Linked list <br/>\"); printList(head); // This code contributed by aashish1995 </script>",
"e": 27702,
"s": 25675,
"text": null
},
{
"code": null,
"e": 27779,
"s": 27702,
"text": "Given linked list \n10 20 30 40 50 60 \nRotated Linked list \n50 60 10 20 30 40"
},
{
"code": null,
"e": 27850,
"s": 27781,
"text": "Time Complexity: O(n) where n is the number of nodes in Linked List."
},
{
"code": null,
"e": 27873,
"s": 27850,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 28780,
"s": 27873,
"text": "Add 1 to a number represented as linked list | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAdd 1 to a number represented as linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=utc8bwTDjLk\" 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": 28794,
"s": 28780,
"text": "princiraj1992"
},
{
"code": null,
"e": 28808,
"s": 28794,
"text": "rathbhupendra"
},
{
"code": null,
"e": 28819,
"s": 28808,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28827,
"s": 28819,
"text": "pkurada"
},
{
"code": null,
"e": 28839,
"s": 28827,
"text": "shrayansh95"
},
{
"code": null,
"e": 28853,
"s": 28839,
"text": "GauravRajput1"
},
{
"code": null,
"e": 28870,
"s": 28853,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 28880,
"s": 28870,
"text": "rutvik_56"
},
{
"code": null,
"e": 28892,
"s": 28880,
"text": "aashish1995"
},
{
"code": null,
"e": 28905,
"s": 28892,
"text": "todaysgaurav"
},
{
"code": null,
"e": 28915,
"s": 28905,
"text": "skc161931"
},
{
"code": null,
"e": 28931,
"s": 28915,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28948,
"s": 28931,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28961,
"s": 28948,
"text": "codewithmini"
},
{
"code": null,
"e": 28987,
"s": 28961,
"text": "vijayalakshmivenkataraman"
},
{
"code": null,
"e": 28996,
"s": 28987,
"text": "Accolite"
},
{
"code": null,
"e": 29007,
"s": 28996,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 29016,
"s": 29007,
"text": "rotation"
},
{
"code": null,
"e": 29028,
"s": 29016,
"text": "Linked List"
},
{
"code": null,
"e": 29037,
"s": 29028,
"text": "Accolite"
},
{
"code": null,
"e": 29048,
"s": 29037,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 29060,
"s": 29048,
"text": "Linked List"
},
{
"code": null,
"e": 29158,
"s": 29060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29206,
"s": 29158,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 29225,
"s": 29206,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 29257,
"s": 29225,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 29321,
"s": 29257,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 29368,
"s": 29321,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29420,
"s": 29368,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 29460,
"s": 29420,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 29495,
"s": 29460,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 29551,
"s": 29495,
"text": "Function to check if a singly linked list is palindrome"
}
]
|
Longest Subarray having sum of elements atmost ‘k’ | 25 May, 2022
Given an array of integers, our goal is to find the length of the largest subarray having the sum of its elements at most ‘k’ where k>0.
Examples:
Input : arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4
Output : 5
Explanation:
{1, 2, 1} => sum = 4, length = 3
{1, 2, 1, 0}, {2, 1, 0, 1} => sum = 4, length = 4
{1, 0, 1, 1, 0} =>5 sum = 3, length = 5
Method 1 (Brute Force) Find all the subarrays whose sum is less than or equal to k and return the one with the largest length. Time Complexity : O(n^2) Method 2 (Efficient): An efficient approach is to use the sliding window technique.
Traverse the array and check if on adding the current element its sum is less than or equal to k.If it’s less than k then add it to the sum and increase the count.Keep track of Maximum count.
Traverse the array and check if on adding the current element its sum is less than or equal to k.
If it’s less than k then add it to the sum and increase the count.
Keep track of Maximum count.
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to find longest subarray with// sum of elements at-least k.#include <bits/stdc++.h>using namespace std; // function to find the length of largest subarray// having sum atmost k.int atMostSum(int arr[], int n, int k){ int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window and add the current element else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = max(cnt, maxcnt); } return maxcnt;} // Driver functionint main(){ int arr[] = {1, 2, 1, 0, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << atMostSum(arr, n, k); return 0;}
// Java program to find longest subarray with// sum of elements at-least k.import java.util.*; class GFG { // function to find the length of largest // subarray having sum atmost k. public static int atMostSum(int arr[], int n, int k) { int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window. else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.max(cnt, maxcnt); } return maxcnt; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 1, 2, 1, 0, 1, 1, 0 }; int n = arr.length; int k = 4; System.out.print(atMostSum(arr, n, k)); }}// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find longest subarray# with sum of elements at-least k. # function to find the length of largest# subarray having sum atmost k.def atMostSum(arr, n, k): _sum = 0 cnt = 0 maxcnt = 0 for i in range(n): # If adding current element doesn't # Cross limit add it to current window if ((_sum + arr[i]) <= k): _sum += arr[i] cnt += 1 # Else, remove first element of current # window and add the current element else if(sum != 0): _sum = _sum - arr[i - cnt] + arr[i] # keep track of max length. maxcnt = max(cnt, maxcnt) return maxcnt # Driver functionarr = [1, 2, 1, 0, 1, 1, 0]n = len(arr)k = 4print(atMostSum(arr, n, k)) # This code is contributed by "Abhishek Sharma 44"
// C# program to find longest subarray// with sum of elements at-least k.using System; class GFG { // function to find the length of largest // subarray having sum atmost k. public static int atMostSum(int []arr, int n, int k) { int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element // of current window. else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.Max(cnt, maxcnt); } return maxcnt; } // Driver Code public static void Main() { int []arr = {1, 2, 1, 0, 1, 1, 0}; int n = arr.Length; int k = 4; Console.Write(atMostSum(arr, n, k)); }} // This code is contributed by Nitin Mittal
<?php// A PHP program to find longest// subarray with sum of elements// at-least k. // function to find the length// of largest subarray having// sum atmost k.function atMostSum(&$arr, $n, $k){ $sum = 0; $cnt = 0; $maxcnt = 0; for($i = 0; $i < $n; $i++) { // If adding current element // doesn't cross limit add // it to current window if (($sum + $arr[$i]) <= $k) { $sum += $arr[$i] ; $cnt += 1 ; } // Else, remove first element // of current window and add // the current element else if($sum != 0) $sum = $sum - $arr[$i - $cnt] + $arr[$i]; // keep track of max length. $maxcnt = max($cnt, $maxcnt); } return $maxcnt;} // Driver Code$arr = array(1, 2, 1, 0, 1, 1, 0);$n = sizeof($arr);$k = 4; print(atMostSum($arr, $n, $k)); // This code is contributed// by ChitraNayal?>
<script>// A Javascript program to find longest subarray with// sum of elements at-least k. // function to find the length of largest subarray// having sum atmost k.function atMostSum(arr, n, k){ let sum = 0; let cnt = 0, maxcnt = 0; for (let i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window and add the current element else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.max(cnt, maxcnt); } return maxcnt;} // Driver function let arr = [1, 2, 1, 0, 1, 1, 0]; let n = arr.length; let k = 4; document.write(atMostSum(arr, n, k)); </script>
Output:
5
Time Complexity : O(n), where n represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
This article is contributed by Kshitiz gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
ukasp
souravmahato348
simmytarika5
tamanna17122007
sliding-window
subarray
subarray-sum
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Find Second largest element in an array
Search an element in a sorted and rotated array
Find the Missing Number | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 191,
"s": 54,
"text": "Given an array of integers, our goal is to find the length of the largest subarray having the sum of its elements at most ‘k’ where k>0."
},
{
"code": null,
"e": 202,
"s": 191,
"text": "Examples: "
},
{
"code": null,
"e": 397,
"s": 202,
"text": "Input : arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4\nOutput : 5\nExplanation:\n {1, 2, 1} => sum = 4, length = 3\n {1, 2, 1, 0}, {2, 1, 0, 1} => sum = 4, length = 4\n {1, 0, 1, 1, 0} =>5 sum = 3, length = 5"
},
{
"code": null,
"e": 635,
"s": 397,
"text": "Method 1 (Brute Force) Find all the subarrays whose sum is less than or equal to k and return the one with the largest length. Time Complexity : O(n^2) Method 2 (Efficient): An efficient approach is to use the sliding window technique. "
},
{
"code": null,
"e": 827,
"s": 635,
"text": "Traverse the array and check if on adding the current element its sum is less than or equal to k.If it’s less than k then add it to the sum and increase the count.Keep track of Maximum count."
},
{
"code": null,
"e": 925,
"s": 827,
"text": "Traverse the array and check if on adding the current element its sum is less than or equal to k."
},
{
"code": null,
"e": 992,
"s": 925,
"text": "If it’s less than k then add it to the sum and increase the count."
},
{
"code": null,
"e": 1021,
"s": 992,
"text": "Keep track of Maximum count."
},
{
"code": null,
"e": 1025,
"s": 1021,
"text": "C++"
},
{
"code": null,
"e": 1030,
"s": 1025,
"text": "Java"
},
{
"code": null,
"e": 1038,
"s": 1030,
"text": "Python3"
},
{
"code": null,
"e": 1041,
"s": 1038,
"text": "C#"
},
{
"code": null,
"e": 1045,
"s": 1041,
"text": "PHP"
},
{
"code": null,
"e": 1056,
"s": 1045,
"text": "Javascript"
},
{
"code": "// A C++ program to find longest subarray with// sum of elements at-least k.#include <bits/stdc++.h>using namespace std; // function to find the length of largest subarray// having sum atmost k.int atMostSum(int arr[], int n, int k){ int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window and add the current element else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = max(cnt, maxcnt); } return maxcnt;} // Driver functionint main(){ int arr[] = {1, 2, 1, 0, 1, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << atMostSum(arr, n, k); return 0;}",
"e": 2002,
"s": 1056,
"text": null
},
{
"code": "// Java program to find longest subarray with// sum of elements at-least k.import java.util.*; class GFG { // function to find the length of largest // subarray having sum atmost k. public static int atMostSum(int arr[], int n, int k) { int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window. else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.max(cnt, maxcnt); } return maxcnt; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 1, 2, 1, 0, 1, 1, 0 }; int n = arr.length; int k = 4; System.out.print(atMostSum(arr, n, k)); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 3211,
"s": 2002,
"text": null
},
{
"code": "# Python3 program to find longest subarray# with sum of elements at-least k. # function to find the length of largest# subarray having sum atmost k.def atMostSum(arr, n, k): _sum = 0 cnt = 0 maxcnt = 0 for i in range(n): # If adding current element doesn't # Cross limit add it to current window if ((_sum + arr[i]) <= k): _sum += arr[i] cnt += 1 # Else, remove first element of current # window and add the current element else if(sum != 0): _sum = _sum - arr[i - cnt] + arr[i] # keep track of max length. maxcnt = max(cnt, maxcnt) return maxcnt # Driver functionarr = [1, 2, 1, 0, 1, 1, 0]n = len(arr)k = 4print(atMostSum(arr, n, k)) # This code is contributed by \"Abhishek Sharma 44\"",
"e": 4031,
"s": 3211,
"text": null
},
{
"code": "// C# program to find longest subarray// with sum of elements at-least k.using System; class GFG { // function to find the length of largest // subarray having sum atmost k. public static int atMostSum(int []arr, int n, int k) { int sum = 0; int cnt = 0, maxcnt = 0; for (int i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element // of current window. else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.Max(cnt, maxcnt); } return maxcnt; } // Driver Code public static void Main() { int []arr = {1, 2, 1, 0, 1, 1, 0}; int n = arr.Length; int k = 4; Console.Write(atMostSum(arr, n, k)); }} // This code is contributed by Nitin Mittal",
"e": 5190,
"s": 4031,
"text": null
},
{
"code": "<?php// A PHP program to find longest// subarray with sum of elements// at-least k. // function to find the length// of largest subarray having// sum atmost k.function atMostSum(&$arr, $n, $k){ $sum = 0; $cnt = 0; $maxcnt = 0; for($i = 0; $i < $n; $i++) { // If adding current element // doesn't cross limit add // it to current window if (($sum + $arr[$i]) <= $k) { $sum += $arr[$i] ; $cnt += 1 ; } // Else, remove first element // of current window and add // the current element else if($sum != 0) $sum = $sum - $arr[$i - $cnt] + $arr[$i]; // keep track of max length. $maxcnt = max($cnt, $maxcnt); } return $maxcnt;} // Driver Code$arr = array(1, 2, 1, 0, 1, 1, 0);$n = sizeof($arr);$k = 4; print(atMostSum($arr, $n, $k)); // This code is contributed// by ChitraNayal?>",
"e": 6143,
"s": 5190,
"text": null
},
{
"code": "<script>// A Javascript program to find longest subarray with// sum of elements at-least k. // function to find the length of largest subarray// having sum atmost k.function atMostSum(arr, n, k){ let sum = 0; let cnt = 0, maxcnt = 0; for (let i = 0; i < n; i++) { // If adding current element doesn't // cross limit add it to current window if ((sum + arr[i]) <= k) { sum += arr[i]; cnt++; } // Else, remove first element of current // window and add the current element else if(sum!=0) { sum = sum - arr[i - cnt] + arr[i]; } // keep track of max length. maxcnt = Math.max(cnt, maxcnt); } return maxcnt;} // Driver function let arr = [1, 2, 1, 0, 1, 1, 0]; let n = arr.length; let k = 4; document.write(atMostSum(arr, n, k)); </script>",
"e": 7029,
"s": 6143,
"text": null
},
{
"code": null,
"e": 7039,
"s": 7029,
"text": "Output: "
},
{
"code": null,
"e": 7041,
"s": 7039,
"text": "5"
},
{
"code": null,
"e": 7113,
"s": 7041,
"text": "Time Complexity : O(n), where n represents the size of the given array."
},
{
"code": null,
"e": 7185,
"s": 7113,
"text": "Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 7607,
"s": 7185,
"text": "This article is contributed by Kshitiz gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7620,
"s": 7607,
"text": "nitin mittal"
},
{
"code": null,
"e": 7626,
"s": 7620,
"text": "ukasp"
},
{
"code": null,
"e": 7642,
"s": 7626,
"text": "souravmahato348"
},
{
"code": null,
"e": 7655,
"s": 7642,
"text": "simmytarika5"
},
{
"code": null,
"e": 7671,
"s": 7655,
"text": "tamanna17122007"
},
{
"code": null,
"e": 7686,
"s": 7671,
"text": "sliding-window"
},
{
"code": null,
"e": 7695,
"s": 7686,
"text": "subarray"
},
{
"code": null,
"e": 7708,
"s": 7695,
"text": "subarray-sum"
},
{
"code": null,
"e": 7715,
"s": 7708,
"text": "Arrays"
},
{
"code": null,
"e": 7730,
"s": 7715,
"text": "sliding-window"
},
{
"code": null,
"e": 7737,
"s": 7730,
"text": "Arrays"
},
{
"code": null,
"e": 7835,
"s": 7737,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7867,
"s": 7835,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7952,
"s": 7867,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 7975,
"s": 7952,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 8031,
"s": 7975,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 8058,
"s": 8031,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 8090,
"s": 8058,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8135,
"s": 8090,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 8175,
"s": 8135,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 8223,
"s": 8175,
"text": "Search an element in a sorted and rotated array"
}
]
|
Python | Find most frequent element in a list | 17 Jul, 2021
Given a list, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them.
Examples:
Input : [2, 1, 2, 2, 1, 3]
Output : 2
Input : ['Dog', 'Cat', 'Dog']
Output : Dog
Approach #1 : Naive ApproachThis is a brute force approach in which we make use of for loop to count the frequency of each element. If the current frequency is greater than the previous frequency, update the counter and store the element.
Python3
# Program to find most frequent# element in a list def most_frequent(List): counter = 0 num = List[0] for i in List: curr_frequency = List.count(i) if(curr_frequency> counter): counter = curr_frequency num = i return num List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))
2
Approach #2 : Pythonic Naive approachMake a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we find the maximum out of it.
Python3
# Program to find most frequent# element in a listdef most_frequent(List): return max(set(List), key = List.count) List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))
2
Approach #3 : Using CounterMake use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.
Python3
# Program to find most frequent# element in a list from collections import Counter def most_frequent(List): occurence_count = Counter(List) return occurence_count.most_common(1)[0][0] List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))
2
Approach #4 : By finding mode Finding most frequent element means finding mode of the list. Hence, we use mode method from statistics.
Python3
import statisticsfrom statistics import mode def most_common(List): return(mode(List)) List = [2, 1, 2, 2, 1, 3]print(most_common(List))
2
Approach #5 : Using Python dictionaryUse python dictionary to save element as a key and its frequency as the value, and thus find the most frequent element.
Python3
# Program to find most frequent# element in a list def most_frequent(List): dict = {} count, itm = 0, '' for item in reversed(List): dict[item] = dict.get(item, 0) + 1 if dict[item] >= count : count, itm = dict[item], item return(itm) List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))
2
Approach #6 : Using pandas library. Incase of multiple values getting repeated. Print all values.
Python3
import pandas as pdList = [2, 1, 2, 2, 1, 3, 1] # Create a panda DataFrame using the listdf=pd.DataFrame({'Number': List}) # Creating a new dataframe to store the values# with appropriate column name# value_counts() returns the count based on# the grouped column valuesdf1 = pd.DataFrame(data=df['Number'].value_counts(), columns=[['Number','Count']]) # The values in the List become the index of the new dataframe.# Setting these index as a columndf1['Count']=df1['Number'].index # Fetch the list of frequently repeated columnslist(df1[df1['Number']==df1.Number.max()]['Count'])
[2,1]
sandeepmidde
saurabh1990aror
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jul, 2021"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "Given a list, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them."
},
{
"code": null,
"e": 206,
"s": 195,
"text": "Examples: "
},
{
"code": null,
"e": 288,
"s": 206,
"text": "Input : [2, 1, 2, 2, 1, 3]\nOutput : 2\n\nInput : ['Dog', 'Cat', 'Dog']\nOutput : Dog"
},
{
"code": null,
"e": 528,
"s": 288,
"text": "Approach #1 : Naive ApproachThis is a brute force approach in which we make use of for loop to count the frequency of each element. If the current frequency is greater than the previous frequency, update the counter and store the element. "
},
{
"code": null,
"e": 536,
"s": 528,
"text": "Python3"
},
{
"code": "# Program to find most frequent# element in a list def most_frequent(List): counter = 0 num = List[0] for i in List: curr_frequency = List.count(i) if(curr_frequency> counter): counter = curr_frequency num = i return num List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))",
"e": 863,
"s": 536,
"text": null
},
{
"code": null,
"e": 865,
"s": 863,
"text": "2"
},
{
"code": null,
"e": 1085,
"s": 867,
"text": " Approach #2 : Pythonic Naive approachMake a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we find the maximum out of it. "
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "Python3"
},
{
"code": "# Program to find most frequent# element in a listdef most_frequent(List): return max(set(List), key = List.count) List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))",
"e": 1263,
"s": 1093,
"text": null
},
{
"code": null,
"e": 1265,
"s": 1263,
"text": "2"
},
{
"code": null,
"e": 1449,
"s": 1267,
"text": " Approach #3 : Using CounterMake use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method. "
},
{
"code": null,
"e": 1457,
"s": 1449,
"text": "Python3"
},
{
"code": "# Program to find most frequent# element in a list from collections import Counter def most_frequent(List): occurence_count = Counter(List) return occurence_count.most_common(1)[0][0] List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))",
"e": 1701,
"s": 1457,
"text": null
},
{
"code": null,
"e": 1703,
"s": 1701,
"text": "2"
},
{
"code": null,
"e": 1842,
"s": 1705,
"text": "Approach #4 : By finding mode Finding most frequent element means finding mode of the list. Hence, we use mode method from statistics. "
},
{
"code": null,
"e": 1850,
"s": 1842,
"text": "Python3"
},
{
"code": "import statisticsfrom statistics import mode def most_common(List): return(mode(List)) List = [2, 1, 2, 2, 1, 3]print(most_common(List))",
"e": 1992,
"s": 1850,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1992,
"text": "2"
},
{
"code": null,
"e": 2155,
"s": 1996,
"text": "Approach #5 : Using Python dictionaryUse python dictionary to save element as a key and its frequency as the value, and thus find the most frequent element. "
},
{
"code": null,
"e": 2163,
"s": 2155,
"text": "Python3"
},
{
"code": "# Program to find most frequent# element in a list def most_frequent(List): dict = {} count, itm = 0, '' for item in reversed(List): dict[item] = dict.get(item, 0) + 1 if dict[item] >= count : count, itm = dict[item], item return(itm) List = [2, 1, 2, 2, 1, 3]print(most_frequent(List))",
"e": 2487,
"s": 2163,
"text": null
},
{
"code": null,
"e": 2489,
"s": 2487,
"text": "2"
},
{
"code": null,
"e": 2589,
"s": 2491,
"text": "Approach #6 : Using pandas library. Incase of multiple values getting repeated. Print all values."
},
{
"code": null,
"e": 2597,
"s": 2589,
"text": "Python3"
},
{
"code": "import pandas as pdList = [2, 1, 2, 2, 1, 3, 1] # Create a panda DataFrame using the listdf=pd.DataFrame({'Number': List}) # Creating a new dataframe to store the values# with appropriate column name# value_counts() returns the count based on# the grouped column valuesdf1 = pd.DataFrame(data=df['Number'].value_counts(), columns=[['Number','Count']]) # The values in the List become the index of the new dataframe.# Setting these index as a columndf1['Count']=df1['Number'].index # Fetch the list of frequently repeated columnslist(df1[df1['Number']==df1.Number.max()]['Count'])",
"e": 3177,
"s": 2597,
"text": null
},
{
"code": null,
"e": 3183,
"s": 3177,
"text": "[2,1]"
},
{
"code": null,
"e": 3198,
"s": 3185,
"text": "sandeepmidde"
},
{
"code": null,
"e": 3214,
"s": 3198,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3235,
"s": 3214,
"text": "Python list-programs"
},
{
"code": null,
"e": 3247,
"s": 3235,
"text": "python-list"
},
{
"code": null,
"e": 3254,
"s": 3247,
"text": "Python"
},
{
"code": null,
"e": 3270,
"s": 3254,
"text": "Python Programs"
},
{
"code": null,
"e": 3282,
"s": 3270,
"text": "python-list"
},
{
"code": null,
"e": 3380,
"s": 3282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3398,
"s": 3380,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3440,
"s": 3398,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3462,
"s": 3440,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3488,
"s": 3462,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3520,
"s": 3488,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3563,
"s": 3520,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3585,
"s": 3563,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3624,
"s": 3585,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3662,
"s": 3624,
"text": "Python | Convert a list to dictionary"
}
]
|
PHP array_key_exists() Function | 01 Dec, 2021
In this article, we will see how to get the array key using the array_key_exists() function in PHP, & will also see its implementation through the example. The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false. The required key while specifying the array, is skipped then it will generate the integer value for the key, starting from 0 that will be incremented by 1 for each value.
Pre-requisite: PHP array_keys() Function
Syntax:
boolean array_key_exists($index, $array)
Parameters: This function takes 2 arguments and is described below:
$index: This parameter is mandatory and refers to the key that is needed to be searched for in an input array.
$array: This parameter is mandatory and refers to the original array in which we want to search the given key $index.
Return Value: This function returns a boolean value i.e., TRUE and FALSE depending on whether the key is present in the array or not respectively.
Note: Nested keys will return the FALSE result.
Example 1: The below programs illustrates the array_key_exists() function in PHP. Here, we will see how we can find a key inside an array that holds key_value pair.
PHP
<?php // PHP function to illustrate the use // of array_key_exists() function Exists($index, $array) { if (array_key_exists($index, $array)) { echo "Found the Key"; } else { echo "Key not Found"; } } $array = array( "ram" => 25, "krishna" => 10, "aakash" => 20, "gaurav" ); $index = "aakash"; print_r(Exists($index, $array));?>
Output:
Found the Key
If no key_value pair exits, as shown in the below case, then the array takes the default keys i.e. numeric keys starting from zero, into consideration and returns true as far as the $index limit ranges.
Example: This example illustrates the array_key_exists() function in PHP by specifying the particular $index value.
PHP
<?php // PHP function to illustrate the use of // array_key_exists() function Exists($index, $array) { if (array_key_exists($index, $array)) { echo "Found the Key"; } else { echo "Key not Found"; } } $array = array( "ram", "krishna", "aakash", "gaurav" ); $index = 2; print_r(Exists($index, $array));?>
Output:
Found the Key
Reference: http://php.net/manual/en/function.array-key-exists.php
surinderdawra388
bhaskargeeksforgeeks
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 591,
"s": 28,
"text": "In this article, we will see how to get the array key using the array_key_exists() function in PHP, & will also see its implementation through the example. The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false. The required key while specifying the array, is skipped then it will generate the integer value for the key, starting from 0 that will be incremented by 1 for each value."
},
{
"code": null,
"e": 632,
"s": 591,
"text": "Pre-requisite: PHP array_keys() Function"
},
{
"code": null,
"e": 640,
"s": 632,
"text": "Syntax:"
},
{
"code": null,
"e": 681,
"s": 640,
"text": "boolean array_key_exists($index, $array)"
},
{
"code": null,
"e": 749,
"s": 681,
"text": "Parameters: This function takes 2 arguments and is described below:"
},
{
"code": null,
"e": 860,
"s": 749,
"text": "$index: This parameter is mandatory and refers to the key that is needed to be searched for in an input array."
},
{
"code": null,
"e": 978,
"s": 860,
"text": "$array: This parameter is mandatory and refers to the original array in which we want to search the given key $index."
},
{
"code": null,
"e": 1125,
"s": 978,
"text": "Return Value: This function returns a boolean value i.e., TRUE and FALSE depending on whether the key is present in the array or not respectively."
},
{
"code": null,
"e": 1174,
"s": 1125,
"text": "Note: Nested keys will return the FALSE result. "
},
{
"code": null,
"e": 1339,
"s": 1174,
"text": "Example 1: The below programs illustrates the array_key_exists() function in PHP. Here, we will see how we can find a key inside an array that holds key_value pair."
},
{
"code": null,
"e": 1343,
"s": 1339,
"text": "PHP"
},
{
"code": "<?php // PHP function to illustrate the use // of array_key_exists() function Exists($index, $array) { if (array_key_exists($index, $array)) { echo \"Found the Key\"; } else { echo \"Key not Found\"; } } $array = array( \"ram\" => 25, \"krishna\" => 10, \"aakash\" => 20, \"gaurav\" ); $index = \"aakash\"; print_r(Exists($index, $array));?>",
"e": 1791,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1799,
"s": 1791,
"text": "Output:"
},
{
"code": null,
"e": 1813,
"s": 1799,
"text": "Found the Key"
},
{
"code": null,
"e": 2016,
"s": 1813,
"text": "If no key_value pair exits, as shown in the below case, then the array takes the default keys i.e. numeric keys starting from zero, into consideration and returns true as far as the $index limit ranges."
},
{
"code": null,
"e": 2132,
"s": 2016,
"text": "Example: This example illustrates the array_key_exists() function in PHP by specifying the particular $index value."
},
{
"code": null,
"e": 2136,
"s": 2132,
"text": "PHP"
},
{
"code": "<?php // PHP function to illustrate the use of // array_key_exists() function Exists($index, $array) { if (array_key_exists($index, $array)) { echo \"Found the Key\"; } else { echo \"Key not Found\"; } } $array = array( \"ram\", \"krishna\", \"aakash\", \"gaurav\" ); $index = 2; print_r(Exists($index, $array));?>",
"e": 2561,
"s": 2136,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2561,
"text": "Output:"
},
{
"code": null,
"e": 2583,
"s": 2569,
"text": "Found the Key"
},
{
"code": null,
"e": 2649,
"s": 2583,
"text": "Reference: http://php.net/manual/en/function.array-key-exists.php"
},
{
"code": null,
"e": 2666,
"s": 2649,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2687,
"s": 2666,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 2697,
"s": 2687,
"text": "PHP-array"
},
{
"code": null,
"e": 2710,
"s": 2697,
"text": "PHP-function"
},
{
"code": null,
"e": 2714,
"s": 2710,
"text": "PHP"
},
{
"code": null,
"e": 2731,
"s": 2714,
"text": "Web Technologies"
},
{
"code": null,
"e": 2735,
"s": 2731,
"text": "PHP"
}
]
|
How to standardized a column of R DataFrame ? | 05 Apr, 2021
A large dataset that had multiple columns with varying ranges and units may need to be standardized before further processing. In this article, we will be discussing how to standardize a column of dataframe in R Programming Language.
Let’s first discuss standardization. Standardization is a feature scaling technique. It is the process of rescaling data so that the data have a mean of ‘0’ and standard deviation of ‘1’.
Formula:
Here, is mean and is standard deviation. We are subtracting the mean from each value in observation and then dividing by standard deviation. This is also called the Z-score formula.
Example :
Name
Age
CGPA
1.
A
15
5.0
2.
B
16
4.0
3.
C
20
5.0
4.
D
19
2.0
5.
E
19
1.0
6.
F
17
3.0
In this dataset, we have student names, their age, and CGPA as column names. As age is in the range from 15 to 20 and CGPA is ranging from 1.0 to 5.0. We would like to standardize the CGPA and age column. So, our dataset should look like this:
Name
Age
CGPA
1.
A
-1.3561270
1.0206207
2.
B
-0.8475794
0.4082483
3.
C
1.1866111
1.0206207
4.
D
0.6780635
-0.8164966
5.
E
0.6780635
-1.4288690
6.
F
-0.3390318
-0.2041241
Method 1: Using Scale function.
R has a built-in function called scale() for the purpose of standardization.
Syntax: scale(x,center=True,scale=True)
Here, “x” represents the data column/dataset on which you want to apply standardization. “center” parameter takes boolean values, it will subtract the mean from the observation value when it is set to True. “scale” parameter takes boolean values, it will divide the resulting difference by standard deviation when it is set to True.
Approach:
Create dataset
Apply scale function on the data column
Convert the vector result to the data frame
Display result
Program:
R
# Creating DatasetX <- c('A','B','C','D','E','F')Y <- c(15,16,20,19,19,17)Z <- c(5.0,4.0,5.0,2.0,1.0,3.0) dataframe <- data.frame(Name = X, Age = Y, CGPA = Z ) # applying scale functiondataframe[2 : 3] <- as.data.frame(scale(dataframe[2 : 3])) # displaying resultdataframe
Output:
Using Scale
Method 2: Using base R
Approach:
Create Dataset.
Create a function for standardization.
Syntax: standardize = function(x){ z <- (x – mean(x)) / sd(x) return( z)}
Apply this function to the data columns.
Convert the vector result to the data frame
Display result
Program:
R
# Creating DatasetX <- c('A', 'B', 'C', 'D', 'E', 'F')Y <- c(15, 16, 20, 19, 19, 17)Z <- c(5.0, 4.0, 5.0, 2.0, 1.0, 3.0) dataframe <- data.frame(Name = X, Age = Y, CGPA = Z ) # creating Standardization functionstandardize = function(x){ z <- (x - mean(x)) / sd(x) return( z)} # apply your function to the datasetdataframe[2:3] <- apply(dataframe[2:3], 2, standardize) #displaying resultdataframe
Output:
Using Custom standardization function
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "A large dataset that had multiple columns with varying ranges and units may need to be standardized before further processing. In this article, we will be discussing how to standardize a column of dataframe in R Programming Language."
},
{
"code": null,
"e": 450,
"s": 262,
"text": "Let’s first discuss standardization. Standardization is a feature scaling technique. It is the process of rescaling data so that the data have a mean of ‘0’ and standard deviation of ‘1’."
},
{
"code": null,
"e": 459,
"s": 450,
"text": "Formula:"
},
{
"code": null,
"e": 644,
"s": 459,
"text": "Here, is mean and is standard deviation. We are subtracting the mean from each value in observation and then dividing by standard deviation. This is also called the Z-score formula."
},
{
"code": null,
"e": 654,
"s": 644,
"text": "Example :"
},
{
"code": null,
"e": 661,
"s": 656,
"text": "Name"
},
{
"code": null,
"e": 665,
"s": 661,
"text": "Age"
},
{
"code": null,
"e": 670,
"s": 665,
"text": "CGPA"
},
{
"code": null,
"e": 673,
"s": 670,
"text": "1."
},
{
"code": null,
"e": 675,
"s": 673,
"text": "A"
},
{
"code": null,
"e": 679,
"s": 675,
"text": "15 "
},
{
"code": null,
"e": 683,
"s": 679,
"text": "5.0"
},
{
"code": null,
"e": 686,
"s": 683,
"text": "2."
},
{
"code": null,
"e": 688,
"s": 686,
"text": "B"
},
{
"code": null,
"e": 691,
"s": 688,
"text": "16"
},
{
"code": null,
"e": 695,
"s": 691,
"text": "4.0"
},
{
"code": null,
"e": 698,
"s": 695,
"text": "3."
},
{
"code": null,
"e": 700,
"s": 698,
"text": "C"
},
{
"code": null,
"e": 703,
"s": 700,
"text": "20"
},
{
"code": null,
"e": 707,
"s": 703,
"text": "5.0"
},
{
"code": null,
"e": 710,
"s": 707,
"text": "4."
},
{
"code": null,
"e": 712,
"s": 710,
"text": "D"
},
{
"code": null,
"e": 715,
"s": 712,
"text": "19"
},
{
"code": null,
"e": 719,
"s": 715,
"text": "2.0"
},
{
"code": null,
"e": 722,
"s": 719,
"text": "5."
},
{
"code": null,
"e": 724,
"s": 722,
"text": "E"
},
{
"code": null,
"e": 727,
"s": 724,
"text": "19"
},
{
"code": null,
"e": 731,
"s": 727,
"text": "1.0"
},
{
"code": null,
"e": 734,
"s": 731,
"text": "6."
},
{
"code": null,
"e": 736,
"s": 734,
"text": "F"
},
{
"code": null,
"e": 739,
"s": 736,
"text": "17"
},
{
"code": null,
"e": 743,
"s": 739,
"text": "3.0"
},
{
"code": null,
"e": 987,
"s": 743,
"text": "In this dataset, we have student names, their age, and CGPA as column names. As age is in the range from 15 to 20 and CGPA is ranging from 1.0 to 5.0. We would like to standardize the CGPA and age column. So, our dataset should look like this:"
},
{
"code": null,
"e": 994,
"s": 989,
"text": "Name"
},
{
"code": null,
"e": 998,
"s": 994,
"text": "Age"
},
{
"code": null,
"e": 1003,
"s": 998,
"text": "CGPA"
},
{
"code": null,
"e": 1006,
"s": 1003,
"text": "1."
},
{
"code": null,
"e": 1008,
"s": 1006,
"text": "A"
},
{
"code": null,
"e": 1019,
"s": 1008,
"text": "-1.3561270"
},
{
"code": null,
"e": 1029,
"s": 1019,
"text": "1.0206207"
},
{
"code": null,
"e": 1032,
"s": 1029,
"text": "2."
},
{
"code": null,
"e": 1034,
"s": 1032,
"text": "B"
},
{
"code": null,
"e": 1045,
"s": 1034,
"text": "-0.8475794"
},
{
"code": null,
"e": 1055,
"s": 1045,
"text": "0.4082483"
},
{
"code": null,
"e": 1058,
"s": 1055,
"text": "3."
},
{
"code": null,
"e": 1060,
"s": 1058,
"text": "C"
},
{
"code": null,
"e": 1070,
"s": 1060,
"text": "1.1866111"
},
{
"code": null,
"e": 1080,
"s": 1070,
"text": "1.0206207"
},
{
"code": null,
"e": 1083,
"s": 1080,
"text": "4."
},
{
"code": null,
"e": 1085,
"s": 1083,
"text": "D"
},
{
"code": null,
"e": 1095,
"s": 1085,
"text": "0.6780635"
},
{
"code": null,
"e": 1106,
"s": 1095,
"text": "-0.8164966"
},
{
"code": null,
"e": 1109,
"s": 1106,
"text": "5."
},
{
"code": null,
"e": 1111,
"s": 1109,
"text": "E"
},
{
"code": null,
"e": 1121,
"s": 1111,
"text": "0.6780635"
},
{
"code": null,
"e": 1133,
"s": 1121,
"text": " -1.4288690"
},
{
"code": null,
"e": 1136,
"s": 1133,
"text": "6."
},
{
"code": null,
"e": 1138,
"s": 1136,
"text": "F"
},
{
"code": null,
"e": 1149,
"s": 1138,
"text": "-0.3390318"
},
{
"code": null,
"e": 1160,
"s": 1149,
"text": "-0.2041241"
},
{
"code": null,
"e": 1192,
"s": 1160,
"text": "Method 1: Using Scale function."
},
{
"code": null,
"e": 1269,
"s": 1192,
"text": "R has a built-in function called scale() for the purpose of standardization."
},
{
"code": null,
"e": 1309,
"s": 1269,
"text": "Syntax: scale(x,center=True,scale=True)"
},
{
"code": null,
"e": 1643,
"s": 1309,
"text": "Here, “x” represents the data column/dataset on which you want to apply standardization. “center” parameter takes boolean values, it will subtract the mean from the observation value when it is set to True. “scale” parameter takes boolean values, it will divide the resulting difference by standard deviation when it is set to True."
},
{
"code": null,
"e": 1653,
"s": 1643,
"text": "Approach:"
},
{
"code": null,
"e": 1668,
"s": 1653,
"text": "Create dataset"
},
{
"code": null,
"e": 1708,
"s": 1668,
"text": "Apply scale function on the data column"
},
{
"code": null,
"e": 1752,
"s": 1708,
"text": "Convert the vector result to the data frame"
},
{
"code": null,
"e": 1767,
"s": 1752,
"text": "Display result"
},
{
"code": null,
"e": 1776,
"s": 1767,
"text": "Program:"
},
{
"code": null,
"e": 1778,
"s": 1776,
"text": "R"
},
{
"code": "# Creating DatasetX <- c('A','B','C','D','E','F')Y <- c(15,16,20,19,19,17)Z <- c(5.0,4.0,5.0,2.0,1.0,3.0) dataframe <- data.frame(Name = X, Age = Y, CGPA = Z ) # applying scale functiondataframe[2 : 3] <- as.data.frame(scale(dataframe[2 : 3])) # displaying resultdataframe",
"e": 2054,
"s": 1778,
"text": null
},
{
"code": null,
"e": 2062,
"s": 2054,
"text": "Output:"
},
{
"code": null,
"e": 2074,
"s": 2062,
"text": "Using Scale"
},
{
"code": null,
"e": 2097,
"s": 2074,
"text": "Method 2: Using base R"
},
{
"code": null,
"e": 2107,
"s": 2097,
"text": "Approach:"
},
{
"code": null,
"e": 2123,
"s": 2107,
"text": "Create Dataset."
},
{
"code": null,
"e": 2162,
"s": 2123,
"text": "Create a function for standardization."
},
{
"code": null,
"e": 2236,
"s": 2162,
"text": "Syntax: standardize = function(x){ z <- (x – mean(x)) / sd(x) return( z)}"
},
{
"code": null,
"e": 2277,
"s": 2236,
"text": "Apply this function to the data columns."
},
{
"code": null,
"e": 2321,
"s": 2277,
"text": "Convert the vector result to the data frame"
},
{
"code": null,
"e": 2336,
"s": 2321,
"text": "Display result"
},
{
"code": null,
"e": 2345,
"s": 2336,
"text": "Program:"
},
{
"code": null,
"e": 2347,
"s": 2345,
"text": "R"
},
{
"code": "# Creating DatasetX <- c('A', 'B', 'C', 'D', 'E', 'F')Y <- c(15, 16, 20, 19, 19, 17)Z <- c(5.0, 4.0, 5.0, 2.0, 1.0, 3.0) dataframe <- data.frame(Name = X, Age = Y, CGPA = Z ) # creating Standardization functionstandardize = function(x){ z <- (x - mean(x)) / sd(x) return( z)} # apply your function to the datasetdataframe[2:3] <- apply(dataframe[2:3], 2, standardize) #displaying resultdataframe",
"e": 2750,
"s": 2347,
"text": null
},
{
"code": null,
"e": 2758,
"s": 2750,
"text": "Output:"
},
{
"code": null,
"e": 2796,
"s": 2758,
"text": "Using Custom standardization function"
},
{
"code": null,
"e": 2803,
"s": 2796,
"text": "Picked"
},
{
"code": null,
"e": 2815,
"s": 2803,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2826,
"s": 2815,
"text": "R Language"
},
{
"code": null,
"e": 2924,
"s": 2826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2976,
"s": 2924,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 3034,
"s": 2976,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 3086,
"s": 3034,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3144,
"s": 3086,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3176,
"s": 3144,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 3211,
"s": 3176,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3255,
"s": 3211,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 3287,
"s": 3255,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 3325,
"s": 3287,
"text": "How to Change Axis Scales in R Plots?"
}
]
|
What is Vagrant? | 09 Jun, 2021
Vagrant is an open-source tool that helps us to automate the creation and management of Virtual Machines. In a nutshell, we can specify the configuration of a virtual machine in a simple configuration file, and Vagrant creates the same Virtual machine using just one simple command. It provides command-line interfaces to automate such tasks.
Virtual Machine is a machine that does not exist physically but can be used just like a physical computer. Any task that can be done on a physical machine can also be executed in a virtual machine. But Virtual Machine is built on top of a physical system, and multiple virtual machines can be created in a single physical computer. All the virtual machines share the same hardware, but each of them might have a separate operating system. The physical system that hosts all the virtual machines is called the Host Computer. The medium that separates the Host Computer hardware and the virtual environments is something called Hypervisor, or Hyper-V.
Fig: Structure of Virtual Machine
Each Virtual Machine should have its own configuration like operating system, CPUs, RAM, Hard Disk Memory, networking, etc. And the creation of such VMs, manually configuring all the properties is really a hectic task. In this scenario, Vagrant comes into the picture.
Why Vagrant?An application consists of several components which need to be configured properly to run the application. For example, a modern web application might have components like Java, JavaScript, Python, etc. as a language, MySQL, Oracle, MongoDB, etc. as Databases, other components like webserver, load-balancer, API Gateway, Message Queue, etc. based on requirements.
Prior to Vagrant, all these components need to be set up manually. During the setup process, a lot of issues are faced-
In every machine, the setup needs to be done separately, which takes a lot of time.
The manual configuration might be erroneous, which needs to debug and fix every time.
The development, testing, and production environment should be identical. But due to this manual installation and setup of the components, there might be a slight difference which provides us a lot of pain, because, in such a scenario, the application might run in a development environment, but face issues in the production one.
Vagrant is the modern solution to all these problems. Instead of setting up all the components manually, Vagrant provides us the feature of using one configuration file (called Vagrantfile), where all the required software components and their configuration information are specified. So, while this same configuration file is executed in multiple machines, Vagrant creates the Virtual Machine on top of each physical machine, installs and setups all the mentioned components automatically, and provides a ready start-to-work Virtual Machine. And since this provides a Virtual Machine, there is no need to bother about whether one software component would run on Windows OS or Linux OS and what should be their configuration and also developer, QA both work in a separate machine, but both machines should have a completely identical setup.
Terminologies Of Vagrant: Before getting into the details of Installation and how to use Vagrant, let’s first discuss the basic terminologies related to Vagrant.
1. Vagrant Box: The basic unit of Vagrant setup is Vagrant Box. Just like Docker Image, Vagrant Box is a self-contained image of the Operating System. More specifically, it is a packaged Virtual Machine. Instead of installing an operating system and all the software components inside a VM manually,
The vagrant box is a ready-made base image of a Virtual Machine Environment.
For example, if there is a need to get some VM with all default setups of Spring Boot application development, one can get the same Vagrant Box. All that is required to do is to download the Vagrant Box and run it. Vagrant creates the VM and development work can be started immediately.
A lot of Vagrant Box is present in Vagrant Cloud box catalog, which we can use as a base image for our own Virtual Machine.
2. Vagrant File: Vagrant maintains one configuration file, called Vagrantfile, where all configurations of a VM are mentioned. And Vagrant creates the Virtual Machine with the same configuration mentioned in the file. Even if there is a need to install some software in the VM, one can specify the same in Vagrantfile, and Vagrant downloads and installs the same for us.
Let’s look into the steps for provisioning one VM using Vagrant.
Step 1: Download Vagrant based on your operating system and install it in the system.Step 2: Verify vagrant installation using command vagrant -v in command prompt. It will show the version of our vagrant installed as below.
Step 3: Download Virtual Box based on your operating system and install it in the system.
Step 1: Create a folder where we want to save all the Vagrant-related files.Step 2: Create a file, named Vagrantfile for mentioning the configuration of the VM. Since this is the first time Vagrant is being used after the installation, so it is advisable to let Vagrant creates the file for us with minimum configuration. And modification can be done later.Step 3: Open PowerShell (for Windows) or Terminal (for Linux) and go to the location of the folder that was created in step 1.Step 4: Run command vagrant init bento/ubuntu-16.04, and let the execution complete. This command will initialize the directory with the specified Vagrant Box (bento/ubuntu-16.04). We will find Vagrantfile created in this location. If opened, you will see that some sample configuration has already been mentioned with proper examples and all of them are commented. Anyone can check it out to build a Virtual Machine with a more specific configuration. A piece of important information mentioned in the file can be seen.
config.vm.box = "bento/ubuntu-16.04"
This is the Vagrant Box, that was mentioned during initialization.
Boot up Virtual Machine Using Vagrant:
vagrant up
This command will take Vagrantfile and provision one VM with all the configurations mentioned. For now, it boots up a Virtual machine with a Ubuntu-16.04 version of the Operating System.
Step 1: Now, the VM has been created. So, to get into it, run command vagrant ssh. After executing this command you are now inside the newly created VM. Now, anything can be done inside the VM through this terminal. The following screen will be visible-
Step 2: To log out from Virtual Machine, run the command logout. Again the terminal will come back to the host machine.
Step 1: To shut down the VM using Vagrant, run command vagrant halt. This command will switch off the VM and again to power on the VM, run vagrant up command.
Step 2: In order to shut down a Virtual Machine, keeping its current state, run vagrant suspend. In this case, when the VM is started again using vagrant up, the system will start from the same position where it left off. All unsaved work can be restored.But in this case, VM will not release the resources from the Host Machine, even it takes some more disk space to store the current state of its own RAM inside the Host Machine.
Step 3: To delete the VM with all its resources, run vagrant destroy. This command will shut down the VM and delete it from the Host System.
Let’s install a web server inside VM and access the same from your host computer. Follow the steps below-
Step 1: Do vagrant ssh, to go into the VM created.Step 2: Inside the VM, install a web server, say Nginx, manually. Run below commands-
sudo apt update
sudo apt install nginx
Step 3: Check whether the Nginx service is running or not using the command-
systemctl status nginx
If the service is not running, start the service using the command-
sudo service nginx start
Note- The above installation can also be done with the Vagrantfile, but for now, let’s use vagrant ssh functionality.
Step 4: Go to /var/www/html and create one sample HTML file, say index1.html as below-
HTML
<!DOCTYPE html><html> <body> <h2 style = "color: green"> Welcome to GeeksforGeeks </h2> <body></html>
Step 5: Now Nginx is running in its default port 80 inside the VM. But to access the VM’s Nginx server from the Host Machine, it is required to map port 80 of VM with some port in Host Computer. And this mapping is called Port Forwarding. Port forwarding can be done manually using Virtual Box Manager. But since Vagrant is being used here, let’s do it using Vagrantfile.Step 6: Open Vagrantfile and add the line
config.vm.network "forwarded_port", guest: 80, host: 85
after the line
config.vm.box = "bento/ubuntu-16.04"
and save the file.
Here basically the 80 port of VM is mapped with 85 port of the host system.Step 7: Exit from the VM in PowerShell or terminal and run the command vagrant reload to reload the new setting that we added in Vagrantfile. During reload, one can see the forwarded port as below. In the below snapshot, the first forwarded port is the one that is recently added and the second one is the default for SSH connectivity.
Step 8: Check whether Nginx is running or not. Now the Nginx server of the VM can be accessed using 85 port from the host system. The HTML file created above can be retrieved, using the URL- localhost:85/index1.html
Advantages Of Vagrant:
Vagrant is free and open-source.
It offers extremely efficient project scaffolding of a dev/ test environment.
Vagrant has a great variety of community boxes and plugins.
Disadvantages Of Vagrant:
Syntax updates have major repercussions for the plugin compatibility
Community support is good, but it is a lengthy process.
Major updates have introduced some serious bugs with consequences in the dev projects.
samandal2021
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 372,
"s": 28,
"text": "Vagrant is an open-source tool that helps us to automate the creation and management of Virtual Machines. In a nutshell, we can specify the configuration of a virtual machine in a simple configuration file, and Vagrant creates the same Virtual machine using just one simple command. It provides command-line interfaces to automate such tasks. "
},
{
"code": null,
"e": 1024,
"s": 372,
"text": "Virtual Machine is a machine that does not exist physically but can be used just like a physical computer. Any task that can be done on a physical machine can also be executed in a virtual machine. But Virtual Machine is built on top of a physical system, and multiple virtual machines can be created in a single physical computer. All the virtual machines share the same hardware, but each of them might have a separate operating system. The physical system that hosts all the virtual machines is called the Host Computer. The medium that separates the Host Computer hardware and the virtual environments is something called Hypervisor, or Hyper-V. "
},
{
"code": null,
"e": 1060,
"s": 1026,
"text": "Fig: Structure of Virtual Machine"
},
{
"code": null,
"e": 1330,
"s": 1060,
"text": "Each Virtual Machine should have its own configuration like operating system, CPUs, RAM, Hard Disk Memory, networking, etc. And the creation of such VMs, manually configuring all the properties is really a hectic task. In this scenario, Vagrant comes into the picture. "
},
{
"code": null,
"e": 1709,
"s": 1330,
"text": "Why Vagrant?An application consists of several components which need to be configured properly to run the application. For example, a modern web application might have components like Java, JavaScript, Python, etc. as a language, MySQL, Oracle, MongoDB, etc. as Databases, other components like webserver, load-balancer, API Gateway, Message Queue, etc. based on requirements. "
},
{
"code": null,
"e": 1829,
"s": 1709,
"text": "Prior to Vagrant, all these components need to be set up manually. During the setup process, a lot of issues are faced-"
},
{
"code": null,
"e": 1913,
"s": 1829,
"text": "In every machine, the setup needs to be done separately, which takes a lot of time."
},
{
"code": null,
"e": 1999,
"s": 1913,
"text": "The manual configuration might be erroneous, which needs to debug and fix every time."
},
{
"code": null,
"e": 2330,
"s": 1999,
"text": "The development, testing, and production environment should be identical. But due to this manual installation and setup of the components, there might be a slight difference which provides us a lot of pain, because, in such a scenario, the application might run in a development environment, but face issues in the production one."
},
{
"code": null,
"e": 3174,
"s": 2330,
"text": "Vagrant is the modern solution to all these problems. Instead of setting up all the components manually, Vagrant provides us the feature of using one configuration file (called Vagrantfile), where all the required software components and their configuration information are specified. So, while this same configuration file is executed in multiple machines, Vagrant creates the Virtual Machine on top of each physical machine, installs and setups all the mentioned components automatically, and provides a ready start-to-work Virtual Machine. And since this provides a Virtual Machine, there is no need to bother about whether one software component would run on Windows OS or Linux OS and what should be their configuration and also developer, QA both work in a separate machine, but both machines should have a completely identical setup. "
},
{
"code": null,
"e": 3336,
"s": 3174,
"text": "Terminologies Of Vagrant: Before getting into the details of Installation and how to use Vagrant, let’s first discuss the basic terminologies related to Vagrant."
},
{
"code": null,
"e": 3637,
"s": 3336,
"text": "1. Vagrant Box: The basic unit of Vagrant setup is Vagrant Box. Just like Docker Image, Vagrant Box is a self-contained image of the Operating System. More specifically, it is a packaged Virtual Machine. Instead of installing an operating system and all the software components inside a VM manually, "
},
{
"code": null,
"e": 3714,
"s": 3637,
"text": "The vagrant box is a ready-made base image of a Virtual Machine Environment."
},
{
"code": null,
"e": 4001,
"s": 3714,
"text": "For example, if there is a need to get some VM with all default setups of Spring Boot application development, one can get the same Vagrant Box. All that is required to do is to download the Vagrant Box and run it. Vagrant creates the VM and development work can be started immediately."
},
{
"code": null,
"e": 4125,
"s": 4001,
"text": "A lot of Vagrant Box is present in Vagrant Cloud box catalog, which we can use as a base image for our own Virtual Machine."
},
{
"code": null,
"e": 4497,
"s": 4125,
"text": "2. Vagrant File: Vagrant maintains one configuration file, called Vagrantfile, where all configurations of a VM are mentioned. And Vagrant creates the Virtual Machine with the same configuration mentioned in the file. Even if there is a need to install some software in the VM, one can specify the same in Vagrantfile, and Vagrant downloads and installs the same for us. "
},
{
"code": null,
"e": 4563,
"s": 4497,
"text": "Let’s look into the steps for provisioning one VM using Vagrant. "
},
{
"code": null,
"e": 4789,
"s": 4563,
"text": "Step 1: Download Vagrant based on your operating system and install it in the system.Step 2: Verify vagrant installation using command vagrant -v in command prompt. It will show the version of our vagrant installed as below. "
},
{
"code": null,
"e": 4879,
"s": 4789,
"text": "Step 3: Download Virtual Box based on your operating system and install it in the system."
},
{
"code": null,
"e": 5884,
"s": 4879,
"text": "Step 1: Create a folder where we want to save all the Vagrant-related files.Step 2: Create a file, named Vagrantfile for mentioning the configuration of the VM. Since this is the first time Vagrant is being used after the installation, so it is advisable to let Vagrant creates the file for us with minimum configuration. And modification can be done later.Step 3: Open PowerShell (for Windows) or Terminal (for Linux) and go to the location of the folder that was created in step 1.Step 4: Run command vagrant init bento/ubuntu-16.04, and let the execution complete. This command will initialize the directory with the specified Vagrant Box (bento/ubuntu-16.04). We will find Vagrantfile created in this location. If opened, you will see that some sample configuration has already been mentioned with proper examples and all of them are commented. Anyone can check it out to build a Virtual Machine with a more specific configuration. A piece of important information mentioned in the file can be seen."
},
{
"code": null,
"e": 5921,
"s": 5884,
"text": "config.vm.box = \"bento/ubuntu-16.04\""
},
{
"code": null,
"e": 5988,
"s": 5921,
"text": "This is the Vagrant Box, that was mentioned during initialization."
},
{
"code": null,
"e": 6028,
"s": 5988,
"text": "Boot up Virtual Machine Using Vagrant: "
},
{
"code": null,
"e": 6039,
"s": 6028,
"text": "vagrant up"
},
{
"code": null,
"e": 6226,
"s": 6039,
"text": "This command will take Vagrantfile and provision one VM with all the configurations mentioned. For now, it boots up a Virtual machine with a Ubuntu-16.04 version of the Operating System."
},
{
"code": null,
"e": 6480,
"s": 6226,
"text": "Step 1: Now, the VM has been created. So, to get into it, run command vagrant ssh. After executing this command you are now inside the newly created VM. Now, anything can be done inside the VM through this terminal. The following screen will be visible-"
},
{
"code": null,
"e": 6600,
"s": 6480,
"text": "Step 2: To log out from Virtual Machine, run the command logout. Again the terminal will come back to the host machine."
},
{
"code": null,
"e": 6759,
"s": 6600,
"text": "Step 1: To shut down the VM using Vagrant, run command vagrant halt. This command will switch off the VM and again to power on the VM, run vagrant up command."
},
{
"code": null,
"e": 7191,
"s": 6759,
"text": "Step 2: In order to shut down a Virtual Machine, keeping its current state, run vagrant suspend. In this case, when the VM is started again using vagrant up, the system will start from the same position where it left off. All unsaved work can be restored.But in this case, VM will not release the resources from the Host Machine, even it takes some more disk space to store the current state of its own RAM inside the Host Machine."
},
{
"code": null,
"e": 7333,
"s": 7191,
"text": "Step 3: To delete the VM with all its resources, run vagrant destroy. This command will shut down the VM and delete it from the Host System. "
},
{
"code": null,
"e": 7439,
"s": 7333,
"text": "Let’s install a web server inside VM and access the same from your host computer. Follow the steps below-"
},
{
"code": null,
"e": 7575,
"s": 7439,
"text": "Step 1: Do vagrant ssh, to go into the VM created.Step 2: Inside the VM, install a web server, say Nginx, manually. Run below commands-"
},
{
"code": null,
"e": 7614,
"s": 7575,
"text": "sudo apt update\nsudo apt install nginx"
},
{
"code": null,
"e": 7691,
"s": 7614,
"text": "Step 3: Check whether the Nginx service is running or not using the command-"
},
{
"code": null,
"e": 7714,
"s": 7691,
"text": "systemctl status nginx"
},
{
"code": null,
"e": 7782,
"s": 7714,
"text": "If the service is not running, start the service using the command-"
},
{
"code": null,
"e": 7807,
"s": 7782,
"text": "sudo service nginx start"
},
{
"code": null,
"e": 7925,
"s": 7807,
"text": "Note- The above installation can also be done with the Vagrantfile, but for now, let’s use vagrant ssh functionality."
},
{
"code": null,
"e": 8013,
"s": 7925,
"text": "Step 4: Go to /var/www/html and create one sample HTML file, say index1.html as below- "
},
{
"code": null,
"e": 8018,
"s": 8013,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2 style = \"color: green\"> Welcome to GeeksforGeeks </h2> <body></html>",
"e": 8127,
"s": 8018,
"text": null
},
{
"code": null,
"e": 8540,
"s": 8127,
"text": "Step 5: Now Nginx is running in its default port 80 inside the VM. But to access the VM’s Nginx server from the Host Machine, it is required to map port 80 of VM with some port in Host Computer. And this mapping is called Port Forwarding. Port forwarding can be done manually using Virtual Box Manager. But since Vagrant is being used here, let’s do it using Vagrantfile.Step 6: Open Vagrantfile and add the line"
},
{
"code": null,
"e": 8597,
"s": 8540,
"text": "config.vm.network \"forwarded_port\", guest: 80, host: 85 "
},
{
"code": null,
"e": 8612,
"s": 8597,
"text": "after the line"
},
{
"code": null,
"e": 8650,
"s": 8612,
"text": "config.vm.box = \"bento/ubuntu-16.04\" "
},
{
"code": null,
"e": 8669,
"s": 8650,
"text": "and save the file."
},
{
"code": null,
"e": 9080,
"s": 8669,
"text": "Here basically the 80 port of VM is mapped with 85 port of the host system.Step 7: Exit from the VM in PowerShell or terminal and run the command vagrant reload to reload the new setting that we added in Vagrantfile. During reload, one can see the forwarded port as below. In the below snapshot, the first forwarded port is the one that is recently added and the second one is the default for SSH connectivity."
},
{
"code": null,
"e": 9298,
"s": 9080,
"text": "Step 8: Check whether Nginx is running or not. Now the Nginx server of the VM can be accessed using 85 port from the host system. The HTML file created above can be retrieved, using the URL- localhost:85/index1.html "
},
{
"code": null,
"e": 9321,
"s": 9298,
"text": "Advantages Of Vagrant:"
},
{
"code": null,
"e": 9354,
"s": 9321,
"text": "Vagrant is free and open-source."
},
{
"code": null,
"e": 9432,
"s": 9354,
"text": "It offers extremely efficient project scaffolding of a dev/ test environment."
},
{
"code": null,
"e": 9492,
"s": 9432,
"text": "Vagrant has a great variety of community boxes and plugins."
},
{
"code": null,
"e": 9518,
"s": 9492,
"text": "Disadvantages Of Vagrant:"
},
{
"code": null,
"e": 9587,
"s": 9518,
"text": "Syntax updates have major repercussions for the plugin compatibility"
},
{
"code": null,
"e": 9643,
"s": 9587,
"text": "Community support is good, but it is a lengthy process."
},
{
"code": null,
"e": 9730,
"s": 9643,
"text": "Major updates have introduced some serious bugs with consequences in the dev projects."
},
{
"code": null,
"e": 9743,
"s": 9730,
"text": "samandal2021"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "Advanced Computer Subject"
}
]
|
How to Improve Performance of PC/Laptop? | 21 Aug, 2021
More often than not people encounter performance issues with their personal computer after a significant time. These can occur due to various issues. Some key factors and their resolution is given in this article.
Follow the below steps to delete all temporary files:
Click on the start button and type “RUN”.
Inside run type “%temp%”. This will open the temp folder.
Select all files and folders and press Shift + delete and click yes to permanently delete all the files and folders.
To delete the temporary files from the command prompt:
Click on the start button
Type “cmd” and hit enter. This will open a command prompt.
Run the following command:
del /q/f/s %TEMP%\*
Refer to this image for step 2
Follow the below steps to delete the MS office file cache:
Click on the start button and type “RUN”.
Inside run type “%localappdata%”. This will open “C:\Users\hp\AppData\Local” folder.
Open folder named “Microsoft”.
Inside Microsoft, open folder named “Office”, inside it open 16.0 folder, inside it open officefilecache folder.
Select all files other than the Decision table and press Shift + delete and click yes to permanently delete all the files and folders.
For disk clean up follow the below steps:
Click on the start button and type “Disk Cleanup.
Disk cleanup will calculate the free space on your computer, which may take a few minutes. After the calculation is complete, you should see a dialog box that looks similar to the following:
Confirm that only the following checkboxes are checked.
Temporary files.Recycle Bin.Temporary internet files.Download Program files.
Temporary files.
Recycle Bin.
Temporary internet files.
Download Program files.
Click OK, you will see a dialog box that prompts to permanently delete these files?
Click delete files.
Disk Clean up will delete the files and folders and close automatically.
To disable startup programs follow the below steps:
Click on the start button and type “startup Apps”.
Switch to off or disable the apps which are putting high impact or medium impact which won’t impact the normal PC working. Do not disable the apps if you are not sure about their process or functioning.
Uninstalling apps will surely free up lots of space, you can delete the applications which you do not use or which is of no use to you.
Click on the start button and type “add or remove programs“.
Click on it and single click on the application that you want to uninstall, just after clicking on app, it will show uninstall option.
Click on uninstall to uninstall that app.
Free up as much space as you can, this will make computer work faster. Also only open the apps which you need to work on at one time, close apps which do you need at one time, this will reduce CPU speed and your system will work faster. you can check your system’s CPU speed by typing task manager in search box.
If you still face slow computer issue:
Increase your system’s RAM size.Change your HDD hard disk with SSD(Solid State Drive).DO NOT keep more than 300 mb of data on Desktop, this will slow down your PC.
Increase your system’s RAM size.
Change your HDD hard disk with SSD(Solid State Drive).
DO NOT keep more than 300 mb of data on Desktop, this will slow down your PC.
Dell
HP
How To
TechTips
Dell
HP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "More often than not people encounter performance issues with their personal computer after a significant time. These can occur due to various issues. Some key factors and their resolution is given in this article."
},
{
"code": null,
"e": 296,
"s": 242,
"text": "Follow the below steps to delete all temporary files:"
},
{
"code": null,
"e": 338,
"s": 296,
"text": "Click on the start button and type “RUN”."
},
{
"code": null,
"e": 396,
"s": 338,
"text": "Inside run type “%temp%”. This will open the temp folder."
},
{
"code": null,
"e": 513,
"s": 396,
"text": "Select all files and folders and press Shift + delete and click yes to permanently delete all the files and folders."
},
{
"code": null,
"e": 568,
"s": 513,
"text": "To delete the temporary files from the command prompt:"
},
{
"code": null,
"e": 595,
"s": 568,
"text": "Click on the start button "
},
{
"code": null,
"e": 654,
"s": 595,
"text": "Type “cmd” and hit enter. This will open a command prompt."
},
{
"code": null,
"e": 681,
"s": 654,
"text": "Run the following command:"
},
{
"code": null,
"e": 701,
"s": 681,
"text": "del /q/f/s %TEMP%\\*"
},
{
"code": null,
"e": 732,
"s": 701,
"text": "Refer to this image for step 2"
},
{
"code": null,
"e": 791,
"s": 732,
"text": "Follow the below steps to delete the MS office file cache:"
},
{
"code": null,
"e": 833,
"s": 791,
"text": "Click on the start button and type “RUN”."
},
{
"code": null,
"e": 919,
"s": 833,
"text": "Inside run type “%localappdata%”. This will open “C:\\Users\\hp\\AppData\\Local” folder."
},
{
"code": null,
"e": 950,
"s": 919,
"text": "Open folder named “Microsoft”."
},
{
"code": null,
"e": 1063,
"s": 950,
"text": "Inside Microsoft, open folder named “Office”, inside it open 16.0 folder, inside it open officefilecache folder."
},
{
"code": null,
"e": 1198,
"s": 1063,
"text": "Select all files other than the Decision table and press Shift + delete and click yes to permanently delete all the files and folders."
},
{
"code": null,
"e": 1240,
"s": 1198,
"text": "For disk clean up follow the below steps:"
},
{
"code": null,
"e": 1291,
"s": 1240,
"text": "Click on the start button and type “Disk Cleanup. "
},
{
"code": null,
"e": 1482,
"s": 1291,
"text": "Disk cleanup will calculate the free space on your computer, which may take a few minutes. After the calculation is complete, you should see a dialog box that looks similar to the following:"
},
{
"code": null,
"e": 1538,
"s": 1482,
"text": "Confirm that only the following checkboxes are checked."
},
{
"code": null,
"e": 1615,
"s": 1538,
"text": "Temporary files.Recycle Bin.Temporary internet files.Download Program files."
},
{
"code": null,
"e": 1632,
"s": 1615,
"text": "Temporary files."
},
{
"code": null,
"e": 1645,
"s": 1632,
"text": "Recycle Bin."
},
{
"code": null,
"e": 1671,
"s": 1645,
"text": "Temporary internet files."
},
{
"code": null,
"e": 1695,
"s": 1671,
"text": "Download Program files."
},
{
"code": null,
"e": 1779,
"s": 1695,
"text": "Click OK, you will see a dialog box that prompts to permanently delete these files?"
},
{
"code": null,
"e": 1799,
"s": 1779,
"text": "Click delete files."
},
{
"code": null,
"e": 1872,
"s": 1799,
"text": "Disk Clean up will delete the files and folders and close automatically."
},
{
"code": null,
"e": 1924,
"s": 1872,
"text": "To disable startup programs follow the below steps:"
},
{
"code": null,
"e": 1975,
"s": 1924,
"text": "Click on the start button and type “startup Apps”."
},
{
"code": null,
"e": 2178,
"s": 1975,
"text": "Switch to off or disable the apps which are putting high impact or medium impact which won’t impact the normal PC working. Do not disable the apps if you are not sure about their process or functioning."
},
{
"code": null,
"e": 2314,
"s": 2178,
"text": "Uninstalling apps will surely free up lots of space, you can delete the applications which you do not use or which is of no use to you."
},
{
"code": null,
"e": 2375,
"s": 2314,
"text": "Click on the start button and type “add or remove programs“."
},
{
"code": null,
"e": 2510,
"s": 2375,
"text": "Click on it and single click on the application that you want to uninstall, just after clicking on app, it will show uninstall option."
},
{
"code": null,
"e": 2552,
"s": 2510,
"text": "Click on uninstall to uninstall that app."
},
{
"code": null,
"e": 2865,
"s": 2552,
"text": "Free up as much space as you can, this will make computer work faster. Also only open the apps which you need to work on at one time, close apps which do you need at one time, this will reduce CPU speed and your system will work faster. you can check your system’s CPU speed by typing task manager in search box."
},
{
"code": null,
"e": 2904,
"s": 2865,
"text": "If you still face slow computer issue:"
},
{
"code": null,
"e": 3068,
"s": 2904,
"text": "Increase your system’s RAM size.Change your HDD hard disk with SSD(Solid State Drive).DO NOT keep more than 300 mb of data on Desktop, this will slow down your PC."
},
{
"code": null,
"e": 3101,
"s": 3068,
"text": "Increase your system’s RAM size."
},
{
"code": null,
"e": 3156,
"s": 3101,
"text": "Change your HDD hard disk with SSD(Solid State Drive)."
},
{
"code": null,
"e": 3234,
"s": 3156,
"text": "DO NOT keep more than 300 mb of data on Desktop, this will slow down your PC."
},
{
"code": null,
"e": 3239,
"s": 3234,
"text": "Dell"
},
{
"code": null,
"e": 3242,
"s": 3239,
"text": "HP"
},
{
"code": null,
"e": 3249,
"s": 3242,
"text": "How To"
},
{
"code": null,
"e": 3258,
"s": 3249,
"text": "TechTips"
},
{
"code": null,
"e": 3263,
"s": 3258,
"text": "Dell"
},
{
"code": null,
"e": 3266,
"s": 3263,
"text": "HP"
}
]
|
How to Resize JPEG Image in PHP ? | 27 May, 2020
Why do we need to resize images?In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those cases, it’s not feasible to manually resize the image always.
One way to solve the above problem is to use the following method where we need to just set the width and height attributes on the image tag in our HTML.
<img src="check.jpg" height="100" width="100" alt="Image resize">
The problem with this is that the entire image is downloaded from the server and it is shown in the decreased size within the browser. This means the same amount of bandwidth is required to show the image in the smaller size that would have been required in case of the original size.
Using PHP to resize the image on server end: We will be henceforth using PHP to decrease the image dimension and render it so that a smaller size is only downloaded on the client end and not the original image. To achieve this we will be using the imagecopyresampled() function in PHP.
The imagecopyresampled() function is used to copy and resize an image or part of the image with resampling.
Syntax:
bool imagecopyresampled( resource $dst_image, resource $src_image,
int $dst_x, int $dst_y, int $src_x, int $src_y,
int $dst_w, int $dst_h, int $src_w, int $src_h )
Parameters: This function accepts a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).
Example: This example uses imagecopyresampled() function to resize the image.
<?php // The file concerned$filename = 'check.jpg'; // Maximum width and height$width = 100;$height = 100; // File typeheader('Content-Type: image/jpg'); // Get new dimensionslist($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig;} else { $height = $width/$ratio_orig;} // Resampling the image $image_p = imagecreatetruecolor($width, $height);$image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Display of output imageimagejpeg($image_p, null, 100); ?>
Output:
Original Image:
Output Image:
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
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 ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2020"
},
{
"code": null,
"e": 388,
"s": 28,
"text": "Why do we need to resize images?In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those cases, it’s not feasible to manually resize the image always."
},
{
"code": null,
"e": 542,
"s": 388,
"text": "One way to solve the above problem is to use the following method where we need to just set the width and height attributes on the image tag in our HTML."
},
{
"code": null,
"e": 608,
"s": 542,
"text": "<img src=\"check.jpg\" height=\"100\" width=\"100\" alt=\"Image resize\">"
},
{
"code": null,
"e": 893,
"s": 608,
"text": "The problem with this is that the entire image is downloaded from the server and it is shown in the decreased size within the browser. This means the same amount of bandwidth is required to show the image in the smaller size that would have been required in case of the original size."
},
{
"code": null,
"e": 1179,
"s": 893,
"text": "Using PHP to resize the image on server end: We will be henceforth using PHP to decrease the image dimension and render it so that a smaller size is only downloaded on the client end and not the original image. To achieve this we will be using the imagecopyresampled() function in PHP."
},
{
"code": null,
"e": 1287,
"s": 1179,
"text": "The imagecopyresampled() function is used to copy and resize an image or part of the image with resampling."
},
{
"code": null,
"e": 1295,
"s": 1287,
"text": "Syntax:"
},
{
"code": null,
"e": 1495,
"s": 1295,
"text": "bool imagecopyresampled( resource $dst_image, resource $src_image,\n int $dst_x, int $dst_y, int $src_x, int $src_y,\n int $dst_w, int $dst_h, int $src_w, int $src_h )"
},
{
"code": null,
"e": 1740,
"s": 1495,
"text": "Parameters: This function accepts a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y)."
},
{
"code": null,
"e": 1818,
"s": 1740,
"text": "Example: This example uses imagecopyresampled() function to resize the image."
},
{
"code": "<?php // The file concerned$filename = 'check.jpg'; // Maximum width and height$width = 100;$height = 100; // File typeheader('Content-Type: image/jpg'); // Get new dimensionslist($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig;} else { $height = $width/$ratio_orig;} // Resampling the image $image_p = imagecreatetruecolor($width, $height);$image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Display of output imageimagejpeg($image_p, null, 100); ?>",
"e": 2489,
"s": 1818,
"text": null
},
{
"code": null,
"e": 2497,
"s": 2489,
"text": "Output:"
},
{
"code": null,
"e": 2513,
"s": 2497,
"text": "Original Image:"
},
{
"code": null,
"e": 2527,
"s": 2513,
"text": "Output Image:"
},
{
"code": null,
"e": 2536,
"s": 2527,
"text": "PHP-Misc"
},
{
"code": null,
"e": 2543,
"s": 2536,
"text": "Picked"
},
{
"code": null,
"e": 2547,
"s": 2543,
"text": "PHP"
},
{
"code": null,
"e": 2560,
"s": 2547,
"text": "PHP Programs"
},
{
"code": null,
"e": 2577,
"s": 2560,
"text": "Web Technologies"
},
{
"code": null,
"e": 2604,
"s": 2577,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2608,
"s": 2604,
"text": "PHP"
},
{
"code": null,
"e": 2706,
"s": 2608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2788,
"s": 2706,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2833,
"s": 2788,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 2884,
"s": 2833,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 2914,
"s": 2884,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 2937,
"s": 2914,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2989,
"s": 2937,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 3071,
"s": 2989,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 3094,
"s": 3071,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 3136,
"s": 3094,
"text": "How to create admin login page using PHP?"
}
]
|
tidyr Package in R Programming | 06 Aug, 2020
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the process of creating tidy data. Tidy data describes a standard way of storing data that is used wherever possible throughout the tidyverse. If you once make sure that your data is tidy, you’ll spend less time punching with the tools and more time working on your analysis.
To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”). To install the whole tidyverse package type this:
install.packages("tidyverse")
Alternatively, to install just tidyr package type this:
install.packages("tidyr")
To install the development version from GitHub type this:
# install.packages("devtools")
devtools::install_github("tidyverse/tidyr")
The Dataset:
Before going to the important verb function let’s prepare the data set first. Define a dataset tidy_dataframe that contains data about the frequency of people in a particular group.
R
# load the tidyr packagelibrary(tidyr) n = 10# creating a data frametidy_dataframe = data.frame( S.No = c(1:n), Group.1 = c(23, 345, 76, 212, 88, 199, 72, 35, 90, 265), Group.2 = c(117, 89, 66, 334, 90, 101, 178, 233, 45, 200), Group.3 = c(29, 101, 239, 289, 176, 320, 89, 109, 199, 56)) # print the elements of the data frametidy_dataframe
Output:
S.No Group.1 Group.2 Group.3
1 1 23 117 29
2 2 345 89 101
3 3 76 66 239
4 4 212 334 289
5 5 88 90 176
6 6 199 101 320
7 7 72 178 89
8 8 35 233 109
9 9 90 45 199
10 10 265 200 56
tidyr package provides various important functions that can be used for Data Cleaning. Those are:
gather() function: It takes multiple columns and gathers them into key-value pairs. Basically it makes “wide” data longer. The gather() function will take multiple columns and collapse them into key-value pairs, duplicating all other columns as needed.
Syntax:
gather(data, key = “key”, value = “value”, ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)
Parameter
Description
the names of new key and value columns,
as strings or as symbols.
the selection of columns. If left empty, all variables are selected.
You can supply bare variable names, select all variables between
x and z with x:z, exclude y with -y.
is set TRUE, it will automatically run type.convert() on the key column.
This is useful if the column types are actually numeric,
integer, or logical.
if FALSE, the default, the key values will be stored as a character vector.
If TRUE, will be stored as a factor, which preserves
the original ordering of the columns.
Example:
Now for a better understanding, we will make our data long with gather() function.
R
# using gather() function on tidy_dataframelong <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # print the data frame in a long formatlong
Output:
S.No Group Frequency
1 1 Group.1 23
2 2 Group.1 345
3 3 Group.1 76
4 4 Group.1 212
5 5 Group.1 88
6 6 Group.1 199
7 7 Group.1 72
8 8 Group.1 35
9 9 Group.1 90
10 10 Group.1 265
11 1 Group.2 117
12 2 Group.2 89
13 3 Group.2 66
14 4 Group.2 334
15 5 Group.2 90
16 6 Group.2 101
17 7 Group.2 178
18 8 Group.2 233
19 9 Group.2 45
20 10 Group.2 200
21 1 Group.3 29
22 2 Group.3 101
23 3 Group.3 239
24 4 Group.3 289
25 5 Group.3 176
26 6 Group.3 320
27 7 Group.3 89
28 8 Group.3 109
29 9 Group.3 199
30 10 Group.3 56
separate() function: It converts longer data to a wider format. The separate() function turns a single character column into multiple columns.
Syntax:
separate(data, col, into, sep = ” “, remove = TRUE, convert = FALSE)
Parameter
Description
Names of new variables to create as character vector.
Use NA to omit the variable in the output.
Example:
We can say that the long datasets created using gather() is appropriate for use, but we can break down Group variable even further using separate().
R
# import tidyr packagelibrary(tidyr)long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c("Allotment", "Number")) # print the wider formatseparate_data
Output:
S.No Allotment Number Frequency
1 1 Group 1 23
2 2 Group 1 345
3 3 Group 1 76
4 4 Group 1 212
5 5 Group 1 88
6 6 Group 1 199
7 7 Group 1 72
8 8 Group 1 35
9 9 Group 1 90
10 10 Group 1 265
11 1 Group 2 117
12 2 Group 2 89
13 3 Group 2 66
14 4 Group 2 334
15 5 Group 2 90
16 6 Group 2 101
17 7 Group 2 178
18 8 Group 2 233
19 9 Group 2 45
20 10 Group 2 200
21 1 Group 3 29
22 2 Group 3 101
23 3 Group 3 239
24 4 Group 3 289
25 5 Group 3 176
26 6 Group 3 320
27 7 Group 3 89
28 8 Group 3 109
29 9 Group 3 199
30 10 Group 3 56
unite() function: It merges two columns into one column. The unite() function is a convenience function to paste together multiple variable values into one. In essence, it combines two variables of a single observation into one variable.
Syntax:
unite(data, col, ..., sep = “_”, remove = TRUE)
Description
Example:
Unite is the compliment of separate. To undo separate(), we can use unite(), which merges two variables into one. Here we will merge two columns Group and Number with a separator “.”.
R
# import tidyr package library(tidyr) long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c("Allotment", "Number")) # use unite() function to glue # Allotment and Number columnsunite_data <- separate_data %>% unite(Group, Allotment, Number, sep = ".") # print the new data frameunite_data
Output:
S.No Group Frequency
1 1 Group.1 23
2 2 Group.1 345
3 3 Group.1 76
4 4 Group.1 212
5 5 Group.1 88
6 6 Group.1 199
7 7 Group.1 72
8 8 Group.1 35
9 9 Group.1 90
10 10 Group.1 265
11 1 Group.2 117
12 2 Group.2 89
13 3 Group.2 66
14 4 Group.2 334
15 5 Group.2 90
16 6 Group.2 101
17 7 Group.2 178
18 8 Group.2 233
19 9 Group.2 45
20 10 Group.2 200
21 1 Group.3 29
22 2 Group.3 101
23 3 Group.3 239
24 4 Group.3 289
25 5 Group.3 176
26 6 Group.3 320
27 7 Group.3 89
28 8 Group.3 109
29 9 Group.3 199
30 10 Group.3 56
spread() function: It helps in reshaping a longer format to a wider format. The spread() function spreads a key-value pair across multiple columns.
Syntax:
spread(data, key, value, fill = NA, convert = FALSE)
Description
Example:
We can transform the data from long back to wide with the spread() function.
R
# import tidyr package library(tidyr) long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c("Allotment", "Number")) # use unite() function to glue# Allotment and Number columnsunite_data <- separate_data %>% unite(Group, Allotment, Number, sep = ".") # use unite() function to make data widerback_to_wide <- unite_data %>% spread(Group, Frequency) # print the new data frameback_to_wide
Output:
S.No Group.1 Group.2 Group.3
1 1 23 117 29
2 2 345 89 101
3 3 76 66 239
4 4 212 334 289
5 5 88 90 176
6 6 199 101 320
7 7 72 178 89
8 8 35 233 109
9 9 90 45 199
10 10 265 200 56
nest() function: It creates a list of data frames containing all the nested variables. Nesting is implicitly a summarizing operation. This is useful in conjunction with other summaries that work with whole datasets, most notably models.
Syntax: nest(data, ..., .key = “data”)
Description
Example: Let’s try to nest Group.2 column from the tidy_dataframe we created in the data set.
R
# import tidyr packagelibrary(tidyr) df <- tidy_dataframe # nest column Group.1 in # tidy_dataframe using nest()df %>% nest(data = c(Group.1))
Output:
# A tibble: 10 x 4
S.No Group.1 Group.3 data
<int> <dbl> <dbl> <list>
1 1 23 29 <tibble [1 x 1]>
2 2 345 101 <tibble [1 x 1]>
3 3 76 239 <tibble [1 x 1]>
4 4 212 289 <tibble [1 x 1]>
5 5 88 176 <tibble [1 x 1]>
6 6 199 320 <tibble [1 x 1]>
7 7 72 89 <tibble [1 x 1]>
8 8 35 109 <tibble [1 x 1]>
9 9 90 199 <tibble [1 x 1]>
10 10 265 56 <tibble [1 x 1]>
unnest() function: It basically reverses the nest operation. It makes each element of the list its own row. It can handle list columns that contain atomic vectors, lists, or data frames (but not a mixture of the different types).
Syntax:
unnest(data, ..., .drop = NA, .id = NULL, .sep = NULL, .preserve = NULL)
Description
Should additional list columns be dropped? By default,
it will drop them if unnesting
the specified columns requires the rows to be duplicated.
If non-NULL, the names of unnested data frame columns
will combine the name of the original list-col with
the names from nested data frame, separated by .sep.
List-columns to preserve in the output. These will be
duplicated in the same way as atomic vectors.
Example:
We will try to nest and unnest Species column in the iris dataframe in the tidyr package.
R
# import the tidyr packagelibrary(tidyr) df <- irisnames(iris) # nesting the species column in # the df data frame using nest()head(df %>% nest(data = c(Species))) # Output (i) # unnesting the species column # in the df data frame using unnest()head(df %>% unnest(Species,.drop = NA, .preserve = NULL)) # Output (ii)
Output (i):
# A tibble: 6 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width data
<dbl> <dbl> <dbl> <dbl> <list>
1 5.1 3.5 1.4 0.2 <tibble [1 x 1]>
2 4.9 3 1.4 0.2 <tibble [1 x 1]>
3 4.7 3.2 1.3 0.2 <tibble [1 x 1]>
4 4.6 3.1 1.5 0.2 <tibble [1 x 1]>
5 5 3.6 1.4 0.2 <tibble [1 x 1]>
6 5.4 3.9 1.7 0.4 <tibble [1 x 1]>
Output (ii):
# A tibble: 6 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
fill() function: Used to fill in the missing values in selected columns using the previous entry. This is useful in the common output format where values are not repeated, they’re recorded each time they change. Missing values are replaced in atomic vectors; NULL is replaced in the list.
Syntax:
fill(data, ..., .direction = c(“down”, “up”))
Description
Example:
R
# import the tidyr packagedf <- data.frame(Month = 1:6, Year = c(2000, rep(NA, 5))) # print the df data framedf # Output (i) # use fill() to fill missing values in # Year column in df data framedf %>% fill(Year) # Output (ii)
Output (i):
Month Year
1 1 2000
2 2 NA
3 3 NA
4 4 NA
5 5 NA
6 6 NA
Output (ii):
Month Year
1 1 2000
2 2 2000
3 3 2000
4 4 2000
5 5 2000
6 6 2000
full_seq() function: It basically fills the missing values in a vector which should have been observed but weren’t. The vector should be numeric.
Syntax: full_seq(x, period, tol = 1e-06)
Description
Example:
R
# import the tidyr packagelibrary(tidyr) # creating a numeric vectornum_vec <- c(1, 7, 9, 14, 19, 20) # use full_seq() to fill missing# values in num_vecfull_seq(num_vector, 1)
Output:
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
drop_na() function: This function drops rows containing missing values.
Syntax: drop_na(data, ...)
Description
Example:
R
# import tidyr packagelibrary(tidyr) # create a tibble df with missing valuesdf <- tibble(S.No = c(1:10), Name = c('John', 'Smith', 'Peter', 'Luke', 'King', rep(NA, 5))) # print df tibbledf # Output (i) # use drop_na() to drop columns # in df with missing values df %>% drop_na(Name) # Output (ii)
Output (i):
# A tibble: 10 x 2
S.No Name
<int> <chr>
1 1 John
2 2 Smith
3 3 Peter
4 4 Luke
5 5 King
6 6 <NA>
7 7 <NA>
8 8 <NA>
9 9 <NA>
10 10 <NA>
Output (ii):
# A tibble: 5 x 2
S.No Name
<int> <chr>
1 1 John
2 2 Smith
3 3 Peter
4 4 Luke
5 5 King
replace_na() function: It replaces missing values.
Syntax: replace_na(data, replace, ...)
Description
If data is a data frame, returns a data frame. If data is a vector,
returns a vector of class determined by the union of data and replace.
Example:
R
# import tidyr packagelibrary(tidyr) df <- data.frame(S.No = c(1:10), Name = c('John', 'Smith', 'Peter', 'Luke', 'King', rep(NA, 5))) df # Output (i) # use replace_na() to replace missing values or nadf %>% replace_na(list(Name = 'Henry')) # Output (ii)
Output (i):
# A tibble: 10 x 2
S.No Name
<int> <chr>
1 1 John
2 2 Smith
3 3 Peter
4 4 Luke
5 5 King
6 6 <NA>
7 7 <NA>
8 8 <NA>
9 9 <NA>
10 10 <NA>
Output (ii):
S.No Name
1 1 John
2 2 Smith
3 3 Peter
4 4 Luke
5 5 King
6 6 Henry
7 7 Henry
8 8 Henry
9 9 Henry
10 10 Henry
data-science
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to filter R DataFrame by values in a column?
Loops in R (for, while, repeat)
Convert Factor to Numeric and Numeric to Factor in R Programming
Adding elements in a vector in R programming - append() method
Creating a Data Frame from Vectors in R Programming
How to change Row Names of DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 647,
"s": 28,
"text": "Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the process of creating tidy data. Tidy data describes a standard way of storing data that is used wherever possible throughout the tidyverse. If you once make sure that your data is tidy, you’ll spend less time punching with the tools and more time working on your analysis."
},
{
"code": null,
"e": 848,
"s": 647,
"text": "To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”). To install the whole tidyverse package type this:"
},
{
"code": null,
"e": 879,
"s": 848,
"text": "install.packages(\"tidyverse\")\n"
},
{
"code": null,
"e": 935,
"s": 879,
"text": "Alternatively, to install just tidyr package type this:"
},
{
"code": null,
"e": 962,
"s": 935,
"text": "install.packages(\"tidyr\")\n"
},
{
"code": null,
"e": 1020,
"s": 962,
"text": "To install the development version from GitHub type this:"
},
{
"code": null,
"e": 1096,
"s": 1020,
"text": "# install.packages(\"devtools\")\ndevtools::install_github(\"tidyverse/tidyr\")\n"
},
{
"code": null,
"e": 1109,
"s": 1096,
"text": "The Dataset:"
},
{
"code": null,
"e": 1291,
"s": 1109,
"text": "Before going to the important verb function let’s prepare the data set first. Define a dataset tidy_dataframe that contains data about the frequency of people in a particular group."
},
{
"code": null,
"e": 1293,
"s": 1291,
"text": "R"
},
{
"code": "# load the tidyr packagelibrary(tidyr) n = 10# creating a data frametidy_dataframe = data.frame( S.No = c(1:n), Group.1 = c(23, 345, 76, 212, 88, 199, 72, 35, 90, 265), Group.2 = c(117, 89, 66, 334, 90, 101, 178, 233, 45, 200), Group.3 = c(29, 101, 239, 289, 176, 320, 89, 109, 199, 56)) # print the elements of the data frametidy_dataframe",
"e": 1809,
"s": 1293,
"text": null
},
{
"code": null,
"e": 1817,
"s": 1809,
"text": "Output:"
},
{
"code": null,
"e": 2171,
"s": 1817,
"text": " S.No Group.1 Group.2 Group.3\n1 1 23 117 29\n2 2 345 89 101\n3 3 76 66 239\n4 4 212 334 289\n5 5 88 90 176\n6 6 199 101 320\n7 7 72 178 89\n8 8 35 233 109\n9 9 90 45 199\n10 10 265 200 56\n"
},
{
"code": null,
"e": 2269,
"s": 2171,
"text": "tidyr package provides various important functions that can be used for Data Cleaning. Those are:"
},
{
"code": null,
"e": 2522,
"s": 2269,
"text": "gather() function: It takes multiple columns and gathers them into key-value pairs. Basically it makes “wide” data longer. The gather() function will take multiple columns and collapse them into key-value pairs, duplicating all other columns as needed."
},
{
"code": null,
"e": 2538,
"s": 2522,
"text": "Syntax: "
},
{
"code": null,
"e": 2639,
"s": 2538,
"text": "gather(data, key = “key”, value = “value”, ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE) "
},
{
"code": null,
"e": 2649,
"s": 2639,
"text": "Parameter"
},
{
"code": null,
"e": 2661,
"s": 2649,
"text": "Description"
},
{
"code": null,
"e": 2702,
"s": 2661,
"text": "the names of new key and value columns, "
},
{
"code": null,
"e": 2728,
"s": 2702,
"text": "as strings or as symbols."
},
{
"code": null,
"e": 2798,
"s": 2728,
"text": "the selection of columns. If left empty, all variables are selected. "
},
{
"code": null,
"e": 2863,
"s": 2798,
"text": "You can supply bare variable names, select all variables between"
},
{
"code": null,
"e": 2901,
"s": 2863,
"text": " x and z with x:z, exclude y with -y."
},
{
"code": null,
"e": 2975,
"s": 2901,
"text": "is set TRUE, it will automatically run type.convert() on the key column. "
},
{
"code": null,
"e": 3032,
"s": 2975,
"text": "This is useful if the column types are actually numeric,"
},
{
"code": null,
"e": 3054,
"s": 3032,
"text": " integer, or logical."
},
{
"code": null,
"e": 3130,
"s": 3054,
"text": "if FALSE, the default, the key values will be stored as a character vector."
},
{
"code": null,
"e": 3184,
"s": 3130,
"text": " If TRUE, will be stored as a factor, which preserves"
},
{
"code": null,
"e": 3222,
"s": 3184,
"text": "the original ordering of the columns."
},
{
"code": null,
"e": 3232,
"s": 3222,
"text": "Example: "
},
{
"code": null,
"e": 3315,
"s": 3232,
"text": "Now for a better understanding, we will make our data long with gather() function."
},
{
"code": null,
"e": 3317,
"s": 3315,
"text": "R"
},
{
"code": "# using gather() function on tidy_dataframelong <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # print the data frame in a long formatlong",
"e": 3504,
"s": 3317,
"text": null
},
{
"code": null,
"e": 3513,
"s": 3504,
"text": " Output:"
},
{
"code": null,
"e": 4322,
"s": 3513,
"text": " S.No Group Frequency\n1 1 Group.1 23\n2 2 Group.1 345\n3 3 Group.1 76\n4 4 Group.1 212\n5 5 Group.1 88\n6 6 Group.1 199\n7 7 Group.1 72\n8 8 Group.1 35\n9 9 Group.1 90\n10 10 Group.1 265\n11 1 Group.2 117\n12 2 Group.2 89\n13 3 Group.2 66\n14 4 Group.2 334\n15 5 Group.2 90\n16 6 Group.2 101\n17 7 Group.2 178\n18 8 Group.2 233\n19 9 Group.2 45\n20 10 Group.2 200\n21 1 Group.3 29\n22 2 Group.3 101\n23 3 Group.3 239\n24 4 Group.3 289\n25 5 Group.3 176\n26 6 Group.3 320\n27 7 Group.3 89\n28 8 Group.3 109\n29 9 Group.3 199\n30 10 Group.3 56\n"
},
{
"code": null,
"e": 4465,
"s": 4322,
"text": "separate() function: It converts longer data to a wider format. The separate() function turns a single character column into multiple columns."
},
{
"code": null,
"e": 4476,
"s": 4465,
"text": " Syntax:"
},
{
"code": null,
"e": 4548,
"s": 4476,
"text": " separate(data, col, into, sep = ” “, remove = TRUE, convert = FALSE)"
},
{
"code": null,
"e": 4558,
"s": 4548,
"text": "Parameter"
},
{
"code": null,
"e": 4570,
"s": 4558,
"text": "Description"
},
{
"code": null,
"e": 4625,
"s": 4570,
"text": "Names of new variables to create as character vector. "
},
{
"code": null,
"e": 4668,
"s": 4625,
"text": "Use NA to omit the variable in the output."
},
{
"code": null,
"e": 4678,
"s": 4668,
"text": "Example: "
},
{
"code": null,
"e": 4828,
"s": 4678,
"text": "We can say that the long datasets created using gather() is appropriate for use, but we can break down Group variable even further using separate(). "
},
{
"code": null,
"e": 4830,
"s": 4828,
"text": "R"
},
{
"code": "# import tidyr packagelibrary(tidyr)long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c(\"Allotment\", \"Number\")) # print the wider formatseparate_data",
"e": 5158,
"s": 4830,
"text": null
},
{
"code": null,
"e": 5166,
"s": 5158,
"text": "Output:"
},
{
"code": null,
"e": 6252,
"s": 5166,
"text": " S.No Allotment Number Frequency\n1 1 Group 1 23\n2 2 Group 1 345\n3 3 Group 1 76\n4 4 Group 1 212\n5 5 Group 1 88\n6 6 Group 1 199\n7 7 Group 1 72\n8 8 Group 1 35\n9 9 Group 1 90\n10 10 Group 1 265\n11 1 Group 2 117\n12 2 Group 2 89\n13 3 Group 2 66\n14 4 Group 2 334\n15 5 Group 2 90\n16 6 Group 2 101\n17 7 Group 2 178\n18 8 Group 2 233\n19 9 Group 2 45\n20 10 Group 2 200\n21 1 Group 3 29\n22 2 Group 3 101\n23 3 Group 3 239\n24 4 Group 3 289\n25 5 Group 3 176\n26 6 Group 3 320\n27 7 Group 3 89\n28 8 Group 3 109\n29 9 Group 3 199\n30 10 Group 3 56\n"
},
{
"code": null,
"e": 6490,
"s": 6252,
"text": "unite() function: It merges two columns into one column. The unite() function is a convenience function to paste together multiple variable values into one. In essence, it combines two variables of a single observation into one variable."
},
{
"code": null,
"e": 6499,
"s": 6490,
"text": "Syntax: "
},
{
"code": null,
"e": 6547,
"s": 6499,
"text": "unite(data, col, ..., sep = “_”, remove = TRUE)"
},
{
"code": null,
"e": 6559,
"s": 6547,
"text": "Description"
},
{
"code": null,
"e": 6568,
"s": 6559,
"text": "Example:"
},
{
"code": null,
"e": 6753,
"s": 6568,
"text": "Unite is the compliment of separate. To undo separate(), we can use unite(), which merges two variables into one. Here we will merge two columns Group and Number with a separator “.”. "
},
{
"code": null,
"e": 6755,
"s": 6753,
"text": "R"
},
{
"code": "# import tidyr package library(tidyr) long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c(\"Allotment\", \"Number\")) # use unite() function to glue # Allotment and Number columnsunite_data <- separate_data %>% unite(Group, Allotment, Number, sep = \".\") # print the new data frameunite_data",
"e": 7251,
"s": 6755,
"text": null
},
{
"code": null,
"e": 7259,
"s": 7251,
"text": "Output:"
},
{
"code": null,
"e": 8066,
"s": 7259,
"text": " S.No Group Frequency\n1 1 Group.1 23\n2 2 Group.1 345\n3 3 Group.1 76\n4 4 Group.1 212\n5 5 Group.1 88\n6 6 Group.1 199\n7 7 Group.1 72\n8 8 Group.1 35\n9 9 Group.1 90\n10 10 Group.1 265\n11 1 Group.2 117\n12 2 Group.2 89\n13 3 Group.2 66\n14 4 Group.2 334\n15 5 Group.2 90\n16 6 Group.2 101\n17 7 Group.2 178\n18 8 Group.2 233\n19 9 Group.2 45\n20 10 Group.2 200\n21 1 Group.3 29\n22 2 Group.3 101\n23 3 Group.3 239\n24 4 Group.3 289\n25 5 Group.3 176\n26 6 Group.3 320\n27 7 Group.3 89\n28 8 Group.3 109\n29 9 Group.3 199\n30 10 Group.3 56\n"
},
{
"code": null,
"e": 8214,
"s": 8066,
"text": "spread() function: It helps in reshaping a longer format to a wider format. The spread() function spreads a key-value pair across multiple columns."
},
{
"code": null,
"e": 8222,
"s": 8214,
"text": "Syntax:"
},
{
"code": null,
"e": 8275,
"s": 8222,
"text": "spread(data, key, value, fill = NA, convert = FALSE)"
},
{
"code": null,
"e": 8287,
"s": 8275,
"text": "Description"
},
{
"code": null,
"e": 8296,
"s": 8287,
"text": "Example:"
},
{
"code": null,
"e": 8374,
"s": 8296,
"text": "We can transform the data from long back to wide with the spread() function. "
},
{
"code": null,
"e": 8376,
"s": 8374,
"text": "R"
},
{
"code": "# import tidyr package library(tidyr) long <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # use separate() function to make data widerseparate_data <- long %>% separate(Group, c(\"Allotment\", \"Number\")) # use unite() function to glue# Allotment and Number columnsunite_data <- separate_data %>% unite(Group, Allotment, Number, sep = \".\") # use unite() function to make data widerback_to_wide <- unite_data %>% spread(Group, Frequency) # print the new data frameback_to_wide",
"e": 8984,
"s": 8376,
"text": null
},
{
"code": null,
"e": 8992,
"s": 8984,
"text": "Output:"
},
{
"code": null,
"e": 9345,
"s": 8992,
"text": " S.No Group.1 Group.2 Group.3\n1 1 23 117 29\n2 2 345 89 101\n3 3 76 66 239\n4 4 212 334 289\n5 5 88 90 176\n6 6 199 101 320\n7 7 72 178 89\n8 8 35 233 109\n9 9 90 45 199\n10 10 265 200 56\n"
},
{
"code": null,
"e": 9582,
"s": 9345,
"text": "nest() function: It creates a list of data frames containing all the nested variables. Nesting is implicitly a summarizing operation. This is useful in conjunction with other summaries that work with whole datasets, most notably models."
},
{
"code": null,
"e": 9621,
"s": 9582,
"text": "Syntax: nest(data, ..., .key = “data”)"
},
{
"code": null,
"e": 9633,
"s": 9621,
"text": "Description"
},
{
"code": null,
"e": 9727,
"s": 9633,
"text": "Example: Let’s try to nest Group.2 column from the tidy_dataframe we created in the data set."
},
{
"code": null,
"e": 9729,
"s": 9727,
"text": "R"
},
{
"code": "# import tidyr packagelibrary(tidyr) df <- tidy_dataframe # nest column Group.1 in # tidy_dataframe using nest()df %>% nest(data = c(Group.1))",
"e": 9874,
"s": 9729,
"text": null
},
{
"code": null,
"e": 9882,
"s": 9874,
"text": "Output:"
},
{
"code": null,
"e": 10406,
"s": 9882,
"text": "# A tibble: 10 x 4\n S.No Group.1 Group.3 data \n <int> <dbl> <dbl> <list> \n 1 1 23 29 <tibble [1 x 1]>\n 2 2 345 101 <tibble [1 x 1]>\n 3 3 76 239 <tibble [1 x 1]>\n 4 4 212 289 <tibble [1 x 1]>\n 5 5 88 176 <tibble [1 x 1]>\n 6 6 199 320 <tibble [1 x 1]>\n 7 7 72 89 <tibble [1 x 1]>\n 8 8 35 109 <tibble [1 x 1]>\n 9 9 90 199 <tibble [1 x 1]>\n10 10 265 56 <tibble [1 x 1]>\n"
},
{
"code": null,
"e": 10636,
"s": 10406,
"text": "unnest() function: It basically reverses the nest operation. It makes each element of the list its own row. It can handle list columns that contain atomic vectors, lists, or data frames (but not a mixture of the different types)."
},
{
"code": null,
"e": 10644,
"s": 10636,
"text": "Syntax:"
},
{
"code": null,
"e": 10717,
"s": 10644,
"text": "unnest(data, ..., .drop = NA, .id = NULL, .sep = NULL, .preserve = NULL)"
},
{
"code": null,
"e": 10729,
"s": 10717,
"text": "Description"
},
{
"code": null,
"e": 10784,
"s": 10729,
"text": "Should additional list columns be dropped? By default,"
},
{
"code": null,
"e": 10816,
"s": 10784,
"text": "it will drop them if unnesting "
},
{
"code": null,
"e": 10874,
"s": 10816,
"text": "the specified columns requires the rows to be duplicated."
},
{
"code": null,
"e": 10929,
"s": 10874,
"text": "If non-NULL, the names of unnested data frame columns "
},
{
"code": null,
"e": 10981,
"s": 10929,
"text": "will combine the name of the original list-col with"
},
{
"code": null,
"e": 11034,
"s": 10981,
"text": "the names from nested data frame, separated by .sep."
},
{
"code": null,
"e": 11088,
"s": 11034,
"text": "List-columns to preserve in the output. These will be"
},
{
"code": null,
"e": 11135,
"s": 11088,
"text": " duplicated in the same way as atomic vectors."
},
{
"code": null,
"e": 11144,
"s": 11135,
"text": "Example:"
},
{
"code": null,
"e": 11234,
"s": 11144,
"text": "We will try to nest and unnest Species column in the iris dataframe in the tidyr package."
},
{
"code": null,
"e": 11236,
"s": 11234,
"text": "R"
},
{
"code": "# import the tidyr packagelibrary(tidyr) df <- irisnames(iris) # nesting the species column in # the df data frame using nest()head(df %>% nest(data = c(Species))) # Output (i) # unnesting the species column # in the df data frame using unnest()head(df %>% unnest(Species,.drop = NA, .preserve = NULL)) # Output (ii)",
"e": 11575,
"s": 11236,
"text": null
},
{
"code": null,
"e": 11588,
"s": 11575,
"text": "Output (i): "
},
{
"code": null,
"e": 12159,
"s": 11588,
"text": "# A tibble: 6 x 5\n Sepal.Length Sepal.Width Petal.Length Petal.Width data \n <dbl> <dbl> <dbl> <dbl> <list> \n1 5.1 3.5 1.4 0.2 <tibble [1 x 1]>\n2 4.9 3 1.4 0.2 <tibble [1 x 1]>\n3 4.7 3.2 1.3 0.2 <tibble [1 x 1]>\n4 4.6 3.1 1.5 0.2 <tibble [1 x 1]>\n5 5 3.6 1.4 0.2 <tibble [1 x 1]>\n6 5.4 3.9 1.7 0.4 <tibble [1 x 1]>\n"
},
{
"code": null,
"e": 12172,
"s": 12159,
"text": "Output (ii):"
},
{
"code": null,
"e": 12671,
"s": 12172,
"text": "# A tibble: 6 x 5\n Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n <dbl> <dbl> <dbl> <dbl> <fct> \n1 5.1 3.5 1.4 0.2 setosa \n2 4.9 3 1.4 0.2 setosa \n3 4.7 3.2 1.3 0.2 setosa \n4 4.6 3.1 1.5 0.2 setosa \n5 5 3.6 1.4 0.2 setosa \n6 5.4 3.9 1.7 0.4 setosa \n"
},
{
"code": null,
"e": 12960,
"s": 12671,
"text": "fill() function: Used to fill in the missing values in selected columns using the previous entry. This is useful in the common output format where values are not repeated, they’re recorded each time they change. Missing values are replaced in atomic vectors; NULL is replaced in the list."
},
{
"code": null,
"e": 12969,
"s": 12960,
"text": "Syntax: "
},
{
"code": null,
"e": 13015,
"s": 12969,
"text": "fill(data, ..., .direction = c(“down”, “up”))"
},
{
"code": null,
"e": 13027,
"s": 13015,
"text": "Description"
},
{
"code": null,
"e": 13036,
"s": 13027,
"text": "Example:"
},
{
"code": null,
"e": 13038,
"s": 13036,
"text": "R"
},
{
"code": "# import the tidyr packagedf <- data.frame(Month = 1:6, Year = c(2000, rep(NA, 5))) # print the df data framedf # Output (i) # use fill() to fill missing values in # Year column in df data framedf %>% fill(Year) # Output (ii)",
"e": 13304,
"s": 13038,
"text": null
},
{
"code": null,
"e": 13316,
"s": 13304,
"text": "Output (i):"
},
{
"code": null,
"e": 13408,
"s": 13316,
"text": " Month Year\n1 1 2000\n2 2 NA\n3 3 NA\n4 4 NA\n5 5 NA\n6 6 NA\n"
},
{
"code": null,
"e": 13421,
"s": 13408,
"text": "Output (ii):"
},
{
"code": null,
"e": 13513,
"s": 13421,
"text": " Month Year\n1 1 2000\n2 2 2000\n3 3 2000\n4 4 2000\n5 5 2000\n6 6 2000\n"
},
{
"code": null,
"e": 13659,
"s": 13513,
"text": "full_seq() function: It basically fills the missing values in a vector which should have been observed but weren’t. The vector should be numeric."
},
{
"code": null,
"e": 13700,
"s": 13659,
"text": "Syntax: full_seq(x, period, tol = 1e-06)"
},
{
"code": null,
"e": 13712,
"s": 13700,
"text": "Description"
},
{
"code": null,
"e": 13722,
"s": 13712,
"text": "Example: "
},
{
"code": null,
"e": 13724,
"s": 13722,
"text": "R"
},
{
"code": "# import the tidyr packagelibrary(tidyr) # creating a numeric vectornum_vec <- c(1, 7, 9, 14, 19, 20) # use full_seq() to fill missing# values in num_vecfull_seq(num_vector, 1)",
"e": 13903,
"s": 13724,
"text": null
},
{
"code": null,
"e": 13911,
"s": 13903,
"text": "Output:"
},
{
"code": null,
"e": 13976,
"s": 13911,
"text": "[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n"
},
{
"code": null,
"e": 14048,
"s": 13976,
"text": "drop_na() function: This function drops rows containing missing values."
},
{
"code": null,
"e": 14075,
"s": 14048,
"text": "Syntax: drop_na(data, ...)"
},
{
"code": null,
"e": 14087,
"s": 14075,
"text": "Description"
},
{
"code": null,
"e": 14096,
"s": 14087,
"text": "Example:"
},
{
"code": null,
"e": 14098,
"s": 14096,
"text": "R"
},
{
"code": "# import tidyr packagelibrary(tidyr) # create a tibble df with missing valuesdf <- tibble(S.No = c(1:10), Name = c('John', 'Smith', 'Peter', 'Luke', 'King', rep(NA, 5))) # print df tibbledf # Output (i) # use drop_na() to drop columns # in df with missing values df %>% drop_na(Name) # Output (ii)",
"e": 14452,
"s": 14098,
"text": null
},
{
"code": null,
"e": 14464,
"s": 14452,
"text": "Output (i):"
},
{
"code": null,
"e": 14664,
"s": 14464,
"text": "# A tibble: 10 x 2\n S.No Name \n <int> <chr>\n 1 1 John \n 2 2 Smith\n 3 3 Peter\n 4 4 Luke \n 5 5 King \n 6 6 <NA> \n 7 7 <NA> \n 8 8 <NA> \n 9 9 <NA> \n10 10 <NA> \n"
},
{
"code": null,
"e": 14677,
"s": 14664,
"text": "Output (ii):"
},
{
"code": null,
"e": 14794,
"s": 14677,
"text": "# A tibble: 5 x 2\n S.No Name \n <int> <chr>\n1 1 John \n2 2 Smith\n3 3 Peter\n4 4 Luke \n5 5 King \n"
},
{
"code": null,
"e": 14845,
"s": 14794,
"text": "replace_na() function: It replaces missing values."
},
{
"code": null,
"e": 14884,
"s": 14845,
"text": "Syntax: replace_na(data, replace, ...)"
},
{
"code": null,
"e": 14896,
"s": 14884,
"text": "Description"
},
{
"code": null,
"e": 14965,
"s": 14896,
"text": "If data is a data frame, returns a data frame. If data is a vector, "
},
{
"code": null,
"e": 15036,
"s": 14965,
"text": "returns a vector of class determined by the union of data and replace."
},
{
"code": null,
"e": 15045,
"s": 15036,
"text": "Example:"
},
{
"code": null,
"e": 15047,
"s": 15045,
"text": "R"
},
{
"code": "# import tidyr packagelibrary(tidyr) df <- data.frame(S.No = c(1:10), Name = c('John', 'Smith', 'Peter', 'Luke', 'King', rep(NA, 5))) df # Output (i) # use replace_na() to replace missing values or nadf %>% replace_na(list(Name = 'Henry')) # Output (ii)",
"e": 15408,
"s": 15047,
"text": null
},
{
"code": null,
"e": 15420,
"s": 15408,
"text": "Output (i):"
},
{
"code": null,
"e": 15621,
"s": 15420,
"text": "# A tibble: 10 x 2\n S.No Name \n <int> <chr>\n 1 1 John \n 2 2 Smith\n 3 3 Peter\n 4 4 Luke \n 5 5 King \n 6 6 <NA> \n 7 7 <NA> \n 8 8 <NA> \n 9 9 <NA> \n10 10 <NA> \n"
},
{
"code": null,
"e": 15634,
"s": 15621,
"text": "Output (ii):"
},
{
"code": null,
"e": 15790,
"s": 15634,
"text": " S.No Name\n1 1 John\n2 2 Smith\n3 3 Peter\n4 4 Luke\n5 5 King\n6 6 Henry\n7 7 Henry\n8 8 Henry\n9 9 Henry\n10 10 Henry\n"
},
{
"code": null,
"e": 15803,
"s": 15790,
"text": "data-science"
},
{
"code": null,
"e": 15814,
"s": 15803,
"text": "R-Packages"
},
{
"code": null,
"e": 15825,
"s": 15814,
"text": "R Language"
},
{
"code": null,
"e": 15923,
"s": 15825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15968,
"s": 15923,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 16020,
"s": 15968,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 16055,
"s": 16020,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 16113,
"s": 16055,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 16162,
"s": 16113,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 16194,
"s": 16162,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 16259,
"s": 16194,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 16322,
"s": 16259,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 16374,
"s": 16322,
"text": "Creating a Data Frame from Vectors in R Programming"
}
]
|
Project Idea | God’s Eye | 11 May, 2022
Project Idea: Complete user’s Activities tracking with Remote Assistance This Program is divided into two major modules one is for complete activity tracking and can even tell which activity is currently active on the user’s side. Can also work as a Global Keylogger to log the text written by a user on any process window ( Only when Proper undertaking ). The second module is for Remote Access which is widely used for Visual remote assistance and specially used on Industries, Colleges, Training Centers and many more. This project is fully based on Client-Server Architecture which is efficiently implemented using JAVA, C bridged by JNI.
Features :
First Module : Activity Tracking Server side: It can track 100 clients at a time with simplest user interface with fast access to data . This server program gives you choices to track user text on current activity from window handle to text in it. (A-Z tracking) Can even track Google chrome tabs to a text file located in FileSystem. Uses Global key logger to log text typed by each of the users. Client side: There is no UI for the client-side program. It runs as a background process which runs on window’s startup or can be invoked by server process using RMI(remote method invocation).
Second Module: Remote Visual Accessing Master side: It based on Master and slave architecture. Master’s side provides a visual Reflection of slave’s PC to provide a nice interface for remote access. Master can control the slave’s machine completely from playing music to searching web. It can only handle the slave at a time. Slave side: No user interface for Slave’s side its a background process. Master’s actions are fully reflected on the slave’s machine. A slave can be invoked by a Master machine at any time.
Implementation Details: No database used for the purpose of fast accessing of a large amount of data created per second. For accessing Data we used nested TreeMap along with ArrayList for storing data in an efficient manner for fast access. The concept behind using TreeMap is to fetch the data in Sorted order in O(logn) time complexity. Small code snippet is given from implementation :
Java
for (Map.Entry<String, TreeMap<String, TreeMap<String, ArrayList> > > en : tm.entrySet()) { System.out.print(en.getKey() + "-->"); TreeMap<String, TreeMap<String, ArrayList> > tm1 = en.getValue(); for (Map.Entry<String, TreeMap<String, ArrayList> > en1 : tm1.entrySet()) { System.out.print(en1.getKey() + "-->"); TreeMap<String, ArrayList> tm2 = en1.getValue(); for (Map.Entry<String, ArrayList> en2 : tm2.entrySet()) { System.out.print(en2.getKey() + "-->"); ArrayList ar = en2.getValue(); for(int i=0;i"); } }}
Tools/Programming Languages used: Java C JNI RMI Notepad++ RESEARCH WORK: Deeply studied about JNI from web resources RMI Worked with Windows inbuilt functions using jni. https://msdn.microsoft.com/en-us/library/windows/ Learned about Runtime class, Robot class, etc. Special thanks to GEEKSFORGEEKS, StackOverflow.
Team: Prakhar Gupta, Moradabad Institute of Technology, Github account: https://github.com/prakhar554 GeeksforGeeks Profile: https://auth.geeksforgeeks.org/profile.php?user=PRAKHAR%20GUPTA%2012 LinkedIn profile: https://www.linkedin.com/in/prakhar-gupta-bab211106/ Mritumjay Yadav, Sant longowal Institute of Engineering Technology, Punjab, Pincode:148106 LinkedIn profile: https://www.linkedin.com/in/mritunjay-yadav-37544112a Github account: https://github.com/manutanu GeeksforGeeks profile: https://practice.geeksforgeeks.org/user-profile.php?user=Mritunjay%20Yadav If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
mitalibhola94
ProGeek
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
OpenCV C++ Program for Face Detection
10 Best Web Development Projects For Your Resume
Twitter Sentiment Analysis using Python
Student Information Management System
A Group chat application in Java
Face Detection using Python and OpenCV with webcam
E-commerce Website using Django
Java Swing | Simple User Registration Form
Snake Game in C
Generating Password and OTP in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 696,
"s": 52,
"text": "Project Idea: Complete user’s Activities tracking with Remote Assistance This Program is divided into two major modules one is for complete activity tracking and can even tell which activity is currently active on the user’s side. Can also work as a Global Keylogger to log the text written by a user on any process window ( Only when Proper undertaking ). The second module is for Remote Access which is widely used for Visual remote assistance and specially used on Industries, Colleges, Training Centers and many more. This project is fully based on Client-Server Architecture which is efficiently implemented using JAVA, C bridged by JNI. "
},
{
"code": null,
"e": 708,
"s": 696,
"text": "Features : "
},
{
"code": null,
"e": 1300,
"s": 708,
"text": "First Module : Activity Tracking Server side: It can track 100 clients at a time with simplest user interface with fast access to data . This server program gives you choices to track user text on current activity from window handle to text in it. (A-Z tracking) Can even track Google chrome tabs to a text file located in FileSystem. Uses Global key logger to log text typed by each of the users. Client side: There is no UI for the client-side program. It runs as a background process which runs on window’s startup or can be invoked by server process using RMI(remote method invocation). "
},
{
"code": null,
"e": 1817,
"s": 1300,
"text": "Second Module: Remote Visual Accessing Master side: It based on Master and slave architecture. Master’s side provides a visual Reflection of slave’s PC to provide a nice interface for remote access. Master can control the slave’s machine completely from playing music to searching web. It can only handle the slave at a time. Slave side: No user interface for Slave’s side its a background process. Master’s actions are fully reflected on the slave’s machine. A slave can be invoked by a Master machine at any time. "
},
{
"code": null,
"e": 2207,
"s": 1817,
"text": "Implementation Details: No database used for the purpose of fast accessing of a large amount of data created per second. For accessing Data we used nested TreeMap along with ArrayList for storing data in an efficient manner for fast access. The concept behind using TreeMap is to fetch the data in Sorted order in O(logn) time complexity. Small code snippet is given from implementation : "
},
{
"code": null,
"e": 2212,
"s": 2207,
"text": "Java"
},
{
"code": "for (Map.Entry<String, TreeMap<String, TreeMap<String, ArrayList> > > en : tm.entrySet()) { System.out.print(en.getKey() + \"-->\"); TreeMap<String, TreeMap<String, ArrayList> > tm1 = en.getValue(); for (Map.Entry<String, TreeMap<String, ArrayList> > en1 : tm1.entrySet()) { System.out.print(en1.getKey() + \"-->\"); TreeMap<String, ArrayList> tm2 = en1.getValue(); for (Map.Entry<String, ArrayList> en2 : tm2.entrySet()) { System.out.print(en2.getKey() + \"-->\"); ArrayList ar = en2.getValue(); for(int i=0;i\"); } }}",
"e": 2818,
"s": 2212,
"text": null
},
{
"code": null,
"e": 3135,
"s": 2818,
"text": "Tools/Programming Languages used: Java C JNI RMI Notepad++ RESEARCH WORK: Deeply studied about JNI from web resources RMI Worked with Windows inbuilt functions using jni. https://msdn.microsoft.com/en-us/library/windows/ Learned about Runtime class, Robot class, etc. Special thanks to GEEKSFORGEEKS, StackOverflow. "
},
{
"code": null,
"e": 4081,
"s": 3135,
"text": "Team: Prakhar Gupta, Moradabad Institute of Technology, Github account: https://github.com/prakhar554 GeeksforGeeks Profile: https://auth.geeksforgeeks.org/profile.php?user=PRAKHAR%20GUPTA%2012 LinkedIn profile: https://www.linkedin.com/in/prakhar-gupta-bab211106/ Mritumjay Yadav, Sant longowal Institute of Engineering Technology, Punjab, Pincode:148106 LinkedIn profile: https://www.linkedin.com/in/mritunjay-yadav-37544112a Github account: https://github.com/manutanu GeeksforGeeks profile: https://practice.geeksforgeeks.org/user-profile.php?user=Mritunjay%20Yadav If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4094,
"s": 4081,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4108,
"s": 4094,
"text": "mitalibhola94"
},
{
"code": null,
"e": 4116,
"s": 4108,
"text": "ProGeek"
},
{
"code": null,
"e": 4124,
"s": 4116,
"text": "Project"
},
{
"code": null,
"e": 4222,
"s": 4124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4260,
"s": 4222,
"text": "OpenCV C++ Program for Face Detection"
},
{
"code": null,
"e": 4309,
"s": 4260,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 4349,
"s": 4309,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 4387,
"s": 4349,
"text": "Student Information Management System"
},
{
"code": null,
"e": 4420,
"s": 4387,
"text": "A Group chat application in Java"
},
{
"code": null,
"e": 4471,
"s": 4420,
"text": "Face Detection using Python and OpenCV with webcam"
},
{
"code": null,
"e": 4503,
"s": 4471,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 4546,
"s": 4503,
"text": "Java Swing | Simple User Registration Form"
},
{
"code": null,
"e": 4562,
"s": 4546,
"text": "Snake Game in C"
}
]
|
Python Program for Program to calculate area of a Tetrahedron | 16 Jun, 2022
A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The volume of the tetrahedron can be found by using the following formula :
Volume = a3/(6√2)
Examples :
Input : side = 3
Output : 3.18
Input : side = 20
Output : 942.81
Python3
# Python code to find the volume of a tetrahedronimport mathdef vol_tetra(side): volume = (side ** 3 / (6 * math.sqrt(2))) return round(volume, 2) # Driver Codeside = 3vol = vol_tetra(side)print(vol)
Output :
3.18
Time complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Program to calculate area of a Tetrahedron for more details!
hasani
area-volume-programs
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 427,
"s": 53,
"text": "A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The volume of the tetrahedron can be found by using the following formula :"
},
{
"code": null,
"e": 445,
"s": 427,
"text": "Volume = a3/(6√2)"
},
{
"code": null,
"e": 456,
"s": 445,
"text": "Examples :"
},
{
"code": null,
"e": 523,
"s": 456,
"text": "Input : side = 3\nOutput : 3.18\n\n\nInput : side = 20\nOutput : 942.81"
},
{
"code": null,
"e": 531,
"s": 523,
"text": "Python3"
},
{
"code": "# Python code to find the volume of a tetrahedronimport mathdef vol_tetra(side): volume = (side ** 3 / (6 * math.sqrt(2))) return round(volume, 2) # Driver Codeside = 3vol = vol_tetra(side)print(vol)",
"e": 737,
"s": 531,
"text": null
},
{
"code": null,
"e": 746,
"s": 737,
"text": "Output :"
},
{
"code": null,
"e": 751,
"s": 746,
"text": "3.18"
},
{
"code": null,
"e": 773,
"s": 751,
"text": "Time complexity: O(1)"
},
{
"code": null,
"e": 795,
"s": 773,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 889,
"s": 795,
"text": "Please refer complete article on Program to calculate area of a Tetrahedron for more details!"
},
{
"code": null,
"e": 896,
"s": 889,
"text": "hasani"
},
{
"code": null,
"e": 917,
"s": 896,
"text": "area-volume-programs"
},
{
"code": null,
"e": 933,
"s": 917,
"text": "Python Programs"
},
{
"code": null,
"e": 1031,
"s": 933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1069,
"s": 1031,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1118,
"s": 1069,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 1177,
"s": 1118,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 1232,
"s": 1177,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 1278,
"s": 1232,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 1311,
"s": 1278,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 1375,
"s": 1311,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 1414,
"s": 1375,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 1451,
"s": 1414,
"text": "Python | Convert a list into a tuple"
}
]
|
C++ default constructor | Built-in types - GeeksforGeeks | 29 May, 2017
Predict the output of following program?
#include <iostream>using namespace std; int main() { cout << int() << endl; return 0;}
A constructor without any arguments or with default values for every argument, is treated as default constructor. It will be called by the compiler when in need (precisely code will be generated for default constructor based on need).
C++ allows even built-in type (primitive types) to have default constructors. The function style cast int() is analogous to casting 0 to required type. The program prints 0 on console.
The initial content of the article triggered many discussions, given below is consolidation.
It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions.
An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in types are considered to have constructors”.
The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call. But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document.
Thanks to Prasoon Saurav for initiating the discussion, providing various references and correcting lacuna in my understanding.
Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:
The C++ Programming Language, 3e.Latest C++ standard – working draft section 8.5.
The C++ Programming Language, 3e.
Latest C++ standard – working draft section 8.5.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 24620,
"s": 24592,
"text": "\n29 May, 2017"
},
{
"code": null,
"e": 24661,
"s": 24620,
"text": "Predict the output of following program?"
},
{
"code": "#include <iostream>using namespace std; int main() { cout << int() << endl; return 0;}",
"e": 24755,
"s": 24661,
"text": null
},
{
"code": null,
"e": 24990,
"s": 24755,
"text": "A constructor without any arguments or with default values for every argument, is treated as default constructor. It will be called by the compiler when in need (precisely code will be generated for default constructor based on need)."
},
{
"code": null,
"e": 25175,
"s": 24990,
"text": "C++ allows even built-in type (primitive types) to have default constructors. The function style cast int() is analogous to casting 0 to required type. The program prints 0 on console."
},
{
"code": null,
"e": 25268,
"s": 25175,
"text": "The initial content of the article triggered many discussions, given below is consolidation."
},
{
"code": null,
"e": 25728,
"s": 25268,
"text": "It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions."
},
{
"code": null,
"e": 25923,
"s": 25728,
"text": "An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in types are considered to have constructors”."
},
{
"code": null,
"e": 26264,
"s": 25923,
"text": "The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call. But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document."
},
{
"code": null,
"e": 26392,
"s": 26264,
"text": "Thanks to Prasoon Saurav for initiating the discussion, providing various references and correcting lacuna in my understanding."
},
{
"code": null,
"e": 26539,
"s": 26392,
"text": "Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26551,
"s": 26539,
"text": "References:"
},
{
"code": null,
"e": 26633,
"s": 26551,
"text": "The C++ Programming Language, 3e.Latest C++ standard – working draft section 8.5."
},
{
"code": null,
"e": 26667,
"s": 26633,
"text": "The C++ Programming Language, 3e."
},
{
"code": null,
"e": 26716,
"s": 26667,
"text": "Latest C++ standard – working draft section 8.5."
},
{
"code": null,
"e": 26727,
"s": 26716,
"text": "C Language"
},
{
"code": null,
"e": 26731,
"s": 26727,
"text": "C++"
},
{
"code": null,
"e": 26735,
"s": 26731,
"text": "CPP"
},
{
"code": null,
"e": 26833,
"s": 26735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26868,
"s": 26833,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26914,
"s": 26868,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26926,
"s": 26914,
"text": "fork() in C"
},
{
"code": null,
"e": 26966,
"s": 26926,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26988,
"s": 26966,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27006,
"s": 26988,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27025,
"s": 27006,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27071,
"s": 27025,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27114,
"s": 27071,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Design Pattern - Abstract Factory Pattern | Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.
We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs.
Create an interface for Shapes.
Shape.java
public interface Shape {
void draw();
}
Create concrete classes implementing the same interface.
RoundedRectangle.java
public class RoundedRectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedRectangle::draw() method.");
}
}
RoundedSquare.java
public class RoundedSquare implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedSquare::draw() method.");
}
}
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Create an Abstract class to get factories for Normal and Rounded Shape Objects.
AbstractFactory.java
public abstract class AbstractFactory {
abstract Shape getShape(String shapeType) ;
}
Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
RoundedShapeFactory.java
public class RoundedShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new RoundedRectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new RoundedSquare();
}
return null;
}
}
Create a Factory generator/producer class to get factories by passing an information such as Shape
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(boolean rounded){
if(rounded){
return new RoundedShapeFactory();
}else{
return new ShapeFactory();
}
}
}
Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
//get shape factory
AbstractFactory shapeFactory = FactoryProducer.getFactory(false);
//get an object of Shape Rectangle
Shape shape1 = shapeFactory.getShape("RECTANGLE");
//call draw method of Shape Rectangle
shape1.draw();
//get an object of Shape Square
Shape shape2 = shapeFactory.getShape("SQUARE");
//call draw method of Shape Square
shape2.draw();
//get shape factory
AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true);
//get an object of Shape Rectangle
Shape shape3 = shapeFactory1.getShape("RECTANGLE");
//call draw method of Shape Rectangle
shape3.draw();
//get an object of Shape Square
Shape shape4 = shapeFactory1.getShape("SQUARE");
//call draw method of Shape Square
shape4.draw();
}
}
Verify the output.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Inside RoundedRectangle::draw() method.
Inside RoundedSquare::draw() method.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3015,
"s": 2751,
"text": "Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object."
},
{
"code": null,
"e": 3231,
"s": 3015,
"text": "In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern."
},
{
"code": null,
"e": 3508,
"s": 3231,
"text": "We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory creator/generator class FactoryProducer is created."
},
{
"code": null,
"e": 3725,
"s": 3508,
"text": "AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs."
},
{
"code": null,
"e": 3757,
"s": 3725,
"text": "Create an interface for Shapes."
},
{
"code": null,
"e": 3768,
"s": 3757,
"text": "Shape.java"
},
{
"code": null,
"e": 3811,
"s": 3768,
"text": "public interface Shape {\n void draw();\n}"
},
{
"code": null,
"e": 3868,
"s": 3811,
"text": "Create concrete classes implementing the same interface."
},
{
"code": null,
"e": 3890,
"s": 3868,
"text": "RoundedRectangle.java"
},
{
"code": null,
"e": 4052,
"s": 3890,
"text": "public class RoundedRectangle implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside RoundedRectangle::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 4071,
"s": 4052,
"text": "RoundedSquare.java"
},
{
"code": null,
"e": 4227,
"s": 4071,
"text": "public class RoundedSquare implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside RoundedSquare::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 4242,
"s": 4227,
"text": "Rectangle.java"
},
{
"code": null,
"e": 4390,
"s": 4242,
"text": "public class Rectangle implements Shape {\n @Override\n public void draw() {\n System.out.println(\"Inside Rectangle::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 4470,
"s": 4390,
"text": "Create an Abstract class to get factories for Normal and Rounded Shape Objects."
},
{
"code": null,
"e": 4491,
"s": 4470,
"text": "AbstractFactory.java"
},
{
"code": null,
"e": 4580,
"s": 4491,
"text": "public abstract class AbstractFactory {\n abstract Shape getShape(String shapeType) ;\n}"
},
{
"code": null,
"e": 4694,
"s": 4580,
"text": "Create Factory classes extending AbstractFactory to generate object of concrete class based on given information."
},
{
"code": null,
"e": 4712,
"s": 4694,
"text": "ShapeFactory.java"
},
{
"code": null,
"e": 5038,
"s": 4712,
"text": "public class ShapeFactory extends AbstractFactory {\n @Override\n public Shape getShape(String shapeType){ \n if(shapeType.equalsIgnoreCase(\"RECTANGLE\")){\n return new Rectangle(); \n }else if(shapeType.equalsIgnoreCase(\"SQUARE\")){\n return new Square();\n }\t \n return null;\n }\n}"
},
{
"code": null,
"e": 5063,
"s": 5038,
"text": "RoundedShapeFactory.java"
},
{
"code": null,
"e": 5410,
"s": 5063,
"text": "public class RoundedShapeFactory extends AbstractFactory {\n @Override\n public Shape getShape(String shapeType){ \n if(shapeType.equalsIgnoreCase(\"RECTANGLE\")){\n return new RoundedRectangle(); \n }else if(shapeType.equalsIgnoreCase(\"SQUARE\")){\n return new RoundedSquare();\n }\t \n return null;\n }\n}"
},
{
"code": null,
"e": 5509,
"s": 5410,
"text": "Create a Factory generator/producer class to get factories by passing an information such as Shape"
},
{
"code": null,
"e": 5530,
"s": 5509,
"text": "FactoryProducer.java"
},
{
"code": null,
"e": 5761,
"s": 5530,
"text": "public class FactoryProducer {\n public static AbstractFactory getFactory(boolean rounded){ \n if(rounded){\n return new RoundedShapeFactory(); \n }else{\n return new ShapeFactory();\n }\n }\n}"
},
{
"code": null,
"e": 5894,
"s": 5761,
"text": "Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type."
},
{
"code": null,
"e": 5926,
"s": 5894,
"text": "AbstractFactoryPatternDemo.java"
},
{
"code": null,
"e": 6860,
"s": 5926,
"text": "public class AbstractFactoryPatternDemo {\n public static void main(String[] args) {\n //get shape factory\n AbstractFactory shapeFactory = FactoryProducer.getFactory(false);\n //get an object of Shape Rectangle\n Shape shape1 = shapeFactory.getShape(\"RECTANGLE\");\n //call draw method of Shape Rectangle\n shape1.draw();\n //get an object of Shape Square \n Shape shape2 = shapeFactory.getShape(\"SQUARE\");\n //call draw method of Shape Square\n shape2.draw();\n //get shape factory\n AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true);\n //get an object of Shape Rectangle\n Shape shape3 = shapeFactory1.getShape(\"RECTANGLE\");\n //call draw method of Shape Rectangle\n shape3.draw();\n //get an object of Shape Square \n Shape shape4 = shapeFactory1.getShape(\"SQUARE\");\n //call draw method of Shape Square\n shape4.draw();\n \n }\n}"
},
{
"code": null,
"e": 6879,
"s": 6860,
"text": "Verify the output."
},
{
"code": null,
"e": 7020,
"s": 6879,
"text": "Inside Rectangle::draw() method.\nInside Square::draw() method.\nInside RoundedRectangle::draw() method.\nInside RoundedSquare::draw() method.\n"
},
{
"code": null,
"e": 7055,
"s": 7020,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7074,
"s": 7055,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7107,
"s": 7074,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7126,
"s": 7107,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7159,
"s": 7126,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7178,
"s": 7159,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7213,
"s": 7178,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7226,
"s": 7213,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 7258,
"s": 7226,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7271,
"s": 7258,
"text": " Zach Miller"
},
{
"code": null,
"e": 7304,
"s": 7271,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7318,
"s": 7304,
"text": " Sasha Miller"
},
{
"code": null,
"e": 7325,
"s": 7318,
"text": " Print"
},
{
"code": null,
"e": 7336,
"s": 7325,
"text": " Add Notes"
}
]
|
Find K Closest Points to the Origin in C++ | Suppose we have a set of points. Our task is to find K points which are closest to the origin. Suppose the points are (3, 3), (5, -1) and (-2, 4). Then the closest two (K = 2) points are (3, 3), (-2, 4).
To solve this problem, we will sort the list of points based on their Euclidean distance, after that take the top most K elements from the sorted list. Those are the K nearest points.
Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
class Point{
private:
int x, y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
void display(){
cout << "("<<x<<", "<<y<<")";
}
friend bool comparePoints(Point &p1, Point &p2);
};
bool comparePoints(Point &p1, Point &p2){
float dist1 = (p1.x * p1.x) + (p1.y * p1.y);
float dist2 = (p2.x * p2.x) + (p2.y * p2.y);
return dist1 < dist2;
}
void closestKPoints(Point points[], int n, int k){
sort(points, points+n, comparePoints);
for(int i = 0; i<k; i++){
points[i].display();
cout << endl;
}
}
int main() {
Point points[] = {{3, 3},{5, -1},{-2, 4}};
int n = sizeof(points)/sizeof(points[0]);
int k = 2;
closestKPoints(points, n, k);
}
(3, 3)
(-2, 4) | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "Suppose we have a set of points. Our task is to find K points which are closest to the origin. Suppose the points are (3, 3), (5, -1) and (-2, 4). Then the closest two (K = 2) points are (3, 3), (-2, 4)."
},
{
"code": null,
"e": 1450,
"s": 1266,
"text": "To solve this problem, we will sort the list of points based on their Euclidean distance, after that take the top most K elements from the sorted list. Those are the K nearest points."
},
{
"code": null,
"e": 1461,
"s": 1450,
"text": " Live Demo"
},
{
"code": null,
"e": 2254,
"s": 1461,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nclass Point{\n private:\n int x, y;\n public:\n Point(int x = 0, int y = 0){\n this->x = x;\n this->y = y;\n }\n void display(){\n cout << \"(\"<<x<<\", \"<<y<<\")\";\n }\n friend bool comparePoints(Point &p1, Point &p2);\n};\nbool comparePoints(Point &p1, Point &p2){\n float dist1 = (p1.x * p1.x) + (p1.y * p1.y);\n float dist2 = (p2.x * p2.x) + (p2.y * p2.y);\n return dist1 < dist2;\n}\nvoid closestKPoints(Point points[], int n, int k){\n sort(points, points+n, comparePoints);\n for(int i = 0; i<k; i++){\n points[i].display();\n cout << endl;\n }\n}\nint main() {\n Point points[] = {{3, 3},{5, -1},{-2, 4}};\n int n = sizeof(points)/sizeof(points[0]);\n int k = 2;\n closestKPoints(points, n, k);\n}"
},
{
"code": null,
"e": 2269,
"s": 2254,
"text": "(3, 3)\n(-2, 4)"
}
]
|
Program to find root of an equations using secant method - GeeksforGeeks | 08 Oct, 2021
The secant method is used to find the root of an equation f(x) = 0. It is started from two distinct estimates x1 and x2 for the root. It is an iterative procedure involving linear interpolation to a root. The iteration stops if the difference between two intermediate values is less than the convergence factor.
Examples :
Input : equation = x3 + x - 1
x1 = 0, x2 = 1, E = 0.0001
Output : Root of the given equation = 0.682326
No. of iteration=5
Algorithm
Initialize: x1, x2, E, n // E = convergence indicator
calculate f(x1),f(x2)
if(f(x1) * f(x2) = E); //repeat the loop until the convergence
print 'x0' //value of the root
print 'n' //number of iteration
}
else
print "can not found a root in the given interval"
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find root of an// equations using secant method#include <bits/stdc++.h>using namespace std;// function takes value of x and returns f(x)float f(float x){ // we are taking equation as x^3+x-1 float f = pow(x, 3) + x - 1; return f;} void secant(float x1, float x2, float E){ float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); } while (fabs(xm - x0) >= E); // repeat the loop // until the convergence cout << "Root of the given equation=" << x0 << endl; cout << "No. of iterations = " << n << endl; } else cout << "Can not find a root in the given interval";} // Driver codeint main(){ // initializing the values float x1 = 0, x2 = 1, E = 0.0001; secant(x1, x2, E); return 0;}
// Java Program to find root of an// equations using secant methodclass GFG { // function takes value of x and // returns f(x) static float f(float x) { // we are taking equation // as x^3+x-1 float f = (float)Math.pow(x, 3) + x - 1; return f; } static void secant(float x1, float x2, float E) { float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate // value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of // equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation // then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // repeat the loop until the // convergence } while (Math.abs(xm - x0) >= E); System.out.println("Root of the" + " given equation=" + x0); System.out.println("No. of " + "iterations = " + n); } else System.out.print("Can not find a" + " root in the given interval"); } // Driver code public static void main(String[] args) { // initializing the values float x1 = 0, x2 = 1, E = 0.0001f; secant(x1, x2, E); }} // This code is contributed by Anant Agarwal.
# Python3 Program to find root of an# equations using secant method # function takes value of x# and returns f(x)def f(x): # we are taking equation # as x^3+x-1 f = pow(x, 3) + x - 1; return f; def secant(x1, x2, E): n = 0; xm = 0; x0 = 0; c = 0; if (f(x1) * f(x2) < 0): while True: # calculate the intermediate value x0 = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); # check if x0 is root of # equation or not c = f(x1) * f(x0); # update the value of interval x1 = x2; x2 = x0; # update number of iteration n += 1; # if x0 is the root of equation # then break the loop if (c == 0): break; xm = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); if(abs(xm - x0) < E): break; print("Root of the given equation =", round(x0, 6)); print("No. of iterations = ", n); else: print("Can not find a root in ", "the given interval"); # Driver code # initializing the valuesx1 = 0;x2 = 1;E = 0.0001;secant(x1, x2, E); # This code is contributed by mits
// C# Program to find root of an// equations using secant methodusing System; class GFG { // function takes value of // x and returns f(x) static float f(float x) { // we are taking equation // as x^3+x-1 float f = (float)Math.Pow(x, 3) + x - 1; return f; } static void secant(float x1, float x2, float E) { float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate // value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of // equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation // then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // repeat the loop until // the convergence } while (Math.Abs(xm - x0) >= E); Console.WriteLine("Root of the" + " given equation=" + x0); Console.WriteLine("No. of " + "iterations = " + n); } else Console.WriteLine("Can not find a" + " root in the given interval"); } // Driver code public static void Main(String []args) { // initializing the values float x1 = 0, x2 = 1, E = 0.0001f; secant(x1, x2, E); }} // This code is contributed by vt_m.
<?php// PHP Program to find root of an// equations using secant method // function takes value of x// and returns f(x)function f( $x){ // we are taking equation // as x^3+x-1 $f = pow($x, 3) + $x - 1; return $f;} function secant($x1, $x2, $E){ $n = 0; $xm; $x0; $c; if (f($x1) * f($x2) < 0) { do { // calculate the intermediate value $x0 = ($x1 * f($x2) - $x2 * f($x1)) / (f($x2) - f($x1)); // check if x0 is root // of equation or not $c = f($x1) * f($x0); // update the value of interval $x1 = $x2; $x2 = $x0; // update number of iteration $n++; // if x0 is the root of equation // then break the loop if ($c == 0) break; $xm = ($x1 * f($x2) - $x2 * f($x1)) / (f($x2) - f($x1)); // repeat the loop // until the convergence } while (abs($xm - $x0) >= $E); echo "Root of the given equation=". $x0."\n" ; echo "No. of iterations = ". $n ; } else echo "Can not find a root in the given interval";} // Driver code{ // initializing the values $x1 = 0; $x2 = 1; $E = 0.0001; secant($x1, $x2, $E); return 0;} // This code is contributed by nitin mittal.?>
<script>// JavaScript Program to find root of an// equations using secant method // function takes value of x and returns f(x)function f(x){ // we are taking equation as x^3+x-1 let f = Math.pow(x, 3) + x - 1; return f;} function secant(x1, x2, E){ let n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); } while (Math.abs(xm - x0) >= E); // repeat the loop // until the convergence document.write("Root of the given equation=" + x0.toFixed(6) + "<br>"); document.write("No. of iterations = " + n + "<br>"); } else document.write("Can not find a root in the given interval");} // Driver code // initializing the values let x1 = 0, x2 = 1, E = 0.0001; secant(x1, x2, E); // This code is contributed by Surbhi Tyagi.</script>
Output :
Root of the given equation = 0.682326
No. of iterations = 5
Time Complexity = O(1)
Reference https://en.wikipedia.org/wiki/Secant_methodThis article is contributed by Niteesh 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
nitin mittal
Mithun Kumar
surbhityagi15
abhishek0719kadiyan
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Operators in C / C++
Program for factorial of a number
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube | [
{
"code": null,
"e": 24880,
"s": 24852,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25192,
"s": 24880,
"text": "The secant method is used to find the root of an equation f(x) = 0. It is started from two distinct estimates x1 and x2 for the root. It is an iterative procedure involving linear interpolation to a root. The iteration stops if the difference between two intermediate values is less than the convergence factor."
},
{
"code": null,
"e": 25204,
"s": 25192,
"text": "Examples : "
},
{
"code": null,
"e": 25345,
"s": 25204,
"text": "Input : equation = x3 + x - 1 \n x1 = 0, x2 = 1, E = 0.0001\nOutput : Root of the given equation = 0.682326\n No. of iteration=5"
},
{
"code": null,
"e": 25356,
"s": 25345,
"text": "Algorithm "
},
{
"code": null,
"e": 25637,
"s": 25356,
"text": "Initialize: x1, x2, E, n // E = convergence indicator\ncalculate f(x1),f(x2)\n\nif(f(x1) * f(x2) = E); //repeat the loop until the convergence\n print 'x0' //value of the root\n print 'n' //number of iteration\n}\nelse\n print \"can not found a root in the given interval\""
},
{
"code": null,
"e": 25641,
"s": 25637,
"text": "C++"
},
{
"code": null,
"e": 25646,
"s": 25641,
"text": "Java"
},
{
"code": null,
"e": 25654,
"s": 25646,
"text": "Python3"
},
{
"code": null,
"e": 25657,
"s": 25654,
"text": "C#"
},
{
"code": null,
"e": 25661,
"s": 25657,
"text": "PHP"
},
{
"code": null,
"e": 25672,
"s": 25661,
"text": "Javascript"
},
{
"code": "// C++ Program to find root of an// equations using secant method#include <bits/stdc++.h>using namespace std;// function takes value of x and returns f(x)float f(float x){ // we are taking equation as x^3+x-1 float f = pow(x, 3) + x - 1; return f;} void secant(float x1, float x2, float E){ float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); } while (fabs(xm - x0) >= E); // repeat the loop // until the convergence cout << \"Root of the given equation=\" << x0 << endl; cout << \"No. of iterations = \" << n << endl; } else cout << \"Can not find a root in the given interval\";} // Driver codeint main(){ // initializing the values float x1 = 0, x2 = 1, E = 0.0001; secant(x1, x2, E); return 0;}",
"e": 26969,
"s": 25672,
"text": null
},
{
"code": "// Java Program to find root of an// equations using secant methodclass GFG { // function takes value of x and // returns f(x) static float f(float x) { // we are taking equation // as x^3+x-1 float f = (float)Math.pow(x, 3) + x - 1; return f; } static void secant(float x1, float x2, float E) { float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate // value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of // equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation // then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // repeat the loop until the // convergence } while (Math.abs(xm - x0) >= E); System.out.println(\"Root of the\" + \" given equation=\" + x0); System.out.println(\"No. of \" + \"iterations = \" + n); } else System.out.print(\"Can not find a\" + \" root in the given interval\"); } // Driver code public static void main(String[] args) { // initializing the values float x1 = 0, x2 = 1, E = 0.0001f; secant(x1, x2, E); }} // This code is contributed by Anant Agarwal.",
"e": 28980,
"s": 26969,
"text": null
},
{
"code": "# Python3 Program to find root of an# equations using secant method # function takes value of x# and returns f(x)def f(x): # we are taking equation # as x^3+x-1 f = pow(x, 3) + x - 1; return f; def secant(x1, x2, E): n = 0; xm = 0; x0 = 0; c = 0; if (f(x1) * f(x2) < 0): while True: # calculate the intermediate value x0 = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); # check if x0 is root of # equation or not c = f(x1) * f(x0); # update the value of interval x1 = x2; x2 = x0; # update number of iteration n += 1; # if x0 is the root of equation # then break the loop if (c == 0): break; xm = ((x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1))); if(abs(xm - x0) < E): break; print(\"Root of the given equation =\", round(x0, 6)); print(\"No. of iterations = \", n); else: print(\"Can not find a root in \", \"the given interval\"); # Driver code # initializing the valuesx1 = 0;x2 = 1;E = 0.0001;secant(x1, x2, E); # This code is contributed by mits",
"e": 30319,
"s": 28980,
"text": null
},
{
"code": "// C# Program to find root of an// equations using secant methodusing System; class GFG { // function takes value of // x and returns f(x) static float f(float x) { // we are taking equation // as x^3+x-1 float f = (float)Math.Pow(x, 3) + x - 1; return f; } static void secant(float x1, float x2, float E) { float n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate // value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of // equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation // then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // repeat the loop until // the convergence } while (Math.Abs(xm - x0) >= E); Console.WriteLine(\"Root of the\" + \" given equation=\" + x0); Console.WriteLine(\"No. of \" + \"iterations = \" + n); } else Console.WriteLine(\"Can not find a\" + \" root in the given interval\"); } // Driver code public static void Main(String []args) { // initializing the values float x1 = 0, x2 = 1, E = 0.0001f; secant(x1, x2, E); }} // This code is contributed by vt_m.",
"e": 32343,
"s": 30319,
"text": null
},
{
"code": "<?php// PHP Program to find root of an// equations using secant method // function takes value of x// and returns f(x)function f( $x){ // we are taking equation // as x^3+x-1 $f = pow($x, 3) + $x - 1; return $f;} function secant($x1, $x2, $E){ $n = 0; $xm; $x0; $c; if (f($x1) * f($x2) < 0) { do { // calculate the intermediate value $x0 = ($x1 * f($x2) - $x2 * f($x1)) / (f($x2) - f($x1)); // check if x0 is root // of equation or not $c = f($x1) * f($x0); // update the value of interval $x1 = $x2; $x2 = $x0; // update number of iteration $n++; // if x0 is the root of equation // then break the loop if ($c == 0) break; $xm = ($x1 * f($x2) - $x2 * f($x1)) / (f($x2) - f($x1)); // repeat the loop // until the convergence } while (abs($xm - $x0) >= $E); echo \"Root of the given equation=\". $x0.\"\\n\" ; echo \"No. of iterations = \". $n ; } else echo \"Can not find a root in the given interval\";} // Driver code{ // initializing the values $x1 = 0; $x2 = 1; $E = 0.0001; secant($x1, $x2, $E); return 0;} // This code is contributed by nitin mittal.?>",
"e": 33775,
"s": 32343,
"text": null
},
{
"code": "<script>// JavaScript Program to find root of an// equations using secant method // function takes value of x and returns f(x)function f(x){ // we are taking equation as x^3+x-1 let f = Math.pow(x, 3) + x - 1; return f;} function secant(x1, x2, E){ let n = 0, xm, x0, c; if (f(x1) * f(x2) < 0) { do { // calculate the intermediate value x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); // check if x0 is root of equation or not c = f(x1) * f(x0); // update the value of interval x1 = x2; x2 = x0; // update number of iteration n++; // if x0 is the root of equation then break the loop if (c == 0) break; xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); } while (Math.abs(xm - x0) >= E); // repeat the loop // until the convergence document.write(\"Root of the given equation=\" + x0.toFixed(6) + \"<br>\"); document.write(\"No. of iterations = \" + n + \"<br>\"); } else document.write(\"Can not find a root in the given interval\");} // Driver code // initializing the values let x1 = 0, x2 = 1, E = 0.0001; secant(x1, x2, E); // This code is contributed by Surbhi Tyagi.</script>",
"e": 35095,
"s": 33775,
"text": null
},
{
"code": null,
"e": 35105,
"s": 35095,
"text": "Output : "
},
{
"code": null,
"e": 35165,
"s": 35105,
"text": "Root of the given equation = 0.682326\nNo. of iterations = 5"
},
{
"code": null,
"e": 35188,
"s": 35165,
"text": "Time Complexity = O(1)"
},
{
"code": null,
"e": 35663,
"s": 35188,
"text": "Reference https://en.wikipedia.org/wiki/Secant_methodThis article is contributed by Niteesh 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35668,
"s": 35663,
"text": "vt_m"
},
{
"code": null,
"e": 35681,
"s": 35668,
"text": "nitin mittal"
},
{
"code": null,
"e": 35694,
"s": 35681,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35708,
"s": 35694,
"text": "surbhityagi15"
},
{
"code": null,
"e": 35728,
"s": 35708,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 35741,
"s": 35728,
"text": "Mathematical"
},
{
"code": null,
"e": 35754,
"s": 35741,
"text": "Mathematical"
},
{
"code": null,
"e": 35852,
"s": 35754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35861,
"s": 35852,
"text": "Comments"
},
{
"code": null,
"e": 35874,
"s": 35861,
"text": "Old Comments"
},
{
"code": null,
"e": 35917,
"s": 35874,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 35959,
"s": 35917,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 35983,
"s": 35959,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 35997,
"s": 35983,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36046,
"s": 35997,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36067,
"s": 36046,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 36101,
"s": 36067,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 36123,
"s": 36101,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 36164,
"s": 36123,
"text": "Program for Decimal to Binary Conversion"
}
]
|
C++ program to find two numbers with sum and product both same as N | In this tutorial, we will be discussing a program to find two numbers (say ‘a’ and ‘b’) such that both
a+b = N and a*b = N are satisfied.
Eliminating ‘a’ from both the equations, we get a quadratic equation in ‘b’ and ‘N’ i.e
b2 - bN + N = 0
This equation will have two roots which will give us the value of both ‘a’ and ‘b’. Using the determinant method to find the roots, we get the value of ‘a’ and ‘b’ as,
a=(N−N∗N−4N)/2b=(N+N∗N−4N)/2
Live Demo
#include <iostream>
//header file for the square root function
#include <math.h>
using namespace std;
int main() {
float N = 12,a,b;
cin >> N;
//using determinant method to find roots
a = (N + sqrt(N*N - 4*N))/2;
b = (N - sqrt(N*N - 4*N))/2;
cout << "The two integers are :" << endl;
cout << "a - " << a << endl;
cout << "b - " << b << endl;
return 0;
}
The two integers are :
a - 10.899
b - 1.10102 | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to find two numbers (say ‘a’ and ‘b’) such that both"
},
{
"code": null,
"e": 1200,
"s": 1165,
"text": "a+b = N and a*b = N are satisfied."
},
{
"code": null,
"e": 1288,
"s": 1200,
"text": "Eliminating ‘a’ from both the equations, we get a quadratic equation in ‘b’ and ‘N’ i.e"
},
{
"code": null,
"e": 1304,
"s": 1288,
"text": "b2 - bN + N = 0"
},
{
"code": null,
"e": 1472,
"s": 1304,
"text": "This equation will have two roots which will give us the value of both ‘a’ and ‘b’. Using the determinant method to find the roots, we get the value of ‘a’ and ‘b’ as,"
},
{
"code": null,
"e": 1501,
"s": 1472,
"text": "a=(N−N∗N−4N)/2b=(N+N∗N−4N)/2"
},
{
"code": null,
"e": 1512,
"s": 1501,
"text": " Live Demo"
},
{
"code": null,
"e": 1893,
"s": 1512,
"text": "#include <iostream>\n//header file for the square root function\n#include <math.h>\nusing namespace std;\nint main() {\n float N = 12,a,b;\n cin >> N;\n //using determinant method to find roots\n a = (N + sqrt(N*N - 4*N))/2;\n b = (N - sqrt(N*N - 4*N))/2;\n cout << \"The two integers are :\" << endl;\n cout << \"a - \" << a << endl;\n cout << \"b - \" << b << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1939,
"s": 1893,
"text": "The two integers are :\na - 10.899\nb - 1.10102"
}
]
|
Copy char array to string in Java | Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied.
Let us first create a character array.
char[] arr = { 'p', 'q', 'r', 's' };
The method valueOf() will convert the entire array into a string.
String str = String.valueOf(arr);
The following is an example.
Live Demo
public class Demo {
public static void main(String []args) {
char[] arr = { 'p', 'q', 'r', 's' };
String str = String.valueOf(arr);
System.out.println(str);
}
}
Pqrs
Let us see another example that use copyValueOf() method that convert char array to string.
Live Demo
public class Demo {
public static void main(String []args) {
char[] arr = { 'p', 'q', 'r', 's' };
String str = String.copyValueOf(arr, 1, 2);
System.out.println(str);
}
}
Qr | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied."
},
{
"code": null,
"e": 1325,
"s": 1286,
"text": "Let us first create a character array."
},
{
"code": null,
"e": 1362,
"s": 1325,
"text": "char[] arr = { 'p', 'q', 'r', 's' };"
},
{
"code": null,
"e": 1428,
"s": 1362,
"text": "The method valueOf() will convert the entire array into a string."
},
{
"code": null,
"e": 1462,
"s": 1428,
"text": "String str = String.valueOf(arr);"
},
{
"code": null,
"e": 1491,
"s": 1462,
"text": "The following is an example."
},
{
"code": null,
"e": 1502,
"s": 1491,
"text": " Live Demo"
},
{
"code": null,
"e": 1687,
"s": 1502,
"text": "public class Demo {\n public static void main(String []args) {\n char[] arr = { 'p', 'q', 'r', 's' };\n String str = String.valueOf(arr);\n System.out.println(str);\n }\n}"
},
{
"code": null,
"e": 1692,
"s": 1687,
"text": "Pqrs"
},
{
"code": null,
"e": 1784,
"s": 1692,
"text": "Let us see another example that use copyValueOf() method that convert char array to string."
},
{
"code": null,
"e": 1795,
"s": 1784,
"text": " Live Demo"
},
{
"code": null,
"e": 1990,
"s": 1795,
"text": "public class Demo {\n public static void main(String []args) {\n char[] arr = { 'p', 'q', 'r', 's' };\n String str = String.copyValueOf(arr, 1, 2);\n System.out.println(str);\n }\n}"
},
{
"code": null,
"e": 1993,
"s": 1990,
"text": "Qr"
}
]
|
How to extract a single column of an R data frame as a data frame? | Generally, we extract columns as a vector from an R data frame but sometimes we might need a column as a data frame, therefore, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame.
Consider the below data frame −
set.seed(9)
x1<-rnorm(20)
x2<-rnorm(20,0.2)
x3<-rnorm(20,0.5)
x4<-rnorm(20,2.5)
x5<-rpois(20,5)
x6<-runif(20,2,5)
df<-data.frame(x1,x2,x3,x4,x5,x6)
df
x1 x2 x3 x4 x5 x6
1 -0.76679604 1.95699294 -0.30845634 2.7812222 5 3.087890
2 -0.81645834 0.38225214 -1.51938169 1.2972914 8 3.559316
3 -0.14153519 -0.06688875 -0.23872407 2.9651637 3 2.710724
4 -0.27760503 1.12642163 0.88288656 2.8520164 8 3.417152
5 0.43630690 -0.49333188 2.23086367 1.9101438 5 2.520602
6 -1.18687252 2.88199007 0.29691805 1.6464000 8 4.958743
7 1.19198691 0.42252448 -0.49639735 2.2532679 8 4.302067
8 -0.01819034 -0.50667241 -0.80653629 4.0393386 6 3.447421
9 -0.24808460 0.61721325 -0.49783160 3.0460777 2 2.992220
10 -0.36293689 0.56955678 -0.06502873 4.0649619 4 2.563962
11 1.27757055 -0.71376435 2.25205784 2.7496702 5 3.204598
12 -0.46889715 -0.11691475 -0.04777135 0.5375814 4 2.962441
13 0.07105410 1.24905921 -0.35852571 1.6909398 7 2.752308
14 -0.26603845 0.36811181 0.54929453 2.0013149 5 3.582086
15 1.84525720 0.23144021 0.29995552 2.8051218 3 4.365315
16 -0.83944966 -0.81033054 -0.60395445 2.2107928 3 3.258313
17 -0.07744806 0.58275153 0.74058804 3.9577142 2 2.204786
18 -2.61770553 -0.61969653 0.88111362 3.3737555 9 3.329696
19 0.88788403 0.56171109 2.73045895 1.5470440 7 4.025269
20 -0.70749145 0.29337136 1.69920239 2.4683245 4 4.254372
Extracting some columns as a separate data frames −
x2 <-as.data.frame(df[,2])
x2
df[, 2]
1 1.95699294
2 0.38225214
3 -0.06688875
4 1.12642163
5 -0.49333188
6 2.88199007
7 0.42252448
8 -0.50667241
9 0.61721325
10 0.56955678
11 -0.71376435
12 -0.11691475
13 1.24905921
14 0.36811181
15 0.23144021
16 -0.81033054
17 0.58275153
18 -0.61969653
19 0.56171109
20 0.29337136
is.data.frame(x2)
[1] TRUE
x5 <-as.data.frame(df[,5])
x5
df[, 5]
1 5
2 8
3 3
4 8
5 5
6 8
7 8
8 6
9 2
10 4
11 5
12 4
13 7
14 5
15 3
16 3
17 2
18 9
19 7
20 4
is.data.frame(x5)
[1] TRUE
x3 <-as.data.frame(df[,3])
x3
df[, 3]
1 -0.30845634
2 -1.51938169
3 -0.23872407
4 0.88288656
5 2.23086367
6 0.29691805
7 -0.49639735
8 -0.80653629
9 -0.49783160
10 -0.06502873
11 2.25205784
12 -0.04777135
13 -0.35852571
14 0.54929453
15 0.29995552
16 -0.60395445
17 0.74058804
18 0.88111362
19 2.73045895
20 1.69920239
is.data.frame(x3)
[1] TRUE | [
{
"code": null,
"e": 1380,
"s": 1062,
"text": "Generally, we extract columns as a vector from an R data frame but sometimes we might need a column as a data frame, therefore, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame."
},
{
"code": null,
"e": 1412,
"s": 1380,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1563,
"s": 1412,
"text": "set.seed(9)\nx1<-rnorm(20)\nx2<-rnorm(20,0.2)\nx3<-rnorm(20,0.5)\nx4<-rnorm(20,2.5)\nx5<-rpois(20,5)\nx6<-runif(20,2,5)\ndf<-data.frame(x1,x2,x3,x4,x5,x6)\ndf"
},
{
"code": null,
"e": 2779,
"s": 1563,
"text": " x1 x2 x3 x4 x5 x6\n1 -0.76679604 1.95699294 -0.30845634 2.7812222 5 3.087890\n2 -0.81645834 0.38225214 -1.51938169 1.2972914 8 3.559316\n3 -0.14153519 -0.06688875 -0.23872407 2.9651637 3 2.710724\n4 -0.27760503 1.12642163 0.88288656 2.8520164 8 3.417152\n5 0.43630690 -0.49333188 2.23086367 1.9101438 5 2.520602\n6 -1.18687252 2.88199007 0.29691805 1.6464000 8 4.958743\n7 1.19198691 0.42252448 -0.49639735 2.2532679 8 4.302067\n8 -0.01819034 -0.50667241 -0.80653629 4.0393386 6 3.447421\n9 -0.24808460 0.61721325 -0.49783160 3.0460777 2 2.992220\n10 -0.36293689 0.56955678 -0.06502873 4.0649619 4 2.563962\n11 1.27757055 -0.71376435 2.25205784 2.7496702 5 3.204598\n12 -0.46889715 -0.11691475 -0.04777135 0.5375814 4 2.962441\n13 0.07105410 1.24905921 -0.35852571 1.6909398 7 2.752308\n14 -0.26603845 0.36811181 0.54929453 2.0013149 5 3.582086\n15 1.84525720 0.23144021 0.29995552 2.8051218 3 4.365315\n16 -0.83944966 -0.81033054 -0.60395445 2.2107928 3 3.258313\n17 -0.07744806 0.58275153 0.74058804 3.9577142 2 2.204786\n18 -2.61770553 -0.61969653 0.88111362 3.3737555 9 3.329696\n19 0.88788403 0.56171109 2.73045895 1.5470440 7 4.025269\n20 -0.70749145 0.29337136 1.69920239 2.4683245 4 4.254372"
},
{
"code": null,
"e": 2831,
"s": 2779,
"text": "Extracting some columns as a separate data frames −"
},
{
"code": null,
"e": 2861,
"s": 2831,
"text": "x2 <-as.data.frame(df[,2])\nx2"
},
{
"code": null,
"e": 3147,
"s": 2861,
"text": "df[, 2]\n1 1.95699294\n2 0.38225214\n3 -0.06688875\n4 1.12642163\n5 -0.49333188\n6 2.88199007\n7 0.42252448\n8 -0.50667241\n9 0.61721325\n10 0.56955678\n11 -0.71376435\n12 -0.11691475\n13 1.24905921\n14 0.36811181\n15 0.23144021\n16 -0.81033054\n17 0.58275153\n18 -0.61969653\n19 0.56171109\n20 0.29337136"
},
{
"code": null,
"e": 3212,
"s": 3147,
"text": "is.data.frame(x2)\n[1] TRUE\nx5 <-as.data.frame(df[,5])\nx5\ndf[, 5]"
},
{
"code": null,
"e": 3303,
"s": 3212,
"text": "1 5\n2 8\n3 3\n4 8\n5 5\n6 8\n7 8\n8 6\n9 2\n10 4\n11 5\n12 4\n13 7\n14 5\n15 3\n16 3\n17 2\n18 9\n19 7\n20 4"
},
{
"code": null,
"e": 3368,
"s": 3303,
"text": "is.data.frame(x5)\n[1] TRUE\nx3 <-as.data.frame(df[,3])\nx3\ndf[, 3]"
},
{
"code": null,
"e": 3676,
"s": 3368,
"text": "1 -0.30845634\n2 -1.51938169\n3 -0.23872407\n4 0.88288656\n5 2.23086367\n6 0.29691805\n7 -0.49639735\n8 -0.80653629\n9 -0.49783160\n10 -0.06502873\n11 2.25205784\n12 -0.04777135\n13 -0.35852571\n14 0.54929453\n15 0.29995552\n16 -0.60395445\n17 0.74058804\n18 0.88111362\n19 2.73045895\n20 1.69920239\nis.data.frame(x3)\n[1] TRUE"
}
]
|
Jackson - Quick Guide | Jackson is a simple java based library to serialize java objects to JSON and vice versa.
Easy to use. - jackson API provides a high level facade to simplify commonly used use cases.
Easy to use. - jackson API provides a high level facade to simplify commonly used use cases.
No need to create mapping. - jackson API provides default mapping for most of the objects to be serialized.
No need to create mapping. - jackson API provides default mapping for most of the objects to be serialized.
Performance. - jackson is quiet fast and is of low memory footprint and is suitable for large object graphs or systems.
Performance. - jackson is quiet fast and is of low memory footprint and is suitable for large object graphs or systems.
Clean JSON. - jackson creates a clean and compact JSON results which is easy to read.
Clean JSON. - jackson creates a clean and compact JSON results which is easy to read.
No Dependency. - jackson library does not require any other library apart from jdk.
No Dependency. - jackson library does not require any other library apart from jdk.
Open Source - jackson library is open source and is free to use.
Open Source - jackson library is open source and is free to use.
Jackson provides three alternative ways to process JSON
Streaming API - reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.
Streaming API - reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.
Tree Model - prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.
Tree Model - prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.
Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Full Data Binding - Converts JSON to and from any JAVA type.
ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML.
Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Full Data Binding - Converts JSON to and from any JAVA type.
Full Data Binding - Converts JSON to and from any JAVA type.
You really do not need to set up your own environment to start learning Guava, a JAVA based library. Reason is very simple, we already have setup Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.
Try following example using Try it option available at the top right corner of the below sample code box:
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.
If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment.
Java SE is freely available from the link Download Java. So you download a version based on your operating system.
Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:
Assuming you have installed Java in c:\Program Files\java\jdk directory:
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Assuming you have installed Java in c:\Program Files\java\jdk directory:
Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:
Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html.
Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html.
Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/.
Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/.
Download the latest version of Jackson jar file from Maven Repository - Jackson. In this tutorial, jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar are downloaded and copied into C:\> jackson folder.
Set the jackson_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows.
Set the CLASSPATH environment variable to point to the jackson jar location. Assuming, we've stored jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows.
Before going into the details of the jackson library, let's see an application in action. In this example, we've created Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
"name" : "Mahesh",
"age" : 21
}
Following are the important steps to be considered here.
Create ObjectMapper object. It is a reusable object.
ObjectMapper mapper = new ObjectMapper();
Use readValue() method to get the Object from the JSON. Pass json string/ source of json string and object type as parameter.
//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);
Use writeValueAsString() method to get the JSON string representation of an object.
//Object to JSON Conversion
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content, and to support more advanced Object concepts such as polymorphism and Object identity. ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes.
Following is the declaration for com.fasterxml.jackson.databind.ObjectMapper class −
public class ObjectMapper
extends ObjectCodec
implements Versioned, Serializable
Customized TypeResolverBuilder that provides type resolver builders used with so-called "default typing" (see enableDefaultTyping() for details).
Enumeration used with enableDefaultTyping() to specify what kind of types (classes) default typing should be used for.
protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process.
protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process.
protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes.
protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes.
protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs.
protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs.
protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary.
protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary.
protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in".
protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in".
protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property.
protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property.
protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly).
protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly).
protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers.
protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers.
protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process.
protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process.
protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.
protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.
protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching.
protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching.
protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed.
protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed.
protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages).
protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages).
protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR
protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR
protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances.
protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances.
protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER
protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER
Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory.
Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators.
Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators, and uses given providers for accessing serializers and deserializers.
Copy-constructor, mostly used to support copy().
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Jackson_WORKSPACE
File: JacksonTester.java
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
"name" : "Mahesh",
"age" : 21
}
let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
Student student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("student.json"), student);
}
private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(new File("student.json"), Student.class);
return student;
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ]
Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Full Data Binding - Converts JSON to and from any JAVA type.
Full Data Binding - Converts JSON to and from any JAVA type.
ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML.
Simple data binding refers to mapping of JSON to JAVA Core data types. Following table illustrates the relationship between JSON types vs Java Types.
Let's see simple data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> studentDataMap = new HashMap<String,Object>();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentDataMap.put("student", student);
// JAVA String
studentDataMap.put("name", "Mahesh Kumar");
// JAVA Boolean
studentDataMap.put("verified", Boolean.FALSE);
// Array
studentDataMap.put("marks", marks);
mapper.writeValue(new File("student.json"), studentDataMap);
//result student.json
//{
// "student":{"name":"Mahesh","age":10},
// "marks":[1,2,3],
// "verified":false,
// "name":"Mahesh Kumar"
//}
studentDataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(studentDataMap.get("student"));
System.out.println(studentDataMap.get("name"));
System.out.println(studentDataMap.get("verified"));
System.out.println(studentDataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
{name=Mahesh, age=10}
Mahesh Kumar
false
[1, 2, 3]
Full data binding refers to mapping of JSON to any JAVA Object.
//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
//map JSON content to Student object
Student student = mapper.readValue(new File("student.json"), Student.class);
//map Student object to JSON content
mapper.writeValue(new File("student.json"), student);
Let's see simple data binding in action. Here we'll map JAVA Object directly to JSON and vice versa.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
Student student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("student.json"), student);
}
private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(new File("student.json"), Student.class);
return student;
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ]
In simple data binding, we've used Map class which use String as key and Object as a value object. Instead we can have concrete java object and type cast it to be used in JSON binding.
Consider the following example with a class UserData, a class to hold user specific data.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, UserData> userDataMap = new HashMap<String, UserData>();
UserData studentData = new UserData();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentData.setStudent(student);
// JAVA String
studentData.setName("Mahesh Kumar");
// JAVA Boolean
studentData.setVerified(Boolean.FALSE);
// Array
studentData.setMarks(marks);
TypeReference ref = new TypeReference<Map<String,UserData>>() { };
userDataMap.put("studentData1", studentData);
mapper.writeValue(new File("student.json"), userDataMap);
//{
// "studentData1":
// {
// "student":
// {
// "name":"Mahesh",
// "age":10
// },
// "name":"Mahesh Kumar",
// "verified":false,
// "marks":[1,2,3]
// }
//}
userDataMap = mapper.readValue(new File("student.json"), ref);
System.out.println(userDataMap.get("studentData1").getStudent());
System.out.println(userDataMap.get("studentData1").getName());
System.out.println(userDataMap.get("studentData1").getVerified());
System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
class UserData {
private Student student;
private String name;
private Boolean verified;
private int[] marks;
public UserData(){}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public int[] getMarks() {
return marks;
}
public void setMarks(int[] marks) {
this.marks = marks;
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ]
Mahesh Kumar
false
[1, 2, 3]
Tree Model prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.
ObjectMapper provides a pointer to root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.
//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);
Get each node using relative path to the root node while traversing tree and process the data. Consider the following code snippet traversing the tree provided the root node.
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.intValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.intValue() + " ");
}
System.out.println("]");
}
catch (JsonParseException e) { e.printStackTrace(); }
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]
In this example, we've created a Tree using JsonNode and write it to a json file and read back.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.intValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.intValue() + " ");
}
System.out.println("]");
}
catch (JsonParseException e) { e.printStackTrace(); }
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]
In this example, we've created a Tree using JsonNode and write it to a json file and read back tree and then convert it as a Student object.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
JsonNode marksNode = mapper.createArrayNode();
((ArrayNode)marksNode).add(100);
((ArrayNode)marksNode).add(90);
((ArrayNode)marksNode).add(85);
((ObjectNode) rootNode).put("name", "Mahesh Kumar");
((ObjectNode) rootNode).put("age", 21);
((ObjectNode) rootNode).put("verified", false);
((ObjectNode) rootNode).put("marks",marksNode);
mapper.writeValue(new File("student.json"), rootNode);
rootNode = mapper.readTree(new File("student.json"));
Student student = mapper.treeToValue(rootNode, Student.class);
System.out.println("Name: "+ student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Verified: " + (student.isVerified() ? "Yes":"No"));
System.out.println("Marks: "+Arrays.toString(student.getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int age;
boolean verified;
int[] marks;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
public int[] getMarks() {
return marks;
}
public void setMarks(int[] marks) {
this.marks = marks;
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]
Streaming API reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.
In this Article, we'll showcase using Jackson streaming APIs to read and write JSON data. Streaming API works with concept of token and every details of Json is to be handle carefuly. Following are two class which we'll use in the examples:
JsonGenerator - Write to JSON String.
JsonGenerator - Write to JSON String.
JsonParser - Parse JSON String.
JsonParser - Parse JSON String.
Using JsonGenerator is pretty simple. First create the JsonGenerator using JsonFactory.createJsonGenerator() method and use it's write***() methods to write each json value.
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
"student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
Let's see JsonGenerator in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
try {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("student.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
// "age" : 21
jsonGenerator.writeNumberField("age", 21);
// "verified" : false
jsonGenerator.writeBooleanField("verified", false);
// "marks" : [100, 90, 85]
jsonGenerator.writeFieldName("marks");
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
// ]
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> dataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(dataMap.get("name"));
System.out.println(dataMap.get("age"));
System.out.println(dataMap.get("verified"));
System.out.println(dataMap.get("marks"));
}
catch (JsonParseException e) { e.printStackTrace(); }
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Mahesh Kumar
21
false
[100, 90, 85]
Using JsonParser is again pretty simple. First create the JsonParser using JsonFactory.createJsonParser() method and use it's nextToken() methods to read each json string as token. Check each token and process accordingly
JsonFactory jasonFactory = new JsonFactory();
JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
}
Let's see JsonParser in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
"student.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Mahesh Kumar");
jsonGenerator.writeNumberField("age", 21);
jsonGenerator.writeBooleanField("verified", false);
jsonGenerator.writeFieldName("marks");
jsonGenerator.writeStartArray(); // [
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
JsonParser jsonParser = jsonFactory.createParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("age".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if("verified".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if("marks".equals(fieldname)){
//move to [
jsonParser.nextToken();
// loop till token equal to "]"
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println(jsonParser.getNumberValue());
}
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Mahesh Kumar
21
false
[100, 90, 85]
JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.
Following is the declaration for org.codehaus.jackson.JsonParser class:
public abstract class JsonParser
extends Object
implements Closeable, Versioned
protected PrettyPrinter _cfgPrettyPrinter - Object that handles pretty-printing (usually additional white space to make results more human-readable) during output.
protected PrettyPrinter _cfgPrettyPrinter - Object that handles pretty-printing (usually additional white space to make results more human-readable) during output.
protected JsonToken _currToken - Last token retrieved via nextToken(), if any.
protected JsonToken _currToken - Last token retrieved via nextToken(), if any.
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
protected JsonToken _lastClearedToken - Last cleared token, if any: that is, value that was in effect when clearCurrentToken() was called.
protected JsonToken _lastClearedToken - Last cleared token, if any: that is, value that was in effect when clearCurrentToken() was called.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.
Following is the declaration for com.fasterxml.jackson.core.JsonParser class:
public abstract class JsonParser
extends Object
implements Closeable, Versioned
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1842,
"s": 1753,
"text": "Jackson is a simple java based library to serialize java objects to JSON and vice versa."
},
{
"code": null,
"e": 1935,
"s": 1842,
"text": "Easy to use. - jackson API provides a high level facade to simplify commonly used use cases."
},
{
"code": null,
"e": 2028,
"s": 1935,
"text": "Easy to use. - jackson API provides a high level facade to simplify commonly used use cases."
},
{
"code": null,
"e": 2137,
"s": 2028,
"text": "No need to create mapping. - jackson API provides default mapping for most of the objects to be serialized."
},
{
"code": null,
"e": 2246,
"s": 2137,
"text": "No need to create mapping. - jackson API provides default mapping for most of the objects to be serialized."
},
{
"code": null,
"e": 2366,
"s": 2246,
"text": "Performance. - jackson is quiet fast and is of low memory footprint and is suitable for large object graphs or systems."
},
{
"code": null,
"e": 2486,
"s": 2366,
"text": "Performance. - jackson is quiet fast and is of low memory footprint and is suitable for large object graphs or systems."
},
{
"code": null,
"e": 2573,
"s": 2486,
"text": "Clean JSON. - jackson creates a clean and compact JSON results which is easy to read."
},
{
"code": null,
"e": 2660,
"s": 2573,
"text": "Clean JSON. - jackson creates a clean and compact JSON results which is easy to read."
},
{
"code": null,
"e": 2745,
"s": 2660,
"text": "No Dependency. - jackson library does not require any other library apart from jdk."
},
{
"code": null,
"e": 2830,
"s": 2745,
"text": "No Dependency. - jackson library does not require any other library apart from jdk."
},
{
"code": null,
"e": 2896,
"s": 2830,
"text": "Open Source - jackson library is open source and is free to use."
},
{
"code": null,
"e": 2962,
"s": 2896,
"text": "Open Source - jackson library is open source and is free to use."
},
{
"code": null,
"e": 3018,
"s": 2962,
"text": "Jackson provides three alternative ways to process JSON"
},
{
"code": null,
"e": 3297,
"s": 3018,
"text": "Streaming API - reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML."
},
{
"code": null,
"e": 3576,
"s": 3297,
"text": "Streaming API - reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML."
},
{
"code": null,
"e": 3764,
"s": 3576,
"text": "Tree Model - prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML."
},
{
"code": null,
"e": 3952,
"s": 3764,
"text": "Tree Model - prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML."
},
{
"code": null,
"e": 4402,
"s": 3952,
"text": "Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.\n\nSimple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.\nFull Data Binding - Converts JSON to and from any JAVA type.\n\nObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML.\n"
},
{
"code": null,
"e": 4539,
"s": 4402,
"text": "Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.\n"
},
{
"code": null,
"e": 4650,
"s": 4539,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 4761,
"s": 4650,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 4822,
"s": 4761,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 4883,
"s": 4822,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 5343,
"s": 4883,
"text": "You really do not need to set up your own environment to start learning Guava, a JAVA based library. Reason is very simple, we already have setup Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online."
},
{
"code": null,
"e": 5449,
"s": 5343,
"text": "Try following example using Try it option available at the top right corner of the below sample code box:"
},
{
"code": null,
"e": 5580,
"s": 5449,
"text": "public class MyFirstJavaProgram {\n\n public static void main(String []args) {\n System.out.println(\"Hello World\");\n }\n} "
},
{
"code": null,
"e": 5706,
"s": 5580,
"text": "For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning."
},
{
"code": null,
"e": 5931,
"s": 5706,
"text": "If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment."
},
{
"code": null,
"e": 6046,
"s": 5931,
"text": "Java SE is freely available from the link Download Java. So you download a version based on your operating system."
},
{
"code": null,
"e": 6268,
"s": 6046,
"text": "Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:"
},
{
"code": null,
"e": 6341,
"s": 6268,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory:"
},
{
"code": null,
"e": 6396,
"s": 6341,
"text": "Right-click on 'My Computer' and select 'Properties'. "
},
{
"code": null,
"e": 6451,
"s": 6396,
"text": "Right-click on 'My Computer' and select 'Properties'. "
},
{
"code": null,
"e": 6521,
"s": 6451,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 6591,
"s": 6521,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 6827,
"s": 6591,
"text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 7063,
"s": 6827,
"text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 7136,
"s": 7063,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory:"
},
{
"code": null,
"e": 7255,
"s": 7136,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'"
},
{
"code": null,
"e": 7374,
"s": 7255,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'"
},
{
"code": null,
"e": 7537,
"s": 7374,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 7677,
"s": 7537,
"text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 7851,
"s": 7677,
"text": "To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:"
},
{
"code": null,
"e": 7969,
"s": 7851,
"text": "Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 8087,
"s": 7969,
"text": "Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 8204,
"s": 8087,
"text": "Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html."
},
{
"code": null,
"e": 8321,
"s": 8204,
"text": "Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html."
},
{
"code": null,
"e": 8448,
"s": 8321,
"text": "Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/."
},
{
"code": null,
"e": 8575,
"s": 8448,
"text": "Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/."
},
{
"code": null,
"e": 8810,
"s": 8575,
"text": "Download the latest version of Jackson jar file from Maven Repository - Jackson. In this tutorial, jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar are downloaded and copied into C:\\> jackson folder."
},
{
"code": null,
"e": 9104,
"s": 8810,
"text": "Set the jackson_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows."
},
{
"code": null,
"e": 9347,
"s": 9104,
"text": "Set the CLASSPATH environment variable to point to the jackson jar location. Assuming, we've stored jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows."
},
{
"code": null,
"e": 9609,
"s": 9347,
"text": "Before going into the details of the jackson library, let's see an application in action. In this example, we've created Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String."
},
{
"code": null,
"e": 9680,
"s": 9609,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 9705,
"s": 9680,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 11001,
"s": 9705,
"text": "import java.io.IOException;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n \n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"name\\\":\\\"Mahesh\\\", \\\"age\\\":21}\";\n \n //map json to student\n try{\n Student student = mapper.readValue(jsonString, Student.class);\n \n System.out.println(student);\n \n jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);\n \n System.out.println(jsonString);\n }\n catch (JsonParseException e) { e.printStackTrace();}\n catch (JsonMappingException e) { e.printStackTrace(); }\n catch (IOException e) { e.printStackTrace(); }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\n}"
},
{
"code": null,
"e": 11019,
"s": 11001,
"text": "Verify the result"
},
{
"code": null,
"e": 11072,
"s": 11019,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 11118,
"s": 11072,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 11163,
"s": 11118,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 11203,
"s": 11163,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 11221,
"s": 11203,
"text": "Verify the Output"
},
{
"code": null,
"e": 11294,
"s": 11221,
"text": "Student [ name: Mahesh, age: 21 ]\n{\n \"name\" : \"Mahesh\",\n \"age\" : 21\n}\n"
},
{
"code": null,
"e": 11351,
"s": 11294,
"text": "Following are the important steps to be considered here."
},
{
"code": null,
"e": 11404,
"s": 11351,
"text": "Create ObjectMapper object. It is a reusable object."
},
{
"code": null,
"e": 11446,
"s": 11404,
"text": "ObjectMapper mapper = new ObjectMapper();"
},
{
"code": null,
"e": 11572,
"s": 11446,
"text": "Use readValue() method to get the Object from the JSON. Pass json string/ source of json string and object type as parameter."
},
{
"code": null,
"e": 11663,
"s": 11572,
"text": "//Object to JSON Conversion\nStudent student = mapper.readValue(jsonString, Student.class);"
},
{
"code": null,
"e": 11747,
"s": 11663,
"text": "Use writeValueAsString() method to get the JSON string representation of an object."
},
{
"code": null,
"e": 11859,
"s": 11747,
"text": "//Object to JSON Conversion\t\t\njsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);"
},
{
"code": null,
"e": 12443,
"s": 11859,
"text": "ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content, and to support more advanced Object concepts such as polymorphism and Object identity. ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes."
},
{
"code": null,
"e": 12528,
"s": 12443,
"text": "Following is the declaration for com.fasterxml.jackson.databind.ObjectMapper class −"
},
{
"code": null,
"e": 12618,
"s": 12528,
"text": "public class ObjectMapper\n extends ObjectCodec\n implements Versioned, Serializable"
},
{
"code": null,
"e": 12764,
"s": 12618,
"text": "Customized TypeResolverBuilder that provides type resolver builders used with so-called \"default typing\" (see enableDefaultTyping() for details)."
},
{
"code": null,
"e": 12883,
"s": 12764,
"text": "Enumeration used with enableDefaultTyping() to specify what kind of types (classes) default typing should be used for."
},
{
"code": null,
"e": 13027,
"s": 12883,
"text": "protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process."
},
{
"code": null,
"e": 13171,
"s": 13027,
"text": "protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process."
},
{
"code": null,
"e": 13304,
"s": 13171,
"text": "protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes."
},
{
"code": null,
"e": 13437,
"s": 13304,
"text": "protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes."
},
{
"code": null,
"e": 13537,
"s": 13437,
"text": "protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs."
},
{
"code": null,
"e": 13637,
"s": 13537,
"text": "protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs."
},
{
"code": null,
"e": 13750,
"s": 13637,
"text": "protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary."
},
{
"code": null,
"e": 13863,
"s": 13750,
"text": "protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary."
},
{
"code": null,
"e": 14065,
"s": 13863,
"text": "protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to \"mix in\"."
},
{
"code": null,
"e": 14267,
"s": 14065,
"text": "protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to \"mix in\"."
},
{
"code": null,
"e": 14404,
"s": 14267,
"text": "protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property."
},
{
"code": null,
"e": 14541,
"s": 14404,
"text": "protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property."
},
{
"code": null,
"e": 14852,
"s": 14541,
"text": "protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly)."
},
{
"code": null,
"e": 15163,
"s": 14852,
"text": "protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly)."
},
{
"code": null,
"e": 15332,
"s": 15163,
"text": "protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers."
},
{
"code": null,
"e": 15501,
"s": 15332,
"text": "protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers."
},
{
"code": null,
"e": 15641,
"s": 15501,
"text": "protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process."
},
{
"code": null,
"e": 15781,
"s": 15641,
"text": "protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process."
},
{
"code": null,
"e": 15885,
"s": 15781,
"text": "protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.\n"
},
{
"code": null,
"e": 15989,
"s": 15885,
"text": "protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.\n"
},
{
"code": null,
"e": 16132,
"s": 15989,
"text": "protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching."
},
{
"code": null,
"e": 16275,
"s": 16132,
"text": "protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching."
},
{
"code": null,
"e": 16403,
"s": 16275,
"text": "protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed."
},
{
"code": null,
"e": 16531,
"s": 16403,
"text": "protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed."
},
{
"code": null,
"e": 16733,
"s": 16531,
"text": "protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)."
},
{
"code": null,
"e": 16935,
"s": 16733,
"text": "protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)."
},
{
"code": null,
"e": 17009,
"s": 16935,
"text": "protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR "
},
{
"code": null,
"e": 17083,
"s": 17009,
"text": "protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR "
},
{
"code": null,
"e": 17196,
"s": 17083,
"text": "protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances."
},
{
"code": null,
"e": 17309,
"s": 17196,
"text": "protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances."
},
{
"code": null,
"e": 17371,
"s": 17309,
"text": "protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER "
},
{
"code": null,
"e": 17433,
"s": 17371,
"text": "protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER "
},
{
"code": null,
"e": 17615,
"s": 17433,
"text": "Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory."
},
{
"code": null,
"e": 17729,
"s": 17615,
"text": "Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators."
},
{
"code": null,
"e": 17913,
"s": 17729,
"text": "Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators, and uses given providers for accessing serializers and deserializers."
},
{
"code": null,
"e": 17962,
"s": 17913,
"text": "Copy-constructor, mostly used to support copy()."
},
{
"code": null,
"e": 18018,
"s": 17962,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 18035,
"s": 18018,
"text": "java.lang.Object"
},
{
"code": null,
"e": 18052,
"s": 18035,
"text": "java.lang.Object"
},
{
"code": null,
"e": 18148,
"s": 18052,
"text": "Create the following java program using any editor of your choice in say C:/> Jackson_WORKSPACE"
},
{
"code": null,
"e": 18173,
"s": 18148,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 19469,
"s": 18173,
"text": "import java.io.IOException;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n \n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"name\\\":\\\"Mahesh\\\", \\\"age\\\":21}\";\n \n //map json to student\n try{\n Student student = mapper.readValue(jsonString, Student.class);\n \n System.out.println(student);\n \n jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);\n \n System.out.println(jsonString);\n }\n catch (JsonParseException e) { e.printStackTrace();}\n catch (JsonMappingException e) { e.printStackTrace(); }\n catch (IOException e) { e.printStackTrace(); }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\n}"
},
{
"code": null,
"e": 19487,
"s": 19469,
"text": "Verify the result"
},
{
"code": null,
"e": 19540,
"s": 19487,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 19586,
"s": 19540,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 19631,
"s": 19586,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 19671,
"s": 19631,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 19689,
"s": 19671,
"text": "Verify the Output"
},
{
"code": null,
"e": 19762,
"s": 19689,
"text": "Student [ name: Mahesh, age: 21 ]\n{\n \"name\" : \"Mahesh\",\n \"age\" : 21\n}\n"
},
{
"code": null,
"e": 19996,
"s": 19762,
"text": "let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object."
},
{
"code": null,
"e": 20067,
"s": 19996,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 20092,
"s": 20067,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 21833,
"s": 20092,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport com.fasterxml.jackson.core.JsonGenerationException;\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n tester.writeJSON(student);\n\n Student student1 = tester.readJSON();\n System.out.println(student1);\n\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{\n ObjectMapper mapper = new ObjectMapper();\t\n mapper.writeValue(new File(\"student.json\"), student);\n }\n\n private Student readJSON() throws JsonParseException, JsonMappingException, IOException{\n ObjectMapper mapper = new ObjectMapper();\n Student student = mapper.readValue(new File(\"student.json\"), Student.class);\n return student;\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}"
},
{
"code": null,
"e": 21851,
"s": 21833,
"text": "Verify the result"
},
{
"code": null,
"e": 21904,
"s": 21851,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 21950,
"s": 21904,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 21995,
"s": 21950,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 22035,
"s": 21995,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 22053,
"s": 22035,
"text": "Verify the Output"
},
{
"code": null,
"e": 22088,
"s": 22053,
"text": "Student [ name: Mahesh, age: 10 ]\n"
},
{
"code": null,
"e": 22236,
"s": 22088,
"text": "Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.\n"
},
{
"code": null,
"e": 22347,
"s": 22236,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 22458,
"s": 22347,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 22519,
"s": 22458,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 22580,
"s": 22519,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 22719,
"s": 22580,
"text": "ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML."
},
{
"code": null,
"e": 22869,
"s": 22719,
"text": "Simple data binding refers to mapping of JSON to JAVA Core data types. Following table illustrates the relationship between JSON types vs Java Types."
},
{
"code": null,
"e": 22975,
"s": 22869,
"text": "Let's see simple data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa."
},
{
"code": null,
"e": 23046,
"s": 22975,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 23071,
"s": 23046,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 25337,
"s": 23071,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n ObjectMapper mapper = new ObjectMapper();\n\n Map<String,Object> studentDataMap = new HashMap<String,Object>(); \n int[] marks = {1,2,3};\n\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n // JAVA Object\n studentDataMap.put(\"student\", student);\n // JAVA String\n studentDataMap.put(\"name\", \"Mahesh Kumar\"); \t\t\n // JAVA Boolean\n studentDataMap.put(\"verified\", Boolean.FALSE);\n // Array\n studentDataMap.put(\"marks\", marks);\n\n mapper.writeValue(new File(\"student.json\"), studentDataMap);\n //result student.json\n\t\t\t//{ \n // \"student\":{\"name\":\"Mahesh\",\"age\":10},\n // \"marks\":[1,2,3],\n // \"verified\":false,\n // \"name\":\"Mahesh Kumar\"\n //}\n studentDataMap = mapper.readValue(new File(\"student.json\"), Map.class);\n\n System.out.println(studentDataMap.get(\"student\"));\n System.out.println(studentDataMap.get(\"name\"));\n System.out.println(studentDataMap.get(\"verified\"));\n System.out.println(studentDataMap.get(\"marks\"));\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}"
},
{
"code": null,
"e": 25355,
"s": 25337,
"text": "Verify the result"
},
{
"code": null,
"e": 25408,
"s": 25355,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 25454,
"s": 25408,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 25499,
"s": 25454,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 25539,
"s": 25499,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 25557,
"s": 25539,
"text": "Verify the Output"
},
{
"code": null,
"e": 25609,
"s": 25557,
"text": "{name=Mahesh, age=10}\nMahesh Kumar\nfalse\n[1, 2, 3]\n"
},
{
"code": null,
"e": 25673,
"s": 25609,
"text": "Full data binding refers to mapping of JSON to any JAVA Object."
},
{
"code": null,
"e": 25955,
"s": 25673,
"text": "//Create an ObjectMapper instance\nObjectMapper mapper = new ObjectMapper();\t\n//map JSON content to Student object\nStudent student = mapper.readValue(new File(\"student.json\"), Student.class);\n//map Student object to JSON content\nmapper.writeValue(new File(\"student.json\"), student);"
},
{
"code": null,
"e": 26056,
"s": 25955,
"text": "Let's see simple data binding in action. Here we'll map JAVA Object directly to JSON and vice versa."
},
{
"code": null,
"e": 26127,
"s": 26056,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 26152,
"s": 26127,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 27893,
"s": 26152,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport com.fasterxml.jackson.core.JsonGenerationException;\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n tester.writeJSON(student);\n\n Student student1 = tester.readJSON();\n System.out.println(student1);\n\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{\n ObjectMapper mapper = new ObjectMapper();\t\n mapper.writeValue(new File(\"student.json\"), student);\n }\n\n private Student readJSON() throws JsonParseException, JsonMappingException, IOException{\n ObjectMapper mapper = new ObjectMapper();\n Student student = mapper.readValue(new File(\"student.json\"), Student.class);\n return student;\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}"
},
{
"code": null,
"e": 27911,
"s": 27893,
"text": "Verify the result"
},
{
"code": null,
"e": 27964,
"s": 27911,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 28010,
"s": 27964,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 28055,
"s": 28010,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 28095,
"s": 28055,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 28113,
"s": 28095,
"text": "Verify the Output"
},
{
"code": null,
"e": 28148,
"s": 28113,
"text": "Student [ name: Mahesh, age: 10 ]\n"
},
{
"code": null,
"e": 28333,
"s": 28148,
"text": "In simple data binding, we've used Map class which use String as key and Object as a value object. Instead we can have concrete java object and type cast it to be used in JSON binding."
},
{
"code": null,
"e": 28423,
"s": 28333,
"text": "Consider the following example with a class UserData, a class to hold user specific data."
},
{
"code": null,
"e": 28494,
"s": 28423,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 28519,
"s": 28494,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 31894,
"s": 28519,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n ObjectMapper mapper = new ObjectMapper();\n\n Map<String, UserData> userDataMap = new HashMap<String, UserData>();\n UserData studentData = new UserData(); \n int[] marks = {1,2,3};\n\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n // JAVA Object\n studentData.setStudent(student);\n // JAVA String\n studentData.setName(\"Mahesh Kumar\");\n // JAVA Boolean\n studentData.setVerified(Boolean.FALSE);\n // Array\n studentData.setMarks(marks);\n TypeReference ref = new TypeReference<Map<String,UserData>>() { };\n userDataMap.put(\"studentData1\", studentData);\n mapper.writeValue(new File(\"student.json\"), userDataMap);\n //{\n // \"studentData1\":\n //\t {\n //\t\t\"student\":\n //\t\t{\n //\t\t\t\"name\":\"Mahesh\",\n //\t\t\t\"age\":10\n // },\n // \"name\":\"Mahesh Kumar\",\n // \"verified\":false,\n // \"marks\":[1,2,3]\n // }\n //}\n userDataMap = mapper.readValue(new File(\"student.json\"), ref);\n\n System.out.println(userDataMap.get(\"studentData1\").getStudent());\n System.out.println(userDataMap.get(\"studentData1\").getName());\n System.out.println(userDataMap.get(\"studentData1\").getVerified());\n System.out.println(Arrays.toString(userDataMap.get(\"studentData1\").getMarks()));\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}\n\nclass UserData {\n private Student student;\n private String name;\n private Boolean verified;\n private int[] marks;\n\n public UserData(){}\n\n public Student getStudent() {\n return student;\n }\n public void setStudent(Student student) {\n this.student = student;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public Boolean getVerified() {\n return verified;\n }\n public void setVerified(Boolean verified) {\n this.verified = verified;\n }\n public int[] getMarks() {\n return marks;\n }\n public void setMarks(int[] marks) {\n this.marks = marks;\n }\t\t\n}"
},
{
"code": null,
"e": 31912,
"s": 31894,
"text": "Verify the result"
},
{
"code": null,
"e": 31965,
"s": 31912,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 32011,
"s": 31965,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 32056,
"s": 32011,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 32096,
"s": 32056,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 32114,
"s": 32096,
"text": "Verify the Output"
},
{
"code": null,
"e": 32178,
"s": 32114,
"text": "Student [ name: Mahesh, age: 10 ]\nMahesh Kumar\nfalse\n[1, 2, 3]\n"
},
{
"code": null,
"e": 32364,
"s": 32178,
"text": "Tree Model prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML."
},
{
"code": null,
"e": 32582,
"s": 32364,
"text": "ObjectMapper provides a pointer to root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String."
},
{
"code": null,
"e": 32837,
"s": 32582,
"text": "//Create an ObjectMapper instance\nObjectMapper mapper = new ObjectMapper();\t\nString jsonString = \"{\\\"name\\\":\\\"Mahesh Kumar\\\", \\\"age\\\":21,\\\"verified\\\":false,\\\"marks\\\": [100,90,85]}\";\n//create tree from JSON\nJsonNode rootNode = mapper.readTree(jsonString);"
},
{
"code": null,
"e": 33012,
"s": 32837,
"text": "Get each node using relative path to the root node while traversing tree and process the data. Consider the following code snippet traversing the tree provided the root node."
},
{
"code": null,
"e": 33206,
"s": 33012,
"text": "JsonNode nameNode = rootNode.path(\"name\");\nSystem.out.println(\"Name: \"+ nameNode.textValue());\n \nJsonNode marksNode = rootNode.path(\"marks\");\nIterator<JsonNode> iterator = marksNode.elements();"
},
{
"code": null,
"e": 33277,
"s": 33206,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 33302,
"s": 33277,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 34787,
"s": 33302,
"text": "import java.io.IOException;\nimport java.util.Iterator;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n\n try {\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"name\\\":\\\"Mahesh Kumar\\\", \\\"age\\\":21,\\\"verified\\\":false,\\\"marks\\\": [100,90,85]}\";\n JsonNode rootNode = mapper.readTree(jsonString);\n\n JsonNode nameNode = rootNode.path(\"name\");\n System.out.println(\"Name: \"+ nameNode.textValue());\n\n JsonNode ageNode = rootNode.path(\"age\");\n System.out.println(\"Age: \" + ageNode.intValue());\n\n JsonNode verifiedNode = rootNode.path(\"verified\");\n System.out.println(\"Verified: \" + (verifiedNode.booleanValue() ? \"Yes\":\"No\"));\n\n JsonNode marksNode = rootNode.path(\"marks\");\n Iterator<JsonNode> iterator = marksNode.elements();\n System.out.print(\"Marks: [ \");\n\n while (iterator.hasNext()) {\n JsonNode marks = iterator.next();\n System.out.print(marks.intValue() + \" \"); \n }\n\n System.out.println(\"]\");\n }\n catch (JsonParseException e) { e.printStackTrace(); }\n catch (JsonMappingException e) { e.printStackTrace(); }\n catch (IOException e) { e.printStackTrace(); }\n }\n}"
},
{
"code": null,
"e": 34805,
"s": 34787,
"text": "Verify the result"
},
{
"code": null,
"e": 34858,
"s": 34805,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 34904,
"s": 34858,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 34949,
"s": 34904,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 34989,
"s": 34949,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 35007,
"s": 34989,
"text": "Verify the Output"
},
{
"code": null,
"e": 35069,
"s": 35007,
"text": "Name: Mahesh Kumar\nAge: 21\nVerified: No\nMarks: [ 100 90 85 ]\n"
},
{
"code": null,
"e": 35165,
"s": 35069,
"text": "In this example, we've created a Tree using JsonNode and write it to a json file and read back."
},
{
"code": null,
"e": 35236,
"s": 35165,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 35261,
"s": 35236,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 36746,
"s": 35261,
"text": "import java.io.IOException;\nimport java.util.Iterator;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n\n try {\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"name\\\":\\\"Mahesh Kumar\\\", \\\"age\\\":21,\\\"verified\\\":false,\\\"marks\\\": [100,90,85]}\";\n JsonNode rootNode = mapper.readTree(jsonString);\n\n JsonNode nameNode = rootNode.path(\"name\");\n System.out.println(\"Name: \"+ nameNode.textValue());\n\n JsonNode ageNode = rootNode.path(\"age\");\n System.out.println(\"Age: \" + ageNode.intValue());\n\n JsonNode verifiedNode = rootNode.path(\"verified\");\n System.out.println(\"Verified: \" + (verifiedNode.booleanValue() ? \"Yes\":\"No\"));\n\n JsonNode marksNode = rootNode.path(\"marks\");\n Iterator<JsonNode> iterator = marksNode.elements();\n System.out.print(\"Marks: [ \");\n\n while (iterator.hasNext()) {\n JsonNode marks = iterator.next();\n System.out.print(marks.intValue() + \" \"); \n }\n\n System.out.println(\"]\");\n }\n catch (JsonParseException e) { e.printStackTrace(); }\n catch (JsonMappingException e) { e.printStackTrace(); }\n catch (IOException e) { e.printStackTrace(); }\n }\n}"
},
{
"code": null,
"e": 36764,
"s": 36746,
"text": "Verify the result"
},
{
"code": null,
"e": 36817,
"s": 36764,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 36863,
"s": 36817,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 36908,
"s": 36863,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 36948,
"s": 36908,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 36966,
"s": 36948,
"text": "Verify the Output"
},
{
"code": null,
"e": 37028,
"s": 36966,
"text": "Name: Mahesh Kumar\nAge: 21\nVerified: No\nMarks: [ 100 90 85 ]\n"
},
{
"code": null,
"e": 37169,
"s": 37028,
"text": "In this example, we've created a Tree using JsonNode and write it to a json file and read back tree and then convert it as a Student object."
},
{
"code": null,
"e": 37240,
"s": 37169,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 37265,
"s": 37240,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 39585,
"s": 37265,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n ObjectMapper mapper = new ObjectMapper();\n\n JsonNode rootNode = mapper.createObjectNode();\n JsonNode marksNode = mapper.createArrayNode();\n ((ArrayNode)marksNode).add(100);\n ((ArrayNode)marksNode).add(90);\n ((ArrayNode)marksNode).add(85);\n ((ObjectNode) rootNode).put(\"name\", \"Mahesh Kumar\");\n ((ObjectNode) rootNode).put(\"age\", 21);\n ((ObjectNode) rootNode).put(\"verified\", false);\n ((ObjectNode) rootNode).put(\"marks\",marksNode);\n\n mapper.writeValue(new File(\"student.json\"), rootNode);\n\n rootNode = mapper.readTree(new File(\"student.json\"));\n\n Student student = mapper.treeToValue(rootNode, Student.class);\n\n System.out.println(\"Name: \"+ student.getName());\n System.out.println(\"Age: \" + student.getAge());\n System.out.println(\"Verified: \" + (student.isVerified() ? \"Yes\":\"No\"));\n System.out.println(\"Marks: \"+Arrays.toString(student.getMarks()));\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\nclass Student {\n String name;\n int age;\n boolean verified;\n int[] marks;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public boolean isVerified() {\n return verified;\n }\n public void setVerified(boolean verified) {\n this.verified = verified;\n }\n public int[] getMarks() {\n return marks;\n }\n public void setMarks(int[] marks) {\n this.marks = marks;\n }\n}"
},
{
"code": null,
"e": 39603,
"s": 39585,
"text": "Verify the result"
},
{
"code": null,
"e": 39656,
"s": 39603,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 39702,
"s": 39656,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 39747,
"s": 39702,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 39787,
"s": 39747,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 39805,
"s": 39787,
"text": "Verify the Output"
},
{
"code": null,
"e": 39867,
"s": 39805,
"text": "Name: Mahesh Kumar\nAge: 21\nVerified: No\nMarks: [ 100 90 85 ]\n"
},
{
"code": null,
"e": 40144,
"s": 39867,
"text": "Streaming API reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML."
},
{
"code": null,
"e": 40385,
"s": 40144,
"text": "In this Article, we'll showcase using Jackson streaming APIs to read and write JSON data. Streaming API works with concept of token and every details of Json is to be handle carefuly. Following are two class which we'll use in the examples:"
},
{
"code": null,
"e": 40423,
"s": 40385,
"text": "JsonGenerator - Write to JSON String."
},
{
"code": null,
"e": 40461,
"s": 40423,
"text": "JsonGenerator - Write to JSON String."
},
{
"code": null,
"e": 40493,
"s": 40461,
"text": "JsonParser - Parse JSON String."
},
{
"code": null,
"e": 40525,
"s": 40493,
"text": "JsonParser - Parse JSON String."
},
{
"code": null,
"e": 40699,
"s": 40525,
"text": "Using JsonGenerator is pretty simple. First create the JsonGenerator using JsonFactory.createJsonGenerator() method and use it's write***() methods to write each json value."
},
{
"code": null,
"e": 40975,
"s": 40699,
"text": "JsonFactory jsonFactory = new JsonFactory();\nJsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(\n \"student.json\"), JsonEncoding.UTF8);\n// {\njsonGenerator.writeStartObject();\n// \"name\" : \"Mahesh Kumar\"\njsonGenerator.writeStringField(\"name\", \"Mahesh Kumar\"); "
},
{
"code": null,
"e": 41081,
"s": 40975,
"text": "Let's see JsonGenerator in action. Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 41106,
"s": 41081,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 43226,
"s": 41106,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonEncoding;\nimport com.fasterxml.jackson.core.JsonFactory;\nimport com.fasterxml.jackson.core.JsonGenerator;\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n\n try { \n JsonFactory jsonFactory = new JsonFactory();\n JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(\"student.json\"), JsonEncoding.UTF8);\n\n jsonGenerator.writeStartObject();\n\n // \"name\" : \"Mahesh Kumar\"\n jsonGenerator.writeStringField(\"name\", \"Mahesh Kumar\"); \n\n // \"age\" : 21\n jsonGenerator.writeNumberField(\"age\", 21);\n\n // \"verified\" : false\n jsonGenerator.writeBooleanField(\"verified\", false);\n\n // \"marks\" : [100, 90, 85]\n jsonGenerator.writeFieldName(\"marks\"); \n\n // [\n jsonGenerator.writeStartArray(); \n // 100, 90, 85\n jsonGenerator.writeNumber(100); \n jsonGenerator.writeNumber(90); \n jsonGenerator.writeNumber(85); \n // ]\n\n jsonGenerator.writeEndArray(); \n\n jsonGenerator.writeEndObject(); \n jsonGenerator.close(); \n\n //result student.json\n //{ \n // \"name\":\"Mahesh Kumar\",\n // \"age\":21,\n // \"verified\":false,\n // \"marks\":[100,90,85]\n //}\n\n ObjectMapper mapper = new ObjectMapper();\n Map<String,Object> dataMap = mapper.readValue(new File(\"student.json\"), Map.class);\n\n System.out.println(dataMap.get(\"name\"));\n System.out.println(dataMap.get(\"age\"));\n System.out.println(dataMap.get(\"verified\"));\n System.out.println(dataMap.get(\"marks\"));\n } \n catch (JsonParseException e) { e.printStackTrace(); } \n catch (JsonMappingException e) { e.printStackTrace(); } \n catch (IOException e) { e.printStackTrace(); }\n }\n}"
},
{
"code": null,
"e": 43244,
"s": 43226,
"text": "Verify the result"
},
{
"code": null,
"e": 43297,
"s": 43244,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 43343,
"s": 43297,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 43388,
"s": 43343,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 43428,
"s": 43388,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 43446,
"s": 43428,
"text": "Verify the Output"
},
{
"code": null,
"e": 43483,
"s": 43446,
"text": "Mahesh Kumar\n21\nfalse\n[100, 90, 85]\n"
},
{
"code": null,
"e": 43705,
"s": 43483,
"text": "Using JsonParser is again pretty simple. First create the JsonParser using JsonFactory.createJsonParser() method and use it's nextToken() methods to read each json string as token. Check each token and process accordingly"
},
{
"code": null,
"e": 44124,
"s": 43705,
"text": "JsonFactory jasonFactory = new JsonFactory();\nJsonParser jsonParser = jasonFactory.createJsonParser(new File(\"student.json\"));\nwhile (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n //get the current token\n String fieldname = jsonParser.getCurrentName();\n if (\"name\".equals(fieldname)) {\n //move to next token\n jsonParser.nextToken();\n System.out.println(jsonParser.getText()); \t \n }\n}"
},
{
"code": null,
"e": 44227,
"s": 44124,
"text": "Let's see JsonParser in action. Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 44252,
"s": 44227,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 47129,
"s": 44252,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonEncoding;\nimport com.fasterxml.jackson.core.JsonFactory;\nimport com.fasterxml.jackson.core.JsonGenerator;\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try { \t\n JsonFactory jsonFactory = new JsonFactory();\n\n JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(\n \"student.json\"), JsonEncoding.UTF8);\n jsonGenerator.writeStartObject();\n jsonGenerator.writeStringField(\"name\", \"Mahesh Kumar\"); \n jsonGenerator.writeNumberField(\"age\", 21);\n jsonGenerator.writeBooleanField(\"verified\", false); \n jsonGenerator.writeFieldName(\"marks\"); \n jsonGenerator.writeStartArray(); // [\n jsonGenerator.writeNumber(100); \n jsonGenerator.writeNumber(90); \n jsonGenerator.writeNumber(85); \n jsonGenerator.writeEndArray(); \n jsonGenerator.writeEndObject(); \n jsonGenerator.close(); \t \n\n //result student.json\n //{ \n // \"name\":\"Mahesh Kumar\",\n // \"age\":21,\n // \"verified\":false,\n // \"marks\":[100,90,85]\n //}\n\n JsonParser jsonParser = jsonFactory.createParser(new File(\"student.json\"));\n while (jsonParser.nextToken() != JsonToken.END_OBJECT) {\n //get the current token\n String fieldname = jsonParser.getCurrentName();\n if (\"name\".equals(fieldname)) {\n //move to next token\n jsonParser.nextToken();\n System.out.println(jsonParser.getText()); \t \n }\n if(\"age\".equals(fieldname)){\n //move to next token\n jsonParser.nextToken();\n System.out.println(jsonParser.getNumberValue()); \t \n }\n if(\"verified\".equals(fieldname)){\n //move to next token\n jsonParser.nextToken();\n System.out.println(jsonParser.getBooleanValue()); \t \n }\n if(\"marks\".equals(fieldname)){\n //move to [ \n jsonParser.nextToken();\n // loop till token equal to \"]\"\n while (jsonParser.nextToken() != JsonToken.END_ARRAY) {\n System.out.println(jsonParser.getNumberValue()); \n }\n }\n }\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 47147,
"s": 47129,
"text": "Verify the result"
},
{
"code": null,
"e": 47200,
"s": 47147,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 47246,
"s": 47200,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 47291,
"s": 47246,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 47331,
"s": 47291,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 47349,
"s": 47331,
"text": "Verify the Output"
},
{
"code": null,
"e": 47386,
"s": 47349,
"text": "Mahesh Kumar\n21\nfalse\n[100, 90, 85]\n"
},
{
"code": null,
"e": 47533,
"s": 47386,
"text": "JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance."
},
{
"code": null,
"e": 47605,
"s": 47533,
"text": "Following is the declaration for org.codehaus.jackson.JsonParser class:"
},
{
"code": null,
"e": 47694,
"s": 47605,
"text": "public abstract class JsonParser\n extends Object\n implements Closeable, Versioned"
},
{
"code": null,
"e": 47859,
"s": 47694,
"text": "protected PrettyPrinter _cfgPrettyPrinter - Object that handles pretty-printing (usually additional white space to make results more human-readable) during output."
},
{
"code": null,
"e": 48024,
"s": 47859,
"text": "protected PrettyPrinter _cfgPrettyPrinter - Object that handles pretty-printing (usually additional white space to make results more human-readable) during output."
},
{
"code": null,
"e": 48103,
"s": 48024,
"text": "protected JsonToken _currToken - Last token retrieved via nextToken(), if any."
},
{
"code": null,
"e": 48182,
"s": 48103,
"text": "protected JsonToken _currToken - Last token retrieved via nextToken(), if any."
},
{
"code": null,
"e": 48287,
"s": 48182,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 48392,
"s": 48287,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 48531,
"s": 48392,
"text": "protected JsonToken _lastClearedToken - Last cleared token, if any: that is, value that was in effect when clearCurrentToken() was called."
},
{
"code": null,
"e": 48670,
"s": 48531,
"text": "protected JsonToken _lastClearedToken - Last cleared token, if any: that is, value that was in effect when clearCurrentToken() was called."
},
{
"code": null,
"e": 48726,
"s": 48670,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 48743,
"s": 48726,
"text": "java.lang.Object"
},
{
"code": null,
"e": 48760,
"s": 48743,
"text": "java.lang.Object"
},
{
"code": null,
"e": 48907,
"s": 48760,
"text": "JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance."
},
{
"code": null,
"e": 48985,
"s": 48907,
"text": "Following is the declaration for com.fasterxml.jackson.core.JsonParser class:"
},
{
"code": null,
"e": 49074,
"s": 48985,
"text": "public abstract class JsonParser\n extends Object\n implements Closeable, Versioned"
},
{
"code": null,
"e": 49179,
"s": 49074,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 49284,
"s": 49179,
"text": "protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled."
},
{
"code": null,
"e": 49340,
"s": 49284,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 49357,
"s": 49340,
"text": "java.lang.Object"
},
{
"code": null,
"e": 49374,
"s": 49357,
"text": "java.lang.Object"
},
{
"code": null,
"e": 49381,
"s": 49374,
"text": " Print"
},
{
"code": null,
"e": 49392,
"s": 49381,
"text": " Add Notes"
}
]
|
abs() in Python | The abs() function in python represents the absolute value of a numeric input. The absolute value is concerned with the value or magnitude of a number instead of the sign attached to the number. It is even more useful for complex numbers where the calculation of magnitude involves many steps.
The syntax of the function is −
abs(num)
where num can be integer,floating number or a complex number.
In the below example we take all the above types of numbers and calculate their magnitude.
n = -112
print('Absolute value of a integer', abs(n))
f = -39.222
print('Absolute value of a float: ', abs(f))
c = (11 - 21j)
print('Absolute value or Magnitude of a complex number:', abs(c))
Running the above code gives us the following result:
('Absolute value of a integer', 112)
('Absolute value of a float: ', 39.222)
('Absolute value or Magnitude of a complex number:', 23.706539182259394) | [
{
"code": null,
"e": 1356,
"s": 1062,
"text": "The abs() function in python represents the absolute value of a numeric input. The absolute value is concerned with the value or magnitude of a number instead of the sign attached to the number. It is even more useful for complex numbers where the calculation of magnitude involves many steps."
},
{
"code": null,
"e": 1388,
"s": 1356,
"text": "The syntax of the function is −"
},
{
"code": null,
"e": 1397,
"s": 1388,
"text": "abs(num)"
},
{
"code": null,
"e": 1459,
"s": 1397,
"text": "where num can be integer,floating number or a complex number."
},
{
"code": null,
"e": 1550,
"s": 1459,
"text": "In the below example we take all the above types of numbers and calculate their magnitude."
},
{
"code": null,
"e": 1744,
"s": 1550,
"text": "n = -112\nprint('Absolute value of a integer', abs(n))\n\nf = -39.222\nprint('Absolute value of a float: ', abs(f))\n\nc = (11 - 21j)\nprint('Absolute value or Magnitude of a complex number:', abs(c))"
},
{
"code": null,
"e": 1798,
"s": 1744,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 1948,
"s": 1798,
"text": "('Absolute value of a integer', 112)\n('Absolute value of a float: ', 39.222)\n('Absolute value or Magnitude of a complex number:', 23.706539182259394)"
}
]
|
Count ways to reach the n’th stair | There are n stairs. One person will go to 1'st to the n'th stair. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the n'th stairs.
Let us consider one can cross a maximum two stairs in each step. So we can find recursive relations to solve this problem. One can move to n'th stair, either from (n-1)'th stair or from (n-2)'th stair. So ways(n) = ways(n-1) + ways(n-2).
Input:
The number of stairs, say 10 the maximum number of stairs that can be jumped in one step, say 2
Output:
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89
stairClimpWays(stair, max)
Input − number of stairs, maximum stair jump in a single step.
Output − Number of possible ways to reach.
Begin
define array count of size same as stair number
count[0] := 1
count[0] := 1
for i := 2 to stair -1, do
count[i] := 0
for j = 1 to i and j <= max; do
count[i] := count[i] + count[i - j]
done
done
return count[stair - 1]
End
#include<iostream>
using namespace std;
int stairClimbWays(int stair, int max) {
int count[stair]; //fill the result stair using bottom up manner
count[0] = 1; //when there are 0 or 1 stair, 1 way to climb
count[1] = 1;
for (int i=2; i<stair; i++) { //for stair 2 to higher
count[i] = 0;
for(int j=1; j<=max && j<=i; j++)
count[i] += count[i-j];
}
return count[stair-1];
}
int countWays(int stair, int max) { //person can climb 1,2,...max stairs at a time
return stairClimbWays(stair+1, max);
}
int main () {
int stair, max;
cout << "Enter number of stairs: "; cin >> stair;
cout << "Enter max stair a person can climb: "; cin >> max;
cout << "Number of ways to reach: " << countWays(stair, max);
}
Enter number of stairs: 10
Enter max stair a person can climb: 2
Number of ways to reach: 89 | [
{
"code": null,
"e": 1275,
"s": 1062,
"text": "There are n stairs. One person will go to 1'st to the n'th stair. Maximum how many stairs he/she can cross in one step is also given. With this information, we have to find possible ways to go to the n'th stairs."
},
{
"code": null,
"e": 1513,
"s": 1275,
"text": "Let us consider one can cross a maximum two stairs in each step. So we can find recursive relations to solve this problem. One can move to n'th stair, either from (n-1)'th stair or from (n-2)'th stair. So ways(n) = ways(n-1) + ways(n-2)."
},
{
"code": null,
"e": 1717,
"s": 1513,
"text": "Input:\nThe number of stairs, say 10 the maximum number of stairs that can be jumped in one step, say 2\nOutput:\nEnter number of stairs: 10\nEnter max stair a person can climb: 2\nNumber of ways to reach: 89"
},
{
"code": null,
"e": 1744,
"s": 1717,
"text": "stairClimpWays(stair, max)"
},
{
"code": null,
"e": 1807,
"s": 1744,
"text": "Input − number of stairs, maximum stair jump in a single step."
},
{
"code": null,
"e": 1850,
"s": 1807,
"text": "Output − Number of possible ways to reach."
},
{
"code": null,
"e": 2125,
"s": 1850,
"text": "Begin\n define array count of size same as stair number\n count[0] := 1\n count[0] := 1\n\n for i := 2 to stair -1, do\n count[i] := 0\n for j = 1 to i and j <= max; do\n count[i] := count[i] + count[i - j]\n done\n done\n return count[stair - 1]\nEnd"
},
{
"code": null,
"e": 2900,
"s": 2125,
"text": "#include<iostream>\nusing namespace std;\n\nint stairClimbWays(int stair, int max) {\n int count[stair]; //fill the result stair using bottom up manner\n count[0] = 1; //when there are 0 or 1 stair, 1 way to climb\n count[1] = 1;\n \n for (int i=2; i<stair; i++) { //for stair 2 to higher\n count[i] = 0;\n for(int j=1; j<=max && j<=i; j++)\n count[i] += count[i-j];\n }\n return count[stair-1];\n}\n\nint countWays(int stair, int max) { //person can climb 1,2,...max stairs at a time\n return stairClimbWays(stair+1, max);\n}\n\nint main () {\n int stair, max;\n cout << \"Enter number of stairs: \"; cin >> stair;\n cout << \"Enter max stair a person can climb: \"; cin >> max;\n cout << \"Number of ways to reach: \" << countWays(stair, max);\n}"
},
{
"code": null,
"e": 2993,
"s": 2900,
"text": "Enter number of stairs: 10\nEnter max stair a person can climb: 2\nNumber of ways to reach: 89"
}
]
|
Counting occurrences of vowel, consonants - JavaScript | We are required to write a JavaScript function that takes in a string which contains English alphabet, for example −
const str = 'This is a sample string, will be used to collect some data';
The function should return an object containing the count of vowels and consonants in the string i.e. the output should be −
{ vowels: 17, consonants: 29 }
Following is the code −
const str = 'This is a sample string, will be used to collect some data';
const countAlpha = str => {
return str.split('').reduce((acc, val) => {
const legend = 'aeiou';
let { vowels, consonants } = acc;
if(val.toLowerCase() === val.toUpperCase()){
return acc;
};
if(legend.includes(val.toLowerCase())){
vowels++;
}else{
consonants++;
};
return { vowels, consonants };
}, {
vowels: 0,
consonants: 0
});
};
console.log(countAlpha(str));
This will produce the following output in console −
{ vowels: 17, consonants: 29 } | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a string which contains English alphabet, for example −"
},
{
"code": null,
"e": 1253,
"s": 1179,
"text": "const str = 'This is a sample string, will be used to collect some data';"
},
{
"code": null,
"e": 1378,
"s": 1253,
"text": "The function should return an object containing the count of vowels and consonants in the string i.e. the output should be −"
},
{
"code": null,
"e": 1409,
"s": 1378,
"text": "{ vowels: 17, consonants: 29 }"
},
{
"code": null,
"e": 1433,
"s": 1409,
"text": "Following is the code −"
},
{
"code": null,
"e": 1965,
"s": 1433,
"text": "const str = 'This is a sample string, will be used to collect some data';\nconst countAlpha = str => {\n return str.split('').reduce((acc, val) => {\n const legend = 'aeiou';\n let { vowels, consonants } = acc;\n if(val.toLowerCase() === val.toUpperCase()){\n return acc;\n };\n if(legend.includes(val.toLowerCase())){\n vowels++;\n }else{\n consonants++;\n };\n return { vowels, consonants };\n }, {\n vowels: 0,\n consonants: 0\n });\n};\nconsole.log(countAlpha(str));"
},
{
"code": null,
"e": 2017,
"s": 1965,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 2048,
"s": 2017,
"text": "{ vowels: 17, consonants: 29 }"
}
]
|
Maximum number of fixed points using atmost 1 swap - GeeksforGeeks | 10 Feb, 2022
Given a permutation of N elements (Elements are in range 0 to N-1). A fixed point is an index at which the value is same as the index (That is, a[i]=i). You are allowed to make atmost 1 swap. Find the maximum number of fixed points that you can get.Examples:
Input : N = 5
arr[] = {0, 1, 3, 4, 2}
Output : 3
2 and 3 can be swapped to get:
0 1 2 4 3
which has 3 fixed points.
Input : N = 5
a[] = {0, 1, 2, 4, 3}
Output : 5
Since we are allowed to make only 1 swap, the number of fixed points can be increased by atmost 2.Let’s have an array pos which keeps the position of each element in the input array. Now, we traverse the array and have the following cases:
If, a[i] = i. We can simply increment the count and move on.
If, pos[i] = a[i] which means that swapping the 2 terms would make i and a[i] fixed points, hence increasing the count by 2. Keep in mind that swap can be done atmost once.
At the end of the traversal, if we haven’t made any swap, it means that our swap was not able to increase count by 2, so now if there are at least 2 elements which are not fixed points, we can make a swap to increase count by 1, i.e make one of those points a fixed point.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find maximum number of// fixed points using atmost 1 swap #include <bits/stdc++.h>using namespace std; // Function to find maximum number of// fixed points using atmost 1 swapint maximumFixedPoints(int a[], int n){ int i, pos[n], count = 0, swapped = 0; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Codeint main(){ int a[] = { 0, 1, 3, 4, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << maximumFixedPoints(a, n); return 0;}
// Java program to find maximum number of// fixed points using atmost 1 swapimport java.io.*; class GFG { // Function to find maximum number of// fixed points using atmost 1 swapstatic int maximumFixedPoints(int a[], int n){ int i, count = 0, swapped = 0; int pos[] = new int[n]; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Code public static void main (String[] args) { int []a= { 0, 1, 3, 4, 2 }; int n = a.length; System.out.println(maximumFixedPoints(a, n)); }} // This code is contributed// by shs
# Python3 program to find the maximum number# of fixed points using at most 1 swap # Function to find maximum number of# fixed points using atmost 1 swapdef maximumFixedPoints(a, n): pos = [None] * n count, swapped = 0, 0 # Store position of each element # in input array for i in range(0, n): pos[a[i]] = i for i in range(0, n): # If fixed point, increment count if a[i] == i: count += 1 # Else check if swapping increments # count by 2 elif swapped == 0 and pos[i] == a[i]: count += 2 swapped = 1 # If not swapped yet and elements remaining if swapped == 0 and count < n - 1: count += 1 return count # Driver Codeif __name__ == "__main__": a = [0, 1, 3, 4, 2] n = len(a) print(maximumFixedPoints(a, n)) # This code is contributed by Rituraj Jain
// C# program to find maximum number of// fixed points using atmost 1 swapusing System; class Program { // Function to find maximum number of// fixed points using atmost 1 swapstatic int maximumFixedPoints(int []a, int n){ int i, count = 0, swapped = 0; int []pos = new int[n]; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Code static void Main() { int []a= { 0, 1, 3, 4, 2 }; int n = a.Length; Console.WriteLine(maximumFixedPoints(a, n)); }} // This code is contributed// by ANKITRAI1
<?php// PHP program to find maximum number of// fixed points using atmost 1 swap // Function to find maximum number of// fixed points using atmost 1 swapfunction maximumFixedPoints($a, $n){ $i; $pos[$n]=array(); $count = 0; $swapped = 0; // Store position of each element in // input array for ($i = 0; $i < $n; $i++) $pos[$a[$i]] = $i; for ($i = 0; $i < $n; $i++) { // If fixed point, increment count if ($a[$i] == $i) $count++; // Else check if swapping increments // count by 2 else if ($swapped == 0 && $pos[$i] == $a[$i]) { $count += 2; $swapped = 1; } } // If not swapped yet and elements remaining if ($swapped == 0 && $count < $n - 1) $count++; return $count;} // Driver Code $a = array (0, 1, 3, 4, 2 ); $n = sizeof($a) / sizeof($a[0]); echo maximumFixedPoints($a, $n); // This code is contributed by Sachin?>
<script> // Javascript program to find maximum number of // fixed points using atmost 1 swap // Function to find maximum number of // fixed points using atmost 1 swap function maximumFixedPoints(a, n) { let i, count = 0, swapped = 0; let pos = new Array(n); // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count; } let a= [ 0, 1, 3, 4, 2 ]; let n = a.length; document.write(maximumFixedPoints(a, n)); // This code is contributed by divyesh072019.</script>
3
Time Complexity: O(N)
Shashank12
ankthon
Sach_Code
rituraj_jain
Akanksha_Rai
divyesh072019
simmytarika5
array-rearrange
limited-range-elements
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Building Heap from Array
Remove duplicates from sorted array
Sliding Window Maximum (Maximum of all subarrays of size k)
Move all negative numbers to beginning and positive to end with constant extra space | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 24692,
"s": 24431,
"text": "Given a permutation of N elements (Elements are in range 0 to N-1). A fixed point is an index at which the value is same as the index (That is, a[i]=i). You are allowed to make atmost 1 swap. Find the maximum number of fixed points that you can get.Examples: "
},
{
"code": null,
"e": 24873,
"s": 24692,
"text": "Input : N = 5\n arr[] = {0, 1, 3, 4, 2}\nOutput : 3\n2 and 3 can be swapped to get:\n0 1 2 4 3\nwhich has 3 fixed points.\n\nInput : N = 5\n a[] = {0, 1, 2, 4, 3}\nOutput : 5 "
},
{
"code": null,
"e": 25117,
"s": 24875,
"text": "Since we are allowed to make only 1 swap, the number of fixed points can be increased by atmost 2.Let’s have an array pos which keeps the position of each element in the input array. Now, we traverse the array and have the following cases: "
},
{
"code": null,
"e": 25178,
"s": 25117,
"text": "If, a[i] = i. We can simply increment the count and move on."
},
{
"code": null,
"e": 25351,
"s": 25178,
"text": "If, pos[i] = a[i] which means that swapping the 2 terms would make i and a[i] fixed points, hence increasing the count by 2. Keep in mind that swap can be done atmost once."
},
{
"code": null,
"e": 25676,
"s": 25351,
"text": "At the end of the traversal, if we haven’t made any swap, it means that our swap was not able to increase count by 2, so now if there are at least 2 elements which are not fixed points, we can make a swap to increase count by 1, i.e make one of those points a fixed point.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25680,
"s": 25676,
"text": "C++"
},
{
"code": null,
"e": 25685,
"s": 25680,
"text": "Java"
},
{
"code": null,
"e": 25693,
"s": 25685,
"text": "Python3"
},
{
"code": null,
"e": 25696,
"s": 25693,
"text": "C#"
},
{
"code": null,
"e": 25700,
"s": 25696,
"text": "PHP"
},
{
"code": null,
"e": 25711,
"s": 25700,
"text": "Javascript"
},
{
"code": "// CPP program to find maximum number of// fixed points using atmost 1 swap #include <bits/stdc++.h>using namespace std; // Function to find maximum number of// fixed points using atmost 1 swapint maximumFixedPoints(int a[], int n){ int i, pos[n], count = 0, swapped = 0; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Codeint main(){ int a[] = { 0, 1, 3, 4, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << maximumFixedPoints(a, n); return 0;}",
"e": 26657,
"s": 25711,
"text": null
},
{
"code": "// Java program to find maximum number of// fixed points using atmost 1 swapimport java.io.*; class GFG { // Function to find maximum number of// fixed points using atmost 1 swapstatic int maximumFixedPoints(int a[], int n){ int i, count = 0, swapped = 0; int pos[] = new int[n]; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Code public static void main (String[] args) { int []a= { 0, 1, 3, 4, 2 }; int n = a.length; System.out.println(maximumFixedPoints(a, n)); }} // This code is contributed// by shs",
"e": 27683,
"s": 26657,
"text": null
},
{
"code": "# Python3 program to find the maximum number# of fixed points using at most 1 swap # Function to find maximum number of# fixed points using atmost 1 swapdef maximumFixedPoints(a, n): pos = [None] * n count, swapped = 0, 0 # Store position of each element # in input array for i in range(0, n): pos[a[i]] = i for i in range(0, n): # If fixed point, increment count if a[i] == i: count += 1 # Else check if swapping increments # count by 2 elif swapped == 0 and pos[i] == a[i]: count += 2 swapped = 1 # If not swapped yet and elements remaining if swapped == 0 and count < n - 1: count += 1 return count # Driver Codeif __name__ == \"__main__\": a = [0, 1, 3, 4, 2] n = len(a) print(maximumFixedPoints(a, n)) # This code is contributed by Rituraj Jain",
"e": 28562,
"s": 27683,
"text": null
},
{
"code": "// C# program to find maximum number of// fixed points using atmost 1 swapusing System; class Program { // Function to find maximum number of// fixed points using atmost 1 swapstatic int maximumFixedPoints(int []a, int n){ int i, count = 0, swapped = 0; int []pos = new int[n]; // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count;} // Driver Code static void Main() { int []a= { 0, 1, 3, 4, 2 }; int n = a.Length; Console.WriteLine(maximumFixedPoints(a, n)); }} // This code is contributed// by ANKITRAI1",
"e": 29577,
"s": 28562,
"text": null
},
{
"code": "<?php// PHP program to find maximum number of// fixed points using atmost 1 swap // Function to find maximum number of// fixed points using atmost 1 swapfunction maximumFixedPoints($a, $n){ $i; $pos[$n]=array(); $count = 0; $swapped = 0; // Store position of each element in // input array for ($i = 0; $i < $n; $i++) $pos[$a[$i]] = $i; for ($i = 0; $i < $n; $i++) { // If fixed point, increment count if ($a[$i] == $i) $count++; // Else check if swapping increments // count by 2 else if ($swapped == 0 && $pos[$i] == $a[$i]) { $count += 2; $swapped = 1; } } // If not swapped yet and elements remaining if ($swapped == 0 && $count < $n - 1) $count++; return $count;} // Driver Code $a = array (0, 1, 3, 4, 2 ); $n = sizeof($a) / sizeof($a[0]); echo maximumFixedPoints($a, $n); // This code is contributed by Sachin?>",
"e": 30541,
"s": 29577,
"text": null
},
{
"code": "<script> // Javascript program to find maximum number of // fixed points using atmost 1 swap // Function to find maximum number of // fixed points using atmost 1 swap function maximumFixedPoints(a, n) { let i, count = 0, swapped = 0; let pos = new Array(n); // Store position of each element in // input array for (i = 0; i < n; i++) pos[a[i]] = i; for (i = 0; i < n; i++) { // If fixed point, increment count if (a[i] == i) count++; // Else check if swapping increments // count by 2 else if (swapped == 0 && pos[i] == a[i]) { count += 2; swapped = 1; } } // If not swapped yet and elements remaining if (swapped == 0 && count < n - 1) count++; return count; } let a= [ 0, 1, 3, 4, 2 ]; let n = a.length; document.write(maximumFixedPoints(a, n)); // This code is contributed by divyesh072019.</script>",
"e": 31605,
"s": 30541,
"text": null
},
{
"code": null,
"e": 31607,
"s": 31605,
"text": "3"
},
{
"code": null,
"e": 31632,
"s": 31609,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 31643,
"s": 31632,
"text": "Shashank12"
},
{
"code": null,
"e": 31651,
"s": 31643,
"text": "ankthon"
},
{
"code": null,
"e": 31661,
"s": 31651,
"text": "Sach_Code"
},
{
"code": null,
"e": 31674,
"s": 31661,
"text": "rituraj_jain"
},
{
"code": null,
"e": 31687,
"s": 31674,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31701,
"s": 31687,
"text": "divyesh072019"
},
{
"code": null,
"e": 31714,
"s": 31701,
"text": "simmytarika5"
},
{
"code": null,
"e": 31730,
"s": 31714,
"text": "array-rearrange"
},
{
"code": null,
"e": 31753,
"s": 31730,
"text": "limited-range-elements"
},
{
"code": null,
"e": 31760,
"s": 31753,
"text": "Arrays"
},
{
"code": null,
"e": 31767,
"s": 31760,
"text": "Arrays"
},
{
"code": null,
"e": 31865,
"s": 31767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31874,
"s": 31865,
"text": "Comments"
},
{
"code": null,
"e": 31887,
"s": 31874,
"text": "Old Comments"
},
{
"code": null,
"e": 31908,
"s": 31887,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31933,
"s": 31908,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31960,
"s": 31933,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32009,
"s": 31960,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32047,
"s": 32009,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32106,
"s": 32047,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 32131,
"s": 32106,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 32167,
"s": 32131,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 32227,
"s": 32167,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
}
]
|
Hide content depending on screen size with Bootstrap | Use the .hidden-* class in Bootstrap to hide content depending on screen size with Bootstrap
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<p class = "show">This is visible.</p>
<p class = "hidden">This is hidden.</p>
<h1 class = "hidden-sm bg-info">Hidden on small screen</h1>
<h1 class = "hidden-md bg-warning">Hidden on medium screen</h1>
</body>
</html> | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "Use the .hidden-* class in Bootstrap to hide content depending on screen size with Bootstrap"
},
{
"code": null,
"e": 1165,
"s": 1155,
"text": "Live Demo"
},
{
"code": null,
"e": 1696,
"s": 1165,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p class = \"show\">This is visible.</p>\n <p class = \"hidden\">This is hidden.</p>\n <h1 class = \"hidden-sm bg-info\">Hidden on small screen</h1>\n <h1 class = \"hidden-md bg-warning\">Hidden on medium screen</h1>\n </body>\n</html>"
}
]
|
K distance from root | Practice | GeeksforGeeks | Given a Binary Tree of size N and an integer K. Print all nodes that are at distance k from root (root is considered at distance 0 from itself). Nodes should be printed from left to right. If k is more that height of tree, nothing should be printed.
For example, if below is given tree and k is 2. Output should be 4 5 6.
1
/ \
2 3
/ / \
4 5 6
\
8
Example 1:
Input:
K = 0
1
/ \
3 2
Output: 1
Example 2:
Input:
K = 3
3
/
2
\
1
/ \
5 3
Output: 5 3
Your Task:
You don't have to take input. Complete the function Kdistance() that accepts root node and k as parameter and return the value of the nodes that are at a distance k from the root. (The values are returned as vector in cpp, as ArrayList in java and list in python)
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= N <= 104
0 <= K <= 30
Note: The Input/Ouput format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
0
ravi1010prakash1 day ago
vector<int>v;vector<int> Kdistance(struct Node *root, int k){ // vector<int>v; if(root==NULL) return v; if(k==0) v.push_back(root->data); else{ Kdistance(root->left,k-1); Kdistance(root->right,k-1);} return v;}
what is error in this code in given ???
0
ravi1010prakash
This comment was deleted.
0
shivanshmahajan8762 days ago
void k_d(Node * root , int k ,int level , vector <int> &ans){ if(root == NULL) { return ; } if(level == k) { ans.push_back(root->data); } k_d(root->left , k , level+1 , ans); k_d(root->right , k , level+1 , ans); }vector<int> Kdistance(struct Node *root, int k){ vector <int> ans; k_d(root , k , 0 , ans); return ans;}
0
mohittpattel2 weeks ago
Easy C++ Sol with explanation.
//Function to find the kth node
void kNode(Node* root, int k, vector<int>& result)
{
//Base condition
if(root == nullptr || k < 0)
return;
if(k == 0)
result.push_back(root->data);
//call the recurrsive function for the left subtree and decerment the value k by one
kNode(root->left, k-1, result);
//similarly with right node ofthe tree
kNode(root->right, k-1, result);
}
// function should print the nodes at k distance from root
vector<int> Kdistance(struct Node *root, int k)
{
// Your code here
vector<int> result;
//call the recurrsive function to find all itr nodes utp kth distance
kNode(root, k, result);
return result;
}
+1
alreadytaken2 weeks ago
void height(struct Node* root, int k, vector<int> &ans,int level){ if (root==NULL) return; if (level == k) ans.push_back(root->data); height(root->left,k,ans,level+1); height(root->right,k,ans,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int> ans; height(root,k,ans,0); return ans; }
0
shubhamtripathy2 weeks ago
Easy Python Solution
def Kutil(root,k,level,result):
if root is None:
return
if level==k:
result.append(root.data)
Kutil(root.left,k,level+1,result)
Kutil(root.right,k,level+1,result)
def KDistance(root,k):
result =[]
Kutil(root,k,0,result)
# code here
return result
0
roopsaisurampudi1 month ago
Java Iterative Solution (BFS)
ArrayList<Integer> Kdistance(Node root, int k)
{
// Your code here
ArrayList<Integer> ans = new ArrayList<>();
Queue<Node> q = new LinkedList<>();
q.add(root);
int K = -1;
while(!q.isEmpty()) {
int len = q.size();
K++;
for(int i = 0; i < len; i++) {
if (K == k) {
Node curr = q.poll();
ans.add(curr.data);
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
} else {
Node curr = q.poll();
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
}
}
if (K == k) break;
}
return ans;
}
0
rohanyt741 month ago
void K(Node*root,vector<int>&res,int k,int level){ if(root==NULL)return; if(level==k)res.push_back(root->data); K(root->left,res,k,level+1); K(root->right,res,k,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int>res; K(root,res,k,0); return res;}
0
rajsinh21811 month ago
Easy CPP BFS approach:
vector<int> Kdistance(struct Node *root, int k)
{
vector <int> v;
if(root==NULL) return v;
queue <Node*> q;
q.push(root);
while(!q.empty()){
for(int i=0;i<q.size();i++){
Node* temp = q.front();
if(k==0)v.push_back(temp->data); //only change
q.pop();
if(temp->left!=NULL)q.push(temp->left);
if(temp->right!=NULL)q.push(temp->right);
}
k--;//updation
}
return v;
}
0
ashutos17sharma89891 month ago
class Tree
{
// Recursive function to print right view of a binary tree.
ArrayList<Integer> Kdistance(Node root, int k)
{
// Your code here
ArrayList<Integer> ans = new ArrayList<>();
if(root==null){
return ans;
}
if(k==0){
ans.add(root.data);
}
ans.addAll(Kdistance(root.left, k-1));
ans.addAll(Kdistance(root.right, k-1));
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. | [
{
"code": null,
"e": 488,
"s": 238,
"text": "Given a Binary Tree of size N and an integer K. Print all nodes that are at distance k from root (root is considered at distance 0 from itself). Nodes should be printed from left to right. If k is more that height of tree, nothing should be printed."
},
{
"code": null,
"e": 560,
"s": 488,
"text": "For example, if below is given tree and k is 2. Output should be 4 5 6."
},
{
"code": null,
"e": 656,
"s": 560,
"text": " 1\n / \\\n 2 3\n / / \\\n 4 5 6 \n \\\n 8"
},
{
"code": null,
"e": 667,
"s": 656,
"text": "Example 1:"
},
{
"code": null,
"e": 721,
"s": 667,
"text": "Input:\nK = 0\n 1\n / \\\n 3 2\nOutput: 1\n\n"
},
{
"code": null,
"e": 732,
"s": 721,
"text": "Example 2:"
},
{
"code": null,
"e": 826,
"s": 732,
"text": "Input:\nK = 3\n 3\n /\n 2\n \\\n 1\n / \\\n 5 3\nOutput: 5 3"
},
{
"code": null,
"e": 1182,
"s": 826,
"text": "Your Task:\nYou don't have to take input. Complete the function Kdistance() that accepts root node and k as parameter and return the value of the nodes that are at a distance k from the root. (The values are returned as vector in cpp, as ArrayList in java and list in python)\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 1544,
"s": 1182,
"text": "Constraints:\n1 <= N <= 104\n0 <= K <= 30\n\nNote: The Input/Ouput format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1546,
"s": 1544,
"text": "0"
},
{
"code": null,
"e": 1571,
"s": 1546,
"text": "ravi1010prakash1 day ago"
},
{
"code": null,
"e": 1787,
"s": 1571,
"text": "vector<int>v;vector<int> Kdistance(struct Node *root, int k){ // vector<int>v; if(root==NULL) return v; if(k==0) v.push_back(root->data); else{ Kdistance(root->left,k-1); Kdistance(root->right,k-1);} return v;}"
},
{
"code": null,
"e": 1827,
"s": 1787,
"text": "what is error in this code in given ???"
},
{
"code": null,
"e": 1831,
"s": 1829,
"text": "0"
},
{
"code": null,
"e": 1847,
"s": 1831,
"text": "ravi1010prakash"
},
{
"code": null,
"e": 1873,
"s": 1847,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1875,
"s": 1873,
"text": "0"
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "shivanshmahajan8762 days ago"
},
{
"code": null,
"e": 2260,
"s": 1904,
"text": "void k_d(Node * root , int k ,int level , vector <int> &ans){ if(root == NULL) { return ; } if(level == k) { ans.push_back(root->data); } k_d(root->left , k , level+1 , ans); k_d(root->right , k , level+1 , ans); }vector<int> Kdistance(struct Node *root, int k){ vector <int> ans; k_d(root , k , 0 , ans); return ans;}"
},
{
"code": null,
"e": 2264,
"s": 2262,
"text": "0"
},
{
"code": null,
"e": 2288,
"s": 2264,
"text": "mohittpattel2 weeks ago"
},
{
"code": null,
"e": 2319,
"s": 2288,
"text": "Easy C++ Sol with explanation."
},
{
"code": null,
"e": 3006,
"s": 2319,
"text": "//Function to find the kth node\nvoid kNode(Node* root, int k, vector<int>& result)\n{\n //Base condition\n if(root == nullptr || k < 0)\n return;\n if(k == 0)\n result.push_back(root->data);\n //call the recurrsive function for the left subtree and decerment the value k by one\n kNode(root->left, k-1, result);\n //similarly with right node ofthe tree\n kNode(root->right, k-1, result);\n}\n\n// function should print the nodes at k distance from root\nvector<int> Kdistance(struct Node *root, int k)\n{\n // Your code here\n vector<int> result;\n //call the recurrsive function to find all itr nodes utp kth distance\n kNode(root, k, result);\n \n return result;\n}"
},
{
"code": null,
"e": 3009,
"s": 3006,
"text": "+1"
},
{
"code": null,
"e": 3033,
"s": 3009,
"text": "alreadytaken2 weeks ago"
},
{
"code": null,
"e": 3364,
"s": 3033,
"text": "void height(struct Node* root, int k, vector<int> &ans,int level){ if (root==NULL) return; if (level == k) ans.push_back(root->data); height(root->left,k,ans,level+1); height(root->right,k,ans,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int> ans; height(root,k,ans,0); return ans; }"
},
{
"code": null,
"e": 3366,
"s": 3364,
"text": "0"
},
{
"code": null,
"e": 3393,
"s": 3366,
"text": "shubhamtripathy2 weeks ago"
},
{
"code": null,
"e": 3414,
"s": 3393,
"text": "Easy Python Solution"
},
{
"code": null,
"e": 3716,
"s": 3414,
"text": "def Kutil(root,k,level,result):\n if root is None:\n return\n if level==k:\n result.append(root.data)\n Kutil(root.left,k,level+1,result)\n Kutil(root.right,k,level+1,result)\n \ndef KDistance(root,k):\n \n result =[]\n Kutil(root,k,0,result)\n # code here\n return result "
},
{
"code": null,
"e": 3718,
"s": 3716,
"text": "0"
},
{
"code": null,
"e": 3746,
"s": 3718,
"text": "roopsaisurampudi1 month ago"
},
{
"code": null,
"e": 3776,
"s": 3746,
"text": "Java Iterative Solution (BFS)"
},
{
"code": null,
"e": 4745,
"s": 3776,
"text": "ArrayList<Integer> Kdistance(Node root, int k)\n {\n // Your code here\n ArrayList<Integer> ans = new ArrayList<>();\n Queue<Node> q = new LinkedList<>();\n q.add(root);\n int K = -1;\n while(!q.isEmpty()) {\n int len = q.size();\n K++;\n for(int i = 0; i < len; i++) {\n if (K == k) {\n Node curr = q.poll();\n ans.add(curr.data);\n if (curr.left != null) q.add(curr.left);\n if (curr.right != null) q.add(curr.right);\n } else {\n Node curr = q.poll();\n \n if (curr.left != null) q.add(curr.left);\n if (curr.right != null) q.add(curr.right);\n }\n \n }\n if (K == k) break;\n \n }\n return ans;\n }"
},
{
"code": null,
"e": 4747,
"s": 4745,
"text": "0"
},
{
"code": null,
"e": 4768,
"s": 4747,
"text": "rohanyt741 month ago"
},
{
"code": null,
"e": 5060,
"s": 4768,
"text": "void K(Node*root,vector<int>&res,int k,int level){ if(root==NULL)return; if(level==k)res.push_back(root->data); K(root->left,res,k,level+1); K(root->right,res,k,level+1);}vector<int> Kdistance(struct Node *root, int k){ // Your code here vector<int>res; K(root,res,k,0); return res;}"
},
{
"code": null,
"e": 5062,
"s": 5060,
"text": "0"
},
{
"code": null,
"e": 5085,
"s": 5062,
"text": "rajsinh21811 month ago"
},
{
"code": null,
"e": 5108,
"s": 5085,
"text": "Easy CPP BFS approach:"
},
{
"code": null,
"e": 5583,
"s": 5108,
"text": "vector<int> Kdistance(struct Node *root, int k)\n{\n vector <int> v;\n if(root==NULL) return v;\n queue <Node*> q;\n q.push(root);\n while(!q.empty()){\n for(int i=0;i<q.size();i++){\n Node* temp = q.front();\n if(k==0)v.push_back(temp->data); //only change\n q.pop();\n if(temp->left!=NULL)q.push(temp->left);\n if(temp->right!=NULL)q.push(temp->right);\n }\n k--;//updation\n }\n return v;\n}"
},
{
"code": null,
"e": 5585,
"s": 5583,
"text": "0"
},
{
"code": null,
"e": 5616,
"s": 5585,
"text": "ashutos17sharma89891 month ago"
},
{
"code": null,
"e": 6100,
"s": 5616,
"text": "class Tree\n{\n // Recursive function to print right view of a binary tree.\n \n ArrayList<Integer> Kdistance(Node root, int k)\n {\n // Your code here\n ArrayList<Integer> ans = new ArrayList<>();\n if(root==null){\n return ans;\n }\n if(k==0){\n ans.add(root.data);\n }\n ans.addAll(Kdistance(root.left, k-1));\n ans.addAll(Kdistance(root.right, k-1));\n return ans; \n }\n}\n"
},
{
"code": null,
"e": 6246,
"s": 6100,
"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": 6282,
"s": 6246,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6292,
"s": 6282,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6302,
"s": 6292,
"text": "\nContest\n"
},
{
"code": null,
"e": 6365,
"s": 6302,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6513,
"s": 6365,
"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": 6721,
"s": 6513,
"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": 6827,
"s": 6721,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Python | Test if dictionary contains unique keys and values | 29 Apr, 2019
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it. Let’s test various ways in which this can be done.
Method #1 : Using loopsIn the Naive method to perform this particular task, we can check for each value and insert each value in list/hash in dictionary and when i’l repetition occurs, just stop the flow and return false.
# Python3 code to demonstrate# check for unique values# Using loops # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # using loops# check for unique valuesflag = Falsehash_val = dict()for keys in test_dict: if test_dict[keys] in hash_val: flag = True break else : hash_val[test_dict[keys]] = 1 # print resultprint("Does dictionary contain repetition : " + str(flag))
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True
Method #2 : Using len() + set() + values()This problem can be easily solved using the combination of above three functions. The set function can be used to convert the values to set, removing duplicates and values function can be used to access the values.
# Python3 code to demonstrate# check for unique values# Using len() + set() + values() # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # using len() + set() + values()# check for unique valuesflag = len(test_dict) != len(set(test_dict.values())) # print resultprint("Does dictionary contain repetition : " + str(flag))
The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}
Does dictionary contain repetition : True
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it. Let’s test various ways in which this can be done."
},
{
"code": null,
"e": 653,
"s": 431,
"text": "Method #1 : Using loopsIn the Naive method to perform this particular task, we can check for each value and insert each value in list/hash in dictionary and when i’l repetition occurs, just stop the flow and return false."
},
{
"code": "# Python3 code to demonstrate# check for unique values# Using loops # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # using loops# check for unique valuesflag = Falsehash_val = dict()for keys in test_dict: if test_dict[keys] in hash_val: flag = True break else : hash_val[test_dict[keys]] = 1 # print resultprint(\"Does dictionary contain repetition : \" + str(flag))",
"e": 1179,
"s": 653,
"text": null
},
{
"code": null,
"e": 1301,
"s": 1179,
"text": "The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}\nDoes dictionary contain repetition : True\n"
},
{
"code": null,
"e": 1560,
"s": 1303,
"text": "Method #2 : Using len() + set() + values()This problem can be easily solved using the combination of above three functions. The set function can be used to convert the values to set, removing duplicates and values function can be used to access the values."
},
{
"code": "# Python3 code to demonstrate# check for unique values# Using len() + set() + values() # initializing dictionarytest_dict = {'Manjeet' : 1, 'Akash' : 2, 'Akshat' : 3, 'Nikhil' : 1} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # using len() + set() + values()# check for unique valuesflag = len(test_dict) != len(set(test_dict.values())) # print resultprint(\"Does dictionary contain repetition : \" + str(flag))",
"e": 2012,
"s": 1560,
"text": null
},
{
"code": null,
"e": 2134,
"s": 2012,
"text": "The original dictionary : {'Nikhil': 1, 'Akash': 2, 'Akshat': 3, 'Manjeet': 1}\nDoes dictionary contain repetition : True\n"
},
{
"code": null,
"e": 2161,
"s": 2134,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2173,
"s": 2161,
"text": "python-dict"
},
{
"code": null,
"e": 2180,
"s": 2173,
"text": "Python"
},
{
"code": null,
"e": 2192,
"s": 2180,
"text": "python-dict"
}
]
|
Difference Between Iterator VS Generator | 24 Jan, 2021
A process that is repeated more than one time by applying the same logic is called an Iteration. In programming languages like python, a loop is created with few conditions to perform iteration till it exceeds the limit. If the loop is executed 6 times continuously, then we could say the particular block has iterated 6 times.
Example:
Python3
a = [0, 5, 10, 15, 20]for i in a: if i % 2 == 0: print(str(i)+' is an Even Number') else: print(str(i)+' is an Odd Number')
Output:
0 is an Even Number
5 is an Odd Number
10 is an Even Number
15 is an Odd Number
20 is an Even Number
An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects like list, tuples, sets, etc. Iterators are implemented using a class and a local variable for iterating is not required here, It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the memory until the item is called specifically which helps us to avoid repeated evaluation. As lazy evaluation is implemented, it requires only 1 memory location to process the value and when we are using a large dataset then, wastage of RAM space will be reduced the need to load the entire dataset at the same time will not be there.
Using an iterator-
iter() keyword is used to create an iterator containing an iterable object.
next() keyword is used to call the next element in the iterable object.
After the iterable object is completed, to use them again reassign them to the same object.
Example:
Python3
iter_list = iter(['Geeks', 'For', 'Geeks'])print(next(iter_list))print(next(iter_list))print(next(iter_list))
Output:
Geeks
For
Geeks
It is another way of creating iterators in a simple way where it uses the keyword “yield” instead of returning it in a defined function. Generators are implemented using a function. Just as iterators, generators also follow lazy evaluation. Here, the yield function returns the data without affecting or exiting the function. It will return a sequence of data in an iterable format where we need to iterate over the sequence to use the data as they won’t store the entire sequence in the memory.
Example:
Python3
def sq_numbers(n): for i in range(1, n+1): yield i*i a = sq_numbers(3) print("The square of numbers 1,2,3 are : ")print(next(a))print(next(a))print(next(a))
Output:
The square of numbers 1,2,3 are :
1
4
9
Class is used to implement an iterator
Function is used to implement a generator.
Local Variables aren’t used here.
All the local variables before the yield function are stored.
python-basics
Difference Between
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 382,
"s": 52,
"text": "A process that is repeated more than one time by applying the same logic is called an Iteration. In programming languages like python, a loop is created with few conditions to perform iteration till it exceeds the limit. If the loop is executed 6 times continuously, then we could say the particular block has iterated 6 times. "
},
{
"code": null,
"e": 391,
"s": 382,
"text": "Example:"
},
{
"code": null,
"e": 399,
"s": 391,
"text": "Python3"
},
{
"code": "a = [0, 5, 10, 15, 20]for i in a: if i % 2 == 0: print(str(i)+' is an Even Number') else: print(str(i)+' is an Odd Number')",
"e": 543,
"s": 399,
"text": null
},
{
"code": null,
"e": 551,
"s": 543,
"text": "Output:"
},
{
"code": null,
"e": 571,
"s": 551,
"text": "0 is an Even Number"
},
{
"code": null,
"e": 590,
"s": 571,
"text": "5 is an Odd Number"
},
{
"code": null,
"e": 611,
"s": 590,
"text": "10 is an Even Number"
},
{
"code": null,
"e": 631,
"s": 611,
"text": "15 is an Odd Number"
},
{
"code": null,
"e": 652,
"s": 631,
"text": "20 is an Even Number"
},
{
"code": null,
"e": 1330,
"s": 652,
"text": "An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects like list, tuples, sets, etc. Iterators are implemented using a class and a local variable for iterating is not required here, It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the memory until the item is called specifically which helps us to avoid repeated evaluation. As lazy evaluation is implemented, it requires only 1 memory location to process the value and when we are using a large dataset then, wastage of RAM space will be reduced the need to load the entire dataset at the same time will not be there."
},
{
"code": null,
"e": 1349,
"s": 1330,
"text": "Using an iterator-"
},
{
"code": null,
"e": 1425,
"s": 1349,
"text": "iter() keyword is used to create an iterator containing an iterable object."
},
{
"code": null,
"e": 1497,
"s": 1425,
"text": "next() keyword is used to call the next element in the iterable object."
},
{
"code": null,
"e": 1589,
"s": 1497,
"text": "After the iterable object is completed, to use them again reassign them to the same object."
},
{
"code": null,
"e": 1598,
"s": 1589,
"text": "Example:"
},
{
"code": null,
"e": 1606,
"s": 1598,
"text": "Python3"
},
{
"code": "iter_list = iter(['Geeks', 'For', 'Geeks'])print(next(iter_list))print(next(iter_list))print(next(iter_list))",
"e": 1716,
"s": 1606,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Output:"
},
{
"code": null,
"e": 1730,
"s": 1724,
"text": "Geeks"
},
{
"code": null,
"e": 1734,
"s": 1730,
"text": "For"
},
{
"code": null,
"e": 1742,
"s": 1734,
"text": "Geeks "
},
{
"code": null,
"e": 2238,
"s": 1742,
"text": "It is another way of creating iterators in a simple way where it uses the keyword “yield” instead of returning it in a defined function. Generators are implemented using a function. Just as iterators, generators also follow lazy evaluation. Here, the yield function returns the data without affecting or exiting the function. It will return a sequence of data in an iterable format where we need to iterate over the sequence to use the data as they won’t store the entire sequence in the memory."
},
{
"code": null,
"e": 2247,
"s": 2238,
"text": "Example:"
},
{
"code": null,
"e": 2255,
"s": 2247,
"text": "Python3"
},
{
"code": "def sq_numbers(n): for i in range(1, n+1): yield i*i a = sq_numbers(3) print(\"The square of numbers 1,2,3 are : \")print(next(a))print(next(a))print(next(a))",
"e": 2426,
"s": 2255,
"text": null
},
{
"code": null,
"e": 2434,
"s": 2426,
"text": "Output:"
},
{
"code": null,
"e": 2470,
"s": 2434,
"text": "The square of numbers 1,2,3 are : "
},
{
"code": null,
"e": 2472,
"s": 2470,
"text": "1"
},
{
"code": null,
"e": 2474,
"s": 2472,
"text": "4"
},
{
"code": null,
"e": 2476,
"s": 2474,
"text": "9"
},
{
"code": null,
"e": 2515,
"s": 2476,
"text": "Class is used to implement an iterator"
},
{
"code": null,
"e": 2558,
"s": 2515,
"text": "Function is used to implement a generator."
},
{
"code": null,
"e": 2633,
"s": 2558,
"text": "Local Variables aren’t used here. "
},
{
"code": null,
"e": 2696,
"s": 2633,
"text": "All the local variables before the yield function are stored. "
},
{
"code": null,
"e": 2710,
"s": 2696,
"text": "python-basics"
},
{
"code": null,
"e": 2729,
"s": 2710,
"text": "Difference Between"
},
{
"code": null,
"e": 2736,
"s": 2729,
"text": "Python"
},
{
"code": null,
"e": 2755,
"s": 2736,
"text": "Technical Scripter"
}
]
|
Explain spread operator in ES6 with an Example | 21 Oct, 2021
In this article, we will try to understand the basic details which are associated with the Spread operator which includes the syntax of the spread operator and its usage with the help of certain examples in ES6.
Let us first understand what is exactly Spread Operator is and what is its syntax and then further we will see some examples associated with its declaration.
Spread Operator:
The spread operator eventually takes any iterable object such as an array or any other iterable object and expands the values of that iterable object individually.
This spread operator is mainly used with the array containing more than 1 value in it.
That is, it basically spreads out all the elements of an array, and further after spreading the array elements we could perform any operations with those elements like concatenation, copying the elements of an array into another array, and so on.
Spread operator can also be used with objects for several operations like concatenation or copying one object’s values into another object and so on.
Syntax: Following syntax, we may use to implement spread operator with any iterable object like an array.
let variable = [...values];
Basically, what this syntax is doing that is taking the values from an array and thus storing it in a variable which is therefore acting as an array itself.
Now that we have understood the basics of the Spread operator including its syntax, it’s high time to see few examples which are based on the usage of the spread operator.
Example 1: In this example, we will try to perform the concatenation by firstly using the concat() method and then by using the simpler way which is by using the spread operator.
Javascript
<script> let array1 = [5, 6, 7]; let array2 = [8, 9, 10]; // Using concat() method..... let concatenatedArray = array1.concat(array2); console.log(concatenatedArray); // Using spread (...) operator...... let newArray = [...array1, ...array2]; console.log(newArray);</script>
Output: As you can see in the above code snippet that it becomes so simple to perform concatenation by using the spread operator syntax instead of using the predefined method concat().
[ 5, 6, 7, 8, 9, 10 ]
[ 5, 6, 7, 8, 9, 10 ]
Example 2: In this example, we will try to copy the values of one array into another array then afterward we will try to add some more values into the new array and then further we will see the changes being impacted on the previous and new array elements.
Javascript
<script> let arr = ["Apple", "Mango", "Banana"]; let newArr = [...arr]; console.log(newArr); // [ 'Apple', 'Mango', 'Banana' ] newArr.push("Grapes"); console.log(newArr); // [ 'Apple', 'Mango', 'Banana', 'Grapes' ] console.log(arr); // [ 'Apple', 'Mango', 'Banana' ]</script>
Output: As you can see in the above example when we normally entered a new value in the new array it doesn’t impact the older array, if we try to do it with the regular method we might get new array elements as same as older array elements.
[ 'Apple', 'Mango', 'Banana' ]
[ 'Apple', 'Mango', 'Banana', 'Grapes' ]
[ 'Apple', 'Mango', 'Banana' ]
Example 3: In this example, we will try to find the minimum element in an array of elements using the spread operator.
Javascript
<script> let Array = [5, 6, 8, 1, 0, -8, 10]; console.log(Math.min(...Array));</script>
Output: If we try to find the minimum element using some simpler way then we might experience an error message which says NaN (Not a number), but with the use of a spread operator, we will not be getting any error message like this.
-8
ES6
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "In this article, we will try to understand the basic details which are associated with the Spread operator which includes the syntax of the spread operator and its usage with the help of certain examples in ES6."
},
{
"code": null,
"e": 424,
"s": 266,
"text": "Let us first understand what is exactly Spread Operator is and what is its syntax and then further we will see some examples associated with its declaration."
},
{
"code": null,
"e": 441,
"s": 424,
"text": "Spread Operator:"
},
{
"code": null,
"e": 605,
"s": 441,
"text": "The spread operator eventually takes any iterable object such as an array or any other iterable object and expands the values of that iterable object individually."
},
{
"code": null,
"e": 692,
"s": 605,
"text": "This spread operator is mainly used with the array containing more than 1 value in it."
},
{
"code": null,
"e": 939,
"s": 692,
"text": "That is, it basically spreads out all the elements of an array, and further after spreading the array elements we could perform any operations with those elements like concatenation, copying the elements of an array into another array, and so on."
},
{
"code": null,
"e": 1089,
"s": 939,
"text": "Spread operator can also be used with objects for several operations like concatenation or copying one object’s values into another object and so on."
},
{
"code": null,
"e": 1195,
"s": 1089,
"text": "Syntax: Following syntax, we may use to implement spread operator with any iterable object like an array."
},
{
"code": null,
"e": 1224,
"s": 1195,
"text": "let variable = [...values]; "
},
{
"code": null,
"e": 1381,
"s": 1224,
"text": "Basically, what this syntax is doing that is taking the values from an array and thus storing it in a variable which is therefore acting as an array itself."
},
{
"code": null,
"e": 1553,
"s": 1381,
"text": "Now that we have understood the basics of the Spread operator including its syntax, it’s high time to see few examples which are based on the usage of the spread operator."
},
{
"code": null,
"e": 1732,
"s": 1553,
"text": "Example 1: In this example, we will try to perform the concatenation by firstly using the concat() method and then by using the simpler way which is by using the spread operator."
},
{
"code": null,
"e": 1743,
"s": 1732,
"text": "Javascript"
},
{
"code": "<script> let array1 = [5, 6, 7]; let array2 = [8, 9, 10]; // Using concat() method..... let concatenatedArray = array1.concat(array2); console.log(concatenatedArray); // Using spread (...) operator...... let newArray = [...array1, ...array2]; console.log(newArray);</script>",
"e": 2046,
"s": 1743,
"text": null
},
{
"code": null,
"e": 2231,
"s": 2046,
"text": "Output: As you can see in the above code snippet that it becomes so simple to perform concatenation by using the spread operator syntax instead of using the predefined method concat()."
},
{
"code": null,
"e": 2275,
"s": 2231,
"text": "[ 5, 6, 7, 8, 9, 10 ]\n[ 5, 6, 7, 8, 9, 10 ]"
},
{
"code": null,
"e": 2532,
"s": 2275,
"text": "Example 2: In this example, we will try to copy the values of one array into another array then afterward we will try to add some more values into the new array and then further we will see the changes being impacted on the previous and new array elements."
},
{
"code": null,
"e": 2543,
"s": 2532,
"text": "Javascript"
},
{
"code": "<script> let arr = [\"Apple\", \"Mango\", \"Banana\"]; let newArr = [...arr]; console.log(newArr); // [ 'Apple', 'Mango', 'Banana' ] newArr.push(\"Grapes\"); console.log(newArr); // [ 'Apple', 'Mango', 'Banana', 'Grapes' ] console.log(arr); // [ 'Apple', 'Mango', 'Banana' ]</script>",
"e": 2844,
"s": 2543,
"text": null
},
{
"code": null,
"e": 3087,
"s": 2846,
"text": "Output: As you can see in the above example when we normally entered a new value in the new array it doesn’t impact the older array, if we try to do it with the regular method we might get new array elements as same as older array elements."
},
{
"code": null,
"e": 3190,
"s": 3087,
"text": "[ 'Apple', 'Mango', 'Banana' ]\n[ 'Apple', 'Mango', 'Banana', 'Grapes' ]\n[ 'Apple', 'Mango', 'Banana' ]"
},
{
"code": null,
"e": 3309,
"s": 3190,
"text": "Example 3: In this example, we will try to find the minimum element in an array of elements using the spread operator."
},
{
"code": null,
"e": 3320,
"s": 3309,
"text": "Javascript"
},
{
"code": "<script> let Array = [5, 6, 8, 1, 0, -8, 10]; console.log(Math.min(...Array));</script>",
"e": 3416,
"s": 3320,
"text": null
},
{
"code": null,
"e": 3649,
"s": 3416,
"text": "Output: If we try to find the minimum element using some simpler way then we might experience an error message which says NaN (Not a number), but with the use of a spread operator, we will not be getting any error message like this."
},
{
"code": null,
"e": 3652,
"s": 3649,
"text": "-8"
},
{
"code": null,
"e": 3656,
"s": 3652,
"text": "ES6"
},
{
"code": null,
"e": 3677,
"s": 3656,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3684,
"s": 3677,
"text": "Picked"
},
{
"code": null,
"e": 3695,
"s": 3684,
"text": "JavaScript"
},
{
"code": null,
"e": 3712,
"s": 3695,
"text": "Web Technologies"
}
]
|
Find three element from different three arrays such that a + b + c = sum | 07 Jul, 2022
Given three integer arrays and a “sum”, the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays.
Examples :
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 9
Output : Yes
1 + 2 + 6 = 9 here 1 from a1[] and 2 from
a2[] and 6 from a3[]
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 20
Output : No
A naive approach is to run three loops and check sum of three element form different arrays equal to given number if find then print exist and otherwise print not exist.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find three element// from different three arrays such// that a + b + c is equal to// given sum#include<bits/stdc++.h>using namespace std; // Function to check if there is// an element from each array such// that sum of the three elements// is equal to given sum.bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum){ for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Codeint main(){ int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << "Yes" : cout << "No"; return 0;}
// Java program to find three element// from different three arrays such// that a + b + c is equal to// given sumclass GFG{ // Function to check if there is // an element from each array such // that sum of the three elements // is equal to given sum. static boolean findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false; } // Driver code public static void main (String[] args) { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = a1.length; int n2 = a2.length; int n3 = a3.length; if(findTriplet(a1, a2, a3, n1, n2, n3, sum)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal.
# Python3 program to find# three element from different# three arrays such that# a + b + c is equal to# given sum # Function to check if there# is an element from each# array such that sum of the# three elements is equal to# given sum.def findTriplet(a1, a2, a3, n1, n2, n3, sum): for i in range(0 , n1): for j in range(0 , n2): for k in range(0 , n3): if (a1[i] + a2[j] + a3[k] == sum): return True return False # Driver Codea1 = [ 1 , 2 , 3 , 4 , 5 ]a2 = [ 2 , 3 , 6 , 1 , 2 ]a3 = [ 3 , 2 , 4 , 5 , 6 ]sum = 9n1 = len(a1)n2 = len(a2)n3 = len(a3)print("Yes") if findTriplet(a1, a2, a3, n1, n2, n3, sum) else print("No") # This code is contributed# by Smitha
// C# program to find three element// from different three arrays such// that a + b + c is equal to// given sumusing System; public class GFG{ // Function to check if there is an// element from each array such that// sum of the three elements is// equal to given sum.static bool findTriplet(int []a1, int []a2, int []a3, int n1, int n2, int n3, int sum){ for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Code static public void Main () { int []a1 = {1 , 2 , 3 , 4 , 5}; int []a2 = {2 , 3 , 6 , 1 , 2}; int []a3 = {3 , 2 , 4 , 5 , 6}; int sum = 9; int n1 = a1.Length; int n2 = a2.Length; int n3 = a3.Length; if(findTriplet(a1, a2, a3, n1, n2, n3, sum)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is an// element from each array such that// sum of the three elements is equal// to given sum.function findTriplet($a1, $a2, $a3, $n1, $n2, $n3, $sum){ for ( $i = 0; $i < $n1; $i++) for ( $j = 0; $j < $n2; $j++) for ( $k = 0; $k < $n3; $k++) if ($a1[$i] + $a2[$j] + $a3[$k] == $sum) return true; return false;} // Driver Code$a1 = array( 1 , 2 , 3 , 4 , 5 );$a2 = array( 2 , 3 , 6 , 1 , 2 );$a3 = array( 3 , 2 , 4 , 5 , 6 );$sum = 9;$n1 = count($a1);$n2 = count($a2);$n3 = count($a3);if(findTriplet($a1, $a2, $a3, $n1, $n2, $n3, $sum)==true)echo "Yes" ;elseecho "No"; // This code is contributed by anuj_67.?>
<script> // JavaScript program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is// an element from each array such// that sum of the three elements// is equal to given sum.function findTriplet(a1, a2, a3, n1, n2, n3, sum){ for (var i = 0; i < n1; i++) for (var j = 0; j < n2; j++) for (var k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Codevar a1 = [ 1 , 2 , 3 , 4 , 5 ];var a2 = [ 2 , 3 , 6 , 1 , 2 ];var a3 = [ 3 , 2 , 4 , 5 , 6 ];var sum = 9;var n1 = a1.length;var n2 = a2.length;var n3 = a3.length;findTriplet(a1, a2, a3, n1, n2, n3, sum)? document.write("Yes") : document.write("No"); </script>
Yes
Time complexity : O(n3) Space complexity : O(1)
An efficient solution is to store all elements of first array in hash table (unordered_set in C++) and calculate sum of two elements last two array elements one by one and subtract from given number k and check in hash table if it exists in the hash table then print exist and otherwise not exist.
1. Store all elements of first array in hash table
2. Generate all pairs of elements from two arrays using
nested loop. For every pair (a1[i], a2[j]), check if
sum - (a1[i] + a2[j]) exists in hash table. If yes
return true.
Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to find three element// from different three arrays such// that a + b + c is equal to// given sum#include<bits/stdc++.h>using namespace std; // Function to check if there is// an element from each array such// that sum of the three elements is// equal to given sum.bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum){ // Store elements of // first array in hash unordered_set <int> s; for (int i = 0; i < n1; i++) s.insert(a1[i]); // sum last two arrays // element one by one for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.find(sum - a2[i] - a3[j]) != s.end()) return true; } } return false;} // Driver Codeint main(){ int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << "Yes" : cout << "No"; return 0;}
// Java program to find three element// from different three arrays such// that a + b + c is equal to// given sumimport java.util.*; class GFG{ // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. static boolean findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { // Store elements of // first array in hash HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n1; i++) { s.add(a1[i]); } // sum last two arrays // element one by one ArrayList<Integer> al = new ArrayList<>(s); for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (al.contains(sum - a2[i] - a3[j]) & al.indexOf(sum - a2[i] - a3[j]) != al.get(al.size() - 1)) { return true; } } } return false; } // Driver Code public static void main(String[] args) { int a1[] = {1, 2, 3, 4, 5}; int a2[] = {2, 3, 6, 1, 2}; int a3[] = {3, 2, 4, 5, 6}; int sum = 9; int n1 = a1.length; int n2 = a2.length; int n3 = a3.length; if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by 29AjayKumar
# Python3 program to find three element# from different three arrays such# that a + b + c is equal to# given sum # Function to check if there is# an element from each array such# that sum of the three elements is# equal to given sum.def findTriplet(a1, a2, a3, n1, n2, n3, sum): # Store elements of first # array in hash s = set() # sum last two arrays element # one by one for i in range(n1): s.add(a1[i]) for i in range(n2): for j in range(n3): # Consider current pair and # find if there is an element # in a1[] such that these three # form a required triplet if sum - a2[i] - a3[j] in s: return True return False # Driver codea1 = [1, 2, 3, 4, 5]a2 = [2, 3, 6, 1, 2]a3 = [3, 24, 5, 6]n1 = len(a1)n2 = len(a2)n3 = len(a3)sum = 9if findTriplet(a1, a2, a3, n1, n2, n3, sum) == True: print("Yes")else: print("No") # This code is contributed by Shrikant13
// C# program to find three element// from different three arrays such// that a + b + c is equal to// given sumusing System;using System.Collections.Generic; class GFG{ // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. static bool findTriplet(int []a1, int []a2, int []a3, int n1, int n2, int n3, int sum) { // Store elements of // first array in hash HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n1; i++) { s.Add(a1[i]); } // sum last two arrays // element one by one List<int> al = new List<int>(s); for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (al.Contains(sum - a2[i] - a3[j]) & al.IndexOf(sum - a2[i] - a3[j]) != al[al.Count - 1]) { return true; } } } return false; } // Driver Code public static void Main(String[] args) { int []a1 = {1, 2, 3, 4, 5}; int []a2 = {2, 3, 6, 1, 2}; int []a3 = {3, 2, 4, 5, 6}; int sum = 9; int n1 = a1.Length; int n2 = a2.Length; int n3 = a3.Length; if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is// an element from each array such// that sum of the three elements is// equal to given sum.function findTriplet(a1, a2, a3, n1, n2, n3, sum){ // Store elements of // first array in hash var s = new Set(); for (var i = 0; i < n1; i++) s.add(a1[i]); // sum last two arrays // element one by one for (var i = 0; i < n2; i++) { for (var j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.has(sum - a2[i] - a3[j])) return true; } } return false;} // Driver Codevar a1 = [1 , 2 , 3 , 4 , 5];var a2 = [2 , 3 , 6 , 1 , 2];var a3 = [3 , 2 , 4 , 5 , 6];var sum = 9;var n1 = a1.length;var n2 = a2.length;var n3 = a3.length;findTriplet(a1, a2, a3, n1, n2, n3, sum)?document.write( "Yes" ): document.write( "No"); // This code is contributed by famously.</script>
Yes
Time complexity: O(n2) Auxiliary Space: O(n)
This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
vt_m
Smitha Dinesh Semwal
29AjayKumar
princiraj1992
shrikanth13
Akanksha_Rai
rrrtnx
famously
sooda367
hardikkoriintern
Arrays
Hash
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
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Count pairs with given sum | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 227,
"s": 54,
"text": "Given three integer arrays and a “sum”, the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays. "
},
{
"code": null,
"e": 239,
"s": 227,
"text": "Examples : "
},
{
"code": null,
"e": 591,
"s": 239,
"text": "Input : a1[] = { 1 , 2 , 3 , 4 , 5 };\n a2[] = { 2 , 3 , 6 , 1 , 2 };\n a3[] = { 3 , 2 , 4 , 5 , 6 }; \n sum = 9\nOutput : Yes\n1 + 2 + 6 = 9 here 1 from a1[] and 2 from\na2[] and 6 from a3[] \n \nInput : a1[] = { 1 , 2 , 3 , 4 , 5 };\n a2[] = { 2 , 3 , 6 , 1 , 2 };\n a3[] = { 3 , 2 , 4 , 5 , 6 }; \n sum = 20 \nOutput : No "
},
{
"code": null,
"e": 763,
"s": 591,
"text": "A naive approach is to run three loops and check sum of three element form different arrays equal to given number if find then print exist and otherwise print not exist. "
},
{
"code": null,
"e": 779,
"s": 763,
"text": "Implementation:"
},
{
"code": null,
"e": 783,
"s": 779,
"text": "C++"
},
{
"code": null,
"e": 788,
"s": 783,
"text": "Java"
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Python3"
},
{
"code": null,
"e": 799,
"s": 796,
"text": "C#"
},
{
"code": null,
"e": 803,
"s": 799,
"text": "PHP"
},
{
"code": null,
"e": 814,
"s": 803,
"text": "Javascript"
},
{
"code": "// C++ program to find three element// from different three arrays such// that a + b + c is equal to// given sum#include<bits/stdc++.h>using namespace std; // Function to check if there is// an element from each array such// that sum of the three elements// is equal to given sum.bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum){ for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Codeint main(){ int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 1772,
"s": 814,
"text": null
},
{
"code": "// Java program to find three element// from different three arrays such// that a + b + c is equal to// given sumclass GFG{ // Function to check if there is // an element from each array such // that sum of the three elements // is equal to given sum. static boolean findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false; } // Driver code public static void main (String[] args) { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = a1.length; int n2 = a2.length; int n3 = a3.length; if(findTriplet(a1, a2, a3, n1, n2, n3, sum)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 2939,
"s": 1772,
"text": null
},
{
"code": "# Python3 program to find# three element from different# three arrays such that# a + b + c is equal to# given sum # Function to check if there# is an element from each# array such that sum of the# three elements is equal to# given sum.def findTriplet(a1, a2, a3, n1, n2, n3, sum): for i in range(0 , n1): for j in range(0 , n2): for k in range(0 , n3): if (a1[i] + a2[j] + a3[k] == sum): return True return False # Driver Codea1 = [ 1 , 2 , 3 , 4 , 5 ]a2 = [ 2 , 3 , 6 , 1 , 2 ]a3 = [ 3 , 2 , 4 , 5 , 6 ]sum = 9n1 = len(a1)n2 = len(a2)n3 = len(a3)print(\"Yes\") if findTriplet(a1, a2, a3, n1, n2, n3, sum) else print(\"No\") # This code is contributed# by Smitha",
"e": 3746,
"s": 2939,
"text": null
},
{
"code": "// C# program to find three element// from different three arrays such// that a + b + c is equal to// given sumusing System; public class GFG{ // Function to check if there is an// element from each array such that// sum of the three elements is// equal to given sum.static bool findTriplet(int []a1, int []a2, int []a3, int n1, int n2, int n3, int sum){ for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Code static public void Main () { int []a1 = {1 , 2 , 3 , 4 , 5}; int []a2 = {2 , 3 , 6 , 1 , 2}; int []a3 = {3 , 2 , 4 , 5 , 6}; int sum = 9; int n1 = a1.Length; int n2 = a2.Length; int n3 = a3.Length; if(findTriplet(a1, a2, a3, n1, n2, n3, sum)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 4851,
"s": 3746,
"text": null
},
{
"code": "<?php// PHP program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is an// element from each array such that// sum of the three elements is equal// to given sum.function findTriplet($a1, $a2, $a3, $n1, $n2, $n3, $sum){ for ( $i = 0; $i < $n1; $i++) for ( $j = 0; $j < $n2; $j++) for ( $k = 0; $k < $n3; $k++) if ($a1[$i] + $a2[$j] + $a3[$k] == $sum) return true; return false;} // Driver Code$a1 = array( 1 , 2 , 3 , 4 , 5 );$a2 = array( 2 , 3 , 6 , 1 , 2 );$a3 = array( 3 , 2 , 4 , 5 , 6 );$sum = 9;$n1 = count($a1);$n2 = count($a2);$n3 = count($a3);if(findTriplet($a1, $a2, $a3, $n1, $n2, $n3, $sum)==true)echo \"Yes\" ;elseecho \"No\"; // This code is contributed by anuj_67.?>",
"e": 5702,
"s": 4851,
"text": null
},
{
"code": "<script> // JavaScript program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is// an element from each array such// that sum of the three elements// is equal to given sum.function findTriplet(a1, a2, a3, n1, n2, n3, sum){ for (var i = 0; i < n1; i++) for (var j = 0; j < n2; j++) for (var k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false;} // Driver Codevar a1 = [ 1 , 2 , 3 , 4 , 5 ];var a2 = [ 2 , 3 , 6 , 1 , 2 ];var a3 = [ 3 , 2 , 4 , 5 , 6 ];var sum = 9;var n1 = a1.length;var n2 = a2.length;var n3 = a3.length;findTriplet(a1, a2, a3, n1, n2, n3, sum)? document.write(\"Yes\") : document.write(\"No\"); </script>",
"e": 6501,
"s": 5702,
"text": null
},
{
"code": null,
"e": 6505,
"s": 6501,
"text": "Yes"
},
{
"code": null,
"e": 6554,
"s": 6505,
"text": "Time complexity : O(n3) Space complexity : O(1) "
},
{
"code": null,
"e": 6853,
"s": 6554,
"text": "An efficient solution is to store all elements of first array in hash table (unordered_set in C++) and calculate sum of two elements last two array elements one by one and subtract from given number k and check in hash table if it exists in the hash table then print exist and otherwise not exist. "
},
{
"code": null,
"e": 7092,
"s": 6853,
"text": "1. Store all elements of first array in hash table\n2. Generate all pairs of elements from two arrays using\n nested loop. For every pair (a1[i], a2[j]), check if\n sum - (a1[i] + a2[j]) exists in hash table. If yes\n return true. "
},
{
"code": null,
"e": 7137,
"s": 7092,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 7141,
"s": 7137,
"text": "C++"
},
{
"code": null,
"e": 7146,
"s": 7141,
"text": "Java"
},
{
"code": null,
"e": 7154,
"s": 7146,
"text": "Python3"
},
{
"code": null,
"e": 7157,
"s": 7154,
"text": "C#"
},
{
"code": null,
"e": 7168,
"s": 7157,
"text": "Javascript"
},
{
"code": "// C++ program to find three element// from different three arrays such// that a + b + c is equal to// given sum#include<bits/stdc++.h>using namespace std; // Function to check if there is// an element from each array such// that sum of the three elements is// equal to given sum.bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum){ // Store elements of // first array in hash unordered_set <int> s; for (int i = 0; i < n1; i++) s.insert(a1[i]); // sum last two arrays // element one by one for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.find(sum - a2[i] - a3[j]) != s.end()) return true; } } return false;} // Driver Codeint main(){ int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 8527,
"s": 7168,
"text": null
},
{
"code": "// Java program to find three element// from different three arrays such// that a + b + c is equal to// given sumimport java.util.*; class GFG{ // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. static boolean findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { // Store elements of // first array in hash HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n1; i++) { s.add(a1[i]); } // sum last two arrays // element one by one ArrayList<Integer> al = new ArrayList<>(s); for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (al.contains(sum - a2[i] - a3[j]) & al.indexOf(sum - a2[i] - a3[j]) != al.get(al.size() - 1)) { return true; } } } return false; } // Driver Code public static void main(String[] args) { int a1[] = {1, 2, 3, 4, 5}; int a2[] = {2, 3, 6, 1, 2}; int a3[] = {3, 2, 4, 5, 6}; int sum = 9; int n1 = a1.length; int n2 = a2.length; int n3 = a3.length; if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by 29AjayKumar",
"e": 10344,
"s": 8527,
"text": null
},
{
"code": "# Python3 program to find three element# from different three arrays such# that a + b + c is equal to# given sum # Function to check if there is# an element from each array such# that sum of the three elements is# equal to given sum.def findTriplet(a1, a2, a3, n1, n2, n3, sum): # Store elements of first # array in hash s = set() # sum last two arrays element # one by one for i in range(n1): s.add(a1[i]) for i in range(n2): for j in range(n3): # Consider current pair and # find if there is an element # in a1[] such that these three # form a required triplet if sum - a2[i] - a3[j] in s: return True return False # Driver codea1 = [1, 2, 3, 4, 5]a2 = [2, 3, 6, 1, 2]a3 = [3, 24, 5, 6]n1 = len(a1)n2 = len(a2)n3 = len(a3)sum = 9if findTriplet(a1, a2, a3, n1, n2, n3, sum) == True: print(\"Yes\")else: print(\"No\") # This code is contributed by Shrikant13",
"e": 11346,
"s": 10344,
"text": null
},
{
"code": "// C# program to find three element// from different three arrays such// that a + b + c is equal to// given sumusing System;using System.Collections.Generic; class GFG{ // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. static bool findTriplet(int []a1, int []a2, int []a3, int n1, int n2, int n3, int sum) { // Store elements of // first array in hash HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n1; i++) { s.Add(a1[i]); } // sum last two arrays // element one by one List<int> al = new List<int>(s); for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (al.Contains(sum - a2[i] - a3[j]) & al.IndexOf(sum - a2[i] - a3[j]) != al[al.Count - 1]) { return true; } } } return false; } // Driver Code public static void Main(String[] args) { int []a1 = {1, 2, 3, 4, 5}; int []a2 = {2, 3, 6, 1, 2}; int []a3 = {3, 2, 4, 5, 6}; int sum = 9; int n1 = a1.Length; int n2 = a2.Length; int n3 = a3.Length; if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by PrinciRaj1992",
"e": 13161,
"s": 11346,
"text": null
},
{
"code": "<script> // Javascript program to find three element// from different three arrays such// that a + b + c is equal to// given sum // Function to check if there is// an element from each array such// that sum of the three elements is// equal to given sum.function findTriplet(a1, a2, a3, n1, n2, n3, sum){ // Store elements of // first array in hash var s = new Set(); for (var i = 0; i < n1; i++) s.add(a1[i]); // sum last two arrays // element one by one for (var i = 0; i < n2; i++) { for (var j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.has(sum - a2[i] - a3[j])) return true; } } return false;} // Driver Codevar a1 = [1 , 2 , 3 , 4 , 5];var a2 = [2 , 3 , 6 , 1 , 2];var a3 = [3 , 2 , 4 , 5 , 6];var sum = 9;var n1 = a1.length;var n2 = a2.length;var n3 = a3.length;findTriplet(a1, a2, a3, n1, n2, n3, sum)?document.write( \"Yes\" ): document.write( \"No\"); // This code is contributed by famously.</script>",
"e": 14303,
"s": 13161,
"text": null
},
{
"code": null,
"e": 14307,
"s": 14303,
"text": "Yes"
},
{
"code": null,
"e": 14353,
"s": 14307,
"text": "Time complexity: O(n2) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 14651,
"s": 14353,
"text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 14656,
"s": 14651,
"text": "vt_m"
},
{
"code": null,
"e": 14677,
"s": 14656,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 14689,
"s": 14677,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14703,
"s": 14689,
"text": "princiraj1992"
},
{
"code": null,
"e": 14715,
"s": 14703,
"text": "shrikanth13"
},
{
"code": null,
"e": 14728,
"s": 14715,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14735,
"s": 14728,
"text": "rrrtnx"
},
{
"code": null,
"e": 14744,
"s": 14735,
"text": "famously"
},
{
"code": null,
"e": 14753,
"s": 14744,
"text": "sooda367"
},
{
"code": null,
"e": 14770,
"s": 14753,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 14777,
"s": 14770,
"text": "Arrays"
},
{
"code": null,
"e": 14782,
"s": 14777,
"text": "Hash"
},
{
"code": null,
"e": 14789,
"s": 14782,
"text": "Arrays"
},
{
"code": null,
"e": 14794,
"s": 14789,
"text": "Hash"
},
{
"code": null,
"e": 14892,
"s": 14794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14960,
"s": 14892,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 15004,
"s": 14960,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 15036,
"s": 15004,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 15084,
"s": 15036,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 15098,
"s": 15084,
"text": "Linear Search"
},
{
"code": null,
"e": 15183,
"s": 15098,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15221,
"s": 15183,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 15252,
"s": 15221,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 15288,
"s": 15252,
"text": "Internal Working of HashMap in Java"
}
]
|
Python | Splitting string list by strings | 05 Sep, 2019
Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let’s discuss certain way to solve this particular problem.
Method : Using loop + index() + list slicingThis task can be performed by using the above functionalities together. In this, we just loop along the pairs and get the desired indices using index(). Then list slicing is done to construct a new list of the desired slice and appended to form a new resultant list.
# Python3 code to demonstrate working of# Splitting string list by strings# using loop + index() + list slicing # initialize listtest_list = ['gfg', 'is', 'best', "for", 'CS', 'and', 'Maths' ] # initialize split listsplit_list = [('gfg', 'best'), ('CS', 'Maths')] # printing original listprint("The original list is : " + str(test_list)) # printing split list print("The split list is : " + str(split_list)) # Splitting string list by strings# using loop + index() + list slicingfor start, end in split_list: temp1 = test_list.index(start) temp2 = test_list.index(end) + 1 test_list[temp1 : temp2] = [test_list[temp1 : temp2]] # printing resultprint("The resultant split list is : " + str(test_list))
The original list is : ['gfg', 'is', 'best', 'for', 'CS', 'and', 'Maths']
The split list is : [('gfg', 'best'), ('CS', 'Maths')]
The resultant split list is : [['gfg', 'is', 'best'], 'for', ['CS', 'and', 'Maths']]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let’s discuss certain way to solve this particular problem."
},
{
"code": null,
"e": 666,
"s": 355,
"text": "Method : Using loop + index() + list slicingThis task can be performed by using the above functionalities together. In this, we just loop along the pairs and get the desired indices using index(). Then list slicing is done to construct a new list of the desired slice and appended to form a new resultant list."
},
{
"code": "# Python3 code to demonstrate working of# Splitting string list by strings# using loop + index() + list slicing # initialize listtest_list = ['gfg', 'is', 'best', \"for\", 'CS', 'and', 'Maths' ] # initialize split listsplit_list = [('gfg', 'best'), ('CS', 'Maths')] # printing original listprint(\"The original list is : \" + str(test_list)) # printing split list print(\"The split list is : \" + str(split_list)) # Splitting string list by strings# using loop + index() + list slicingfor start, end in split_list: temp1 = test_list.index(start) temp2 = test_list.index(end) + 1 test_list[temp1 : temp2] = [test_list[temp1 : temp2]] # printing resultprint(\"The resultant split list is : \" + str(test_list))",
"e": 1394,
"s": 666,
"text": null
},
{
"code": null,
"e": 1609,
"s": 1394,
"text": "The original list is : ['gfg', 'is', 'best', 'for', 'CS', 'and', 'Maths']\nThe split list is : [('gfg', 'best'), ('CS', 'Maths')]\nThe resultant split list is : [['gfg', 'is', 'best'], 'for', ['CS', 'and', 'Maths']]\n"
},
{
"code": null,
"e": 1630,
"s": 1609,
"text": "Python list-programs"
},
{
"code": null,
"e": 1637,
"s": 1630,
"text": "Python"
},
{
"code": null,
"e": 1653,
"s": 1637,
"text": "Python Programs"
}
]
|
Fallthrough in C++ | 13 Jan, 2021
Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart ...etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line. Due to this when any case is matched with the specified value then control falls through to subsequent cases until a break statement is found. In C++, the error is not found on fallthrough but in languages like Dart, an error occurs whenever a fallthrough occurs.
It is not always necessary to avoid fallthrough, but it can be used as an advantage as well.
Program 1:
Below is the program to illustrate how fall-through occurs:
C++
// C++ program to illustrate// Fallthrough in C++#include <iostream>using namespace std; // Driver Codeint main(){ int n = 2; // Switch Cases switch (n) { case 1: { cout << "this is one \n"; } case 2: { cout << "this is two \n"; } case 3: { cout << "this is three \n"; } default: { cout << "this is default \n"; } } return 0;}
this is two
this is three
this is default
Explanation: In the above code, there is no break statement so after matching with the 2nd case the control will fall through and the subsequent statements will also get printed.
How to Avoid Fall Through?
To avoid Fall through, the idea is to use a break statement after each and every case so that after matching it goes out of the switch statement and control goes to the statement next to the switch statement.
Program 2:
Below is the program to illustrate how to avoid the fall through:
C++
// C++ program to illustrate how to// avoid fall through#include <iostream>using namespace std; // Driver Codeint main(){ int n = 2; // Switch Cases switch (n) { case 1: { cout << "this is one \n"; break; } case 2: { cout << "this is two \n"; // After this break statement // the control goes out of // the switch statement break; } case 3: { cout << "this is three \n"; break; } default: { cout << "this is default \n"; break; } } return 0;}
this is two
CPP-Basics
CPP-Control-Flow
cpp-switch
C++
C++ Programs
CPP-Control-Flow
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 564,
"s": 52,
"text": "Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart ...etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line. Due to this when any case is matched with the specified value then control falls through to subsequent cases until a break statement is found. In C++, the error is not found on fallthrough but in languages like Dart, an error occurs whenever a fallthrough occurs."
},
{
"code": null,
"e": 657,
"s": 564,
"text": "It is not always necessary to avoid fallthrough, but it can be used as an advantage as well."
},
{
"code": null,
"e": 668,
"s": 657,
"text": "Program 1:"
},
{
"code": null,
"e": 728,
"s": 668,
"text": "Below is the program to illustrate how fall-through occurs:"
},
{
"code": null,
"e": 732,
"s": 728,
"text": "C++"
},
{
"code": "// C++ program to illustrate// Fallthrough in C++#include <iostream>using namespace std; // Driver Codeint main(){ int n = 2; // Switch Cases switch (n) { case 1: { cout << \"this is one \\n\"; } case 2: { cout << \"this is two \\n\"; } case 3: { cout << \"this is three \\n\"; } default: { cout << \"this is default \\n\"; } } return 0;}",
"e": 1131,
"s": 732,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1131,
"text": "this is two \nthis is three \nthis is default\n"
},
{
"code": null,
"e": 1355,
"s": 1176,
"text": "Explanation: In the above code, there is no break statement so after matching with the 2nd case the control will fall through and the subsequent statements will also get printed."
},
{
"code": null,
"e": 1382,
"s": 1355,
"text": "How to Avoid Fall Through?"
},
{
"code": null,
"e": 1591,
"s": 1382,
"text": "To avoid Fall through, the idea is to use a break statement after each and every case so that after matching it goes out of the switch statement and control goes to the statement next to the switch statement."
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": "Program 2:"
},
{
"code": null,
"e": 1668,
"s": 1602,
"text": "Below is the program to illustrate how to avoid the fall through:"
},
{
"code": null,
"e": 1672,
"s": 1668,
"text": "C++"
},
{
"code": "// C++ program to illustrate how to// avoid fall through#include <iostream>using namespace std; // Driver Codeint main(){ int n = 2; // Switch Cases switch (n) { case 1: { cout << \"this is one \\n\"; break; } case 2: { cout << \"this is two \\n\"; // After this break statement // the control goes out of // the switch statement break; } case 3: { cout << \"this is three \\n\"; break; } default: { cout << \"this is default \\n\"; break; } } return 0;}",
"e": 2240,
"s": 1672,
"text": null
},
{
"code": null,
"e": 2253,
"s": 2240,
"text": "this is two\n"
},
{
"code": null,
"e": 2264,
"s": 2253,
"text": "CPP-Basics"
},
{
"code": null,
"e": 2281,
"s": 2264,
"text": "CPP-Control-Flow"
},
{
"code": null,
"e": 2292,
"s": 2281,
"text": "cpp-switch"
},
{
"code": null,
"e": 2296,
"s": 2292,
"text": "C++"
},
{
"code": null,
"e": 2309,
"s": 2296,
"text": "C++ Programs"
},
{
"code": null,
"e": 2326,
"s": 2309,
"text": "CPP-Control-Flow"
},
{
"code": null,
"e": 2330,
"s": 2326,
"text": "CPP"
},
{
"code": null,
"e": 2428,
"s": 2330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2452,
"s": 2428,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2472,
"s": 2452,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2505,
"s": 2472,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2530,
"s": 2505,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2574,
"s": 2530,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2609,
"s": 2574,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2643,
"s": 2609,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2687,
"s": 2643,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2746,
"s": 2687,
"text": "How to return multiple values from a function in C or C++?"
}
]
|
Multithreaded Servers in Java | 09 Nov, 2020
Prerequisites: Socket Programming in Java
Multithreaded Server: A server having more than one thread is known as Multithreaded Server. When a client sends the request, a thread is generated through which a user can communicate with the server. We need to generate multiple threads to accept multiple requests from multiple clients at the same time.
Advantages of Multithreaded Server:
Quick and Efficient: Multithreaded server could respond efficiently and quickly to the increasing client queries quickly.
Waiting time for users decreases: In a single-threaded server, other users had to wait until the running process gets completed but in multithreaded servers, all users can get a response at a single time so no user has to wait for other processes to finish.
Threads are independent of each other: There is no relation between any two threads. When a client is connected a new thread is generated every time.
The issue in one thread does not affect other threads: If any error occurs in any of the threads then no other thread is disturbed, all other processes keep running normally. In a single-threaded server, every other client had to wait if any problem occurs in the thread.
Disadvantages of Multithreaded Server:
Complicated Code: It is difficult to write the code of the multithreaded server. These programs can not be created easily
Debugging is difficult: Analyzing the main reason and origin of the error is difficult.
Quick Overview
We create two java files, Client.java and Server.java. Client file contains only one class Client (for creating a client). Server file has two classes, Server(creates a server) and ClientHandler(handles clients using multithreading).
Client-Side Program: A client can communicate with a server using this code. This involves
Establish a Socket ConnectionCommunication
Establish a Socket Connection
Communication
Java
import java.io.*;import java.net.*;import java.util.*; // Client classclass Client { // driver code public static void main(String[] args) { // establish a connection by providing host and port // number try (Socket socket = new Socket("localhost", 1234)) { // writing to server PrintWriter out = new PrintWriter( socket.getOutputStream(), true); // reading from server BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); // object of scanner class Scanner sc = new Scanner(System.in); String line = null; while (!"exit".equalsIgnoreCase(line)) { // reading from user line = sc.nextLine(); // sending the user input to server out.println(line); out.flush(); // displaying server reply System.out.println("Server replied " + in.readLine()); } // closing the scanner object sc.close(); } catch (IOException e) { e.printStackTrace(); } }}
Server-Side Program: When a new client is connected, and he sends the message to the server.
1. Server class: The steps involved on the server side are similar to the article Socket Programming in Java with a slight change to create the thread object after obtaining the streams and port number.
Establishing the Connection: Server socket object is initialized and inside a while loop a socket object continuously accepts an incoming connection.
Obtaining the Streams: The inputstream object and outputstream object is extracted from the current requests’ socket object.
Creating a handler object: After obtaining the streams and port number, a new clientHandler object (the above class) is created with these parameters.
Invoking the start() method: The start() method is invoked on this newly created thread object.
2. ClientHandler class: As we will be using separate threads for each request, let’s understand the working and implementation of the ClientHandler class implementing Runnable. An object of this class acts as a Runnable target for a new thread.
First, this class implements Runnable interface so that it can be passed as a Runnable target while creating a new Thread.
Secondly, the constructor of this class takes a parameter, which can uniquely identify any incoming request, i.e. a Socket.
Inside the run() method of this class, it reads the client’s message and replies.
Java
import java.io.*;import java.net.*; // Server classclass Server { public static void main(String[] args) { ServerSocket server = null; try { // server is listening on port 1234 server = new ServerSocket(1234); server.setReuseAddress(true); // running infinite loop for getting // client request while (true) { // socket object to receive incoming client // requests Socket client = server.accept(); // Displaying that new client is connected // to server System.out.println("New client connected" + client.getInetAddress() .getHostAddress()); // create a new thread object ClientHandler clientSock = new ClientHandler(client); // This thread will handle the client // separately new Thread(clientSock).start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } // ClientHandler class private static class ClientHandler implements Runnable { private final Socket clientSocket; // Constructor public ClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { PrintWriter out = null; BufferedReader in = null; try { // get the outputstream of client out = new PrintWriter( clientSocket.getOutputStream(), true); // get the inputstream of client in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String line; while ((line = in.readLine()) != null) { // writing the received message from // client System.out.printf( " Sent from the client: %s\n", line); out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); clientSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }}
Steps:
Compile both Client and Server programs.
Run the server first and then the Client.
Output
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Introduction to Java
Constructors in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Nov, 2020"
},
{
"code": null,
"e": 94,
"s": 52,
"text": "Prerequisites: Socket Programming in Java"
},
{
"code": null,
"e": 402,
"s": 94,
"text": "Multithreaded Server: A server having more than one thread is known as Multithreaded Server. When a client sends the request, a thread is generated through which a user can communicate with the server. We need to generate multiple threads to accept multiple requests from multiple clients at the same time. "
},
{
"code": null,
"e": 438,
"s": 402,
"text": "Advantages of Multithreaded Server:"
},
{
"code": null,
"e": 560,
"s": 438,
"text": "Quick and Efficient: Multithreaded server could respond efficiently and quickly to the increasing client queries quickly."
},
{
"code": null,
"e": 818,
"s": 560,
"text": "Waiting time for users decreases: In a single-threaded server, other users had to wait until the running process gets completed but in multithreaded servers, all users can get a response at a single time so no user has to wait for other processes to finish."
},
{
"code": null,
"e": 968,
"s": 818,
"text": "Threads are independent of each other: There is no relation between any two threads. When a client is connected a new thread is generated every time."
},
{
"code": null,
"e": 1240,
"s": 968,
"text": "The issue in one thread does not affect other threads: If any error occurs in any of the threads then no other thread is disturbed, all other processes keep running normally. In a single-threaded server, every other client had to wait if any problem occurs in the thread."
},
{
"code": null,
"e": 1279,
"s": 1240,
"text": "Disadvantages of Multithreaded Server:"
},
{
"code": null,
"e": 1401,
"s": 1279,
"text": "Complicated Code: It is difficult to write the code of the multithreaded server. These programs can not be created easily"
},
{
"code": null,
"e": 1489,
"s": 1401,
"text": "Debugging is difficult: Analyzing the main reason and origin of the error is difficult."
},
{
"code": null,
"e": 1504,
"s": 1489,
"text": "Quick Overview"
},
{
"code": null,
"e": 1738,
"s": 1504,
"text": "We create two java files, Client.java and Server.java. Client file contains only one class Client (for creating a client). Server file has two classes, Server(creates a server) and ClientHandler(handles clients using multithreading)."
},
{
"code": null,
"e": 1830,
"s": 1738,
"text": "Client-Side Program: A client can communicate with a server using this code. This involves "
},
{
"code": null,
"e": 1873,
"s": 1830,
"text": "Establish a Socket ConnectionCommunication"
},
{
"code": null,
"e": 1903,
"s": 1873,
"text": "Establish a Socket Connection"
},
{
"code": null,
"e": 1917,
"s": 1903,
"text": "Communication"
},
{
"code": null,
"e": 1922,
"s": 1917,
"text": "Java"
},
{
"code": "import java.io.*;import java.net.*;import java.util.*; // Client classclass Client { // driver code public static void main(String[] args) { // establish a connection by providing host and port // number try (Socket socket = new Socket(\"localhost\", 1234)) { // writing to server PrintWriter out = new PrintWriter( socket.getOutputStream(), true); // reading from server BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); // object of scanner class Scanner sc = new Scanner(System.in); String line = null; while (!\"exit\".equalsIgnoreCase(line)) { // reading from user line = sc.nextLine(); // sending the user input to server out.println(line); out.flush(); // displaying server reply System.out.println(\"Server replied \" + in.readLine()); } // closing the scanner object sc.close(); } catch (IOException e) { e.printStackTrace(); } }}",
"e": 3224,
"s": 1922,
"text": null
},
{
"code": null,
"e": 3317,
"s": 3224,
"text": "Server-Side Program: When a new client is connected, and he sends the message to the server."
},
{
"code": null,
"e": 3520,
"s": 3317,
"text": "1. Server class: The steps involved on the server side are similar to the article Socket Programming in Java with a slight change to create the thread object after obtaining the streams and port number."
},
{
"code": null,
"e": 3670,
"s": 3520,
"text": "Establishing the Connection: Server socket object is initialized and inside a while loop a socket object continuously accepts an incoming connection."
},
{
"code": null,
"e": 3795,
"s": 3670,
"text": "Obtaining the Streams: The inputstream object and outputstream object is extracted from the current requests’ socket object."
},
{
"code": null,
"e": 3946,
"s": 3795,
"text": "Creating a handler object: After obtaining the streams and port number, a new clientHandler object (the above class) is created with these parameters."
},
{
"code": null,
"e": 4042,
"s": 3946,
"text": "Invoking the start() method: The start() method is invoked on this newly created thread object."
},
{
"code": null,
"e": 4287,
"s": 4042,
"text": "2. ClientHandler class: As we will be using separate threads for each request, let’s understand the working and implementation of the ClientHandler class implementing Runnable. An object of this class acts as a Runnable target for a new thread."
},
{
"code": null,
"e": 4410,
"s": 4287,
"text": "First, this class implements Runnable interface so that it can be passed as a Runnable target while creating a new Thread."
},
{
"code": null,
"e": 4534,
"s": 4410,
"text": "Secondly, the constructor of this class takes a parameter, which can uniquely identify any incoming request, i.e. a Socket."
},
{
"code": null,
"e": 4616,
"s": 4534,
"text": "Inside the run() method of this class, it reads the client’s message and replies."
},
{
"code": null,
"e": 4621,
"s": 4616,
"text": "Java"
},
{
"code": "import java.io.*;import java.net.*; // Server classclass Server { public static void main(String[] args) { ServerSocket server = null; try { // server is listening on port 1234 server = new ServerSocket(1234); server.setReuseAddress(true); // running infinite loop for getting // client request while (true) { // socket object to receive incoming client // requests Socket client = server.accept(); // Displaying that new client is connected // to server System.out.println(\"New client connected\" + client.getInetAddress() .getHostAddress()); // create a new thread object ClientHandler clientSock = new ClientHandler(client); // This thread will handle the client // separately new Thread(clientSock).start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } // ClientHandler class private static class ClientHandler implements Runnable { private final Socket clientSocket; // Constructor public ClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { PrintWriter out = null; BufferedReader in = null; try { // get the outputstream of client out = new PrintWriter( clientSocket.getOutputStream(), true); // get the inputstream of client in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String line; while ((line = in.readLine()) != null) { // writing the received message from // client System.out.printf( \" Sent from the client: %s\\n\", line); out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); clientSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }}",
"e": 7630,
"s": 4621,
"text": null
},
{
"code": null,
"e": 7637,
"s": 7630,
"text": "Steps:"
},
{
"code": null,
"e": 7678,
"s": 7637,
"text": "Compile both Client and Server programs."
},
{
"code": null,
"e": 7720,
"s": 7678,
"text": "Run the server first and then the Client."
},
{
"code": null,
"e": 7727,
"s": 7720,
"text": "Output"
},
{
"code": null,
"e": 7747,
"s": 7727,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 7752,
"s": 7747,
"text": "Java"
},
{
"code": null,
"e": 7757,
"s": 7752,
"text": "Java"
},
{
"code": null,
"e": 7855,
"s": 7757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7874,
"s": 7855,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 7892,
"s": 7874,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 7907,
"s": 7892,
"text": "Stream In Java"
},
{
"code": null,
"e": 7927,
"s": 7907,
"text": "Collections in Java"
},
{
"code": null,
"e": 7959,
"s": 7927,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7983,
"s": 7959,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 8003,
"s": 7983,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 8015,
"s": 8003,
"text": "Set in Java"
},
{
"code": null,
"e": 8036,
"s": 8015,
"text": "Introduction to Java"
}
]
|
Draw Chess Board Using Turtle in Python | 01 Aug, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
For drawing Chess Board following steps are used :
Import turtle and making an object.
Set screen size and turtle position.
Define a method to draw a square
Call the method 8 times under another loop for 8 times with alternative color.
Hide the turtle object.
Below is the implementation :
python3
# import turtle packageimport turtle # create screen objectsc = turtle.Screen() # create turtle objectpen = turtle.Turtle() # method to draw squaredef draw(): for i in range(4): pen.forward(30) pen.left(90) pen.forward(30) # Driver Codeif __name__ == "__main__" : # set screen sc.setup(600, 600) # set turtle object speed pen.speed(100) # loops for board for i in range(8): # not ready to draw pen.up() # set position for every row pen.setpos(0, 30 * i) # ready to draw pen.down() # row for j in range(8): # conditions for alternative color if (i + j)% 2 == 0: col ='black' else: col ='white' # fill with given color pen.fillcolor(col) # start filling with colour pen.begin_fill() # call method draw() # stop filling pen.end_fill() # hide the turtle pen.hideturtle() # This code is contributed by Deepanshu Rustagi.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 323,
"s": 272,
"text": "For drawing Chess Board following steps are used :"
},
{
"code": null,
"e": 359,
"s": 323,
"text": "Import turtle and making an object."
},
{
"code": null,
"e": 396,
"s": 359,
"text": "Set screen size and turtle position."
},
{
"code": null,
"e": 429,
"s": 396,
"text": "Define a method to draw a square"
},
{
"code": null,
"e": 508,
"s": 429,
"text": "Call the method 8 times under another loop for 8 times with alternative color."
},
{
"code": null,
"e": 532,
"s": 508,
"text": "Hide the turtle object."
},
{
"code": null,
"e": 562,
"s": 532,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 570,
"s": 562,
"text": "python3"
},
{
"code": "# import turtle packageimport turtle # create screen objectsc = turtle.Screen() # create turtle objectpen = turtle.Turtle() # method to draw squaredef draw(): for i in range(4): pen.forward(30) pen.left(90) pen.forward(30) # Driver Codeif __name__ == \"__main__\" : # set screen sc.setup(600, 600) # set turtle object speed pen.speed(100) # loops for board for i in range(8): # not ready to draw pen.up() # set position for every row pen.setpos(0, 30 * i) # ready to draw pen.down() # row for j in range(8): # conditions for alternative color if (i + j)% 2 == 0: col ='black' else: col ='white' # fill with given color pen.fillcolor(col) # start filling with colour pen.begin_fill() # call method draw() # stop filling pen.end_fill() # hide the turtle pen.hideturtle() # This code is contributed by Deepanshu Rustagi.",
"e": 1675,
"s": 570,
"text": null
},
{
"code": null,
"e": 1689,
"s": 1675,
"text": "Python-turtle"
},
{
"code": null,
"e": 1696,
"s": 1689,
"text": "Python"
}
]
|
Sorted order printing of a given array that represents a BST | 16 Jun, 2022
Given an array that stores a complete Binary Search Tree, write a function that efficiently prints the given array in ascending order. For example, given an array [4, 2, 5, 1, 3], the function should print 1, 2, 3, 4, 5
Solution:
Inorder traversal of BST prints it in ascending order. The only trick is to modify recursion termination condition in standard Inorder Tree Traversal.
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Code for Sorted order printing of a// given array that represents a BST#include<bits/stdc++.h>using namespace std; void printSorted(int arr[], int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root cout << arr[start] << " "; // print right subtree printSorted(arr, start*2 + 2, end);} int main(){ int arr[] = {4, 2, 5, 1, 3}; int arr_size = sizeof(arr)/sizeof(int); printSorted(arr, 0, arr_size-1); getchar(); return 0;} // This code is contributed by Akanksha Rai
// C Code for Sorted order printing of a// given array that represents a BST#include<stdio.h> void printSorted(int arr[], int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root printf("%d ", arr[start]); // print right subtree printSorted(arr, start*2 + 2, end); } int main(){ int arr[] = {4, 2, 5, 1, 3}; int arr_size = sizeof(arr)/sizeof(int); printSorted(arr, 0, arr_size-1); getchar(); return 0;}
// JAVA Code for Sorted order printing of a// given array that represents a BSTclass GFG{ private static void printSorted(int[] arr, int start, int end) { if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root System.out.print(arr[start] + " "); // print right subtree printSorted(arr, start*2 + 2, end); } // driver program to test above function public static void main(String[] args) { int arr[] = {4, 2, 5, 1, 3}; printSorted(arr, 0, arr.length-1); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 Code for Sorted order printing of a# given array that represents a BSTdef printSorted(arr, start, end): if start > end: return # print left subtree printSorted(arr, start * 2 + 1, end) # print root print(arr[start], end = " ") # print right subtree printSorted(arr, start * 2 + 2, end) # Driver Code if __name__ == '__main__': arr = [4, 2, 5, 1, 3] arr_size = len(arr) printSorted(arr, 0, arr_size - 1) # This code is contributed by PranchalK
// C# Code for Sorted order printing// of a given array that represents a BSTusing System; class GFG{static private void printSorted(int []arr, int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start * 2 + 1, end); // print root Console.Write(arr[start] + " "); // print right subtree printSorted(arr, start * 2 + 2, end); } // Driver Codestatic public void Main(String []args){ int []arr= {4, 2, 5, 1, 3}; printSorted(arr, 0, arr.Length - 1);}} // This code is contributed by Arnab Kundu
<?php// PHP Code for Sorted order printing of a// given array that represents a BST function printSorted($arr, $start, $end){ if($start > $end) return; // print left subtree printSorted($arr, $start * 2 + 1, $end); // print root echo($arr[$start] . " "); // print right subtree printSorted($arr, $start * 2 + 2, $end);} // Driver Code$arr = array(4, 2, 5, 1, 3); printSorted($arr, 0, sizeof($arr) - 1); // This code is contributed by Code_Mech.
<script> // Javascript Code for Sorted order printing of a// given array that represents a BSTfunction printSorted(arr, start, end){ if (start > end) return; // Print var left subtree printSorted(arr, start * 2 + 1, end); // Print var root document.write(arr[start] + " "); // Print var right subtree printSorted(arr, start * 2 + 2, end);} // Driver codevar arr = [4, 2, 5, 1, 3]; printSorted(arr, 0, arr.length - 1); // This code is contributed by shikhasingrajput </script>
Output:
1 2 3 4 5
Time Complexity: O(n)
Sorted order printing of a given array that represents a BST | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSorted order printing of a given array that represents a BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:19•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Z_5OpW49Rik" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find the above solution incorrect, or find better ways to solve the same problem.
andrew1234
PranchalKatiyar
Code_Mech
Akanksha_Rai
shikhasingrajput
hardikkoriintern
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "Given an array that stores a complete Binary Search Tree, write a function that efficiently prints the given array in ascending order. For example, given an array [4, 2, 5, 1, 3], the function should print 1, 2, 3, 4, 5 "
},
{
"code": null,
"e": 283,
"s": 273,
"text": "Solution:"
},
{
"code": null,
"e": 434,
"s": 283,
"text": "Inorder traversal of BST prints it in ascending order. The only trick is to modify recursion termination condition in standard Inorder Tree Traversal."
},
{
"code": null,
"e": 451,
"s": 434,
"text": "Implementation: "
},
{
"code": null,
"e": 455,
"s": 451,
"text": "C++"
},
{
"code": null,
"e": 457,
"s": 455,
"text": "C"
},
{
"code": null,
"e": 462,
"s": 457,
"text": "Java"
},
{
"code": null,
"e": 470,
"s": 462,
"text": "Python3"
},
{
"code": null,
"e": 473,
"s": 470,
"text": "C#"
},
{
"code": null,
"e": 477,
"s": 473,
"text": "PHP"
},
{
"code": null,
"e": 488,
"s": 477,
"text": "Javascript"
},
{
"code": "// C++ Code for Sorted order printing of a// given array that represents a BST#include<bits/stdc++.h>using namespace std; void printSorted(int arr[], int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root cout << arr[start] << \" \"; // print right subtree printSorted(arr, start*2 + 2, end);} int main(){ int arr[] = {4, 2, 5, 1, 3}; int arr_size = sizeof(arr)/sizeof(int); printSorted(arr, 0, arr_size-1); getchar(); return 0;} // This code is contributed by Akanksha Rai",
"e": 1084,
"s": 488,
"text": null
},
{
"code": "// C Code for Sorted order printing of a// given array that represents a BST#include<stdio.h> void printSorted(int arr[], int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root printf(\"%d \", arr[start]); // print right subtree printSorted(arr, start*2 + 2, end); } int main(){ int arr[] = {4, 2, 5, 1, 3}; int arr_size = sizeof(arr)/sizeof(int); printSorted(arr, 0, arr_size-1); getchar(); return 0;}",
"e": 1570,
"s": 1084,
"text": null
},
{
"code": "// JAVA Code for Sorted order printing of a// given array that represents a BSTclass GFG{ private static void printSorted(int[] arr, int start, int end) { if(start > end) return; // print left subtree printSorted(arr, start*2 + 1, end); // print root System.out.print(arr[start] + \" \"); // print right subtree printSorted(arr, start*2 + 2, end); } // driver program to test above function public static void main(String[] args) { int arr[] = {4, 2, 5, 1, 3}; printSorted(arr, 0, arr.length-1); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 2314,
"s": 1570,
"text": null
},
{
"code": "# Python3 Code for Sorted order printing of a# given array that represents a BSTdef printSorted(arr, start, end): if start > end: return # print left subtree printSorted(arr, start * 2 + 1, end) # print root print(arr[start], end = \" \") # print right subtree printSorted(arr, start * 2 + 2, end) # Driver Code if __name__ == '__main__': arr = [4, 2, 5, 1, 3] arr_size = len(arr) printSorted(arr, 0, arr_size - 1) # This code is contributed by PranchalK",
"e": 2821,
"s": 2314,
"text": null
},
{
"code": "// C# Code for Sorted order printing// of a given array that represents a BSTusing System; class GFG{static private void printSorted(int []arr, int start, int end){ if(start > end) return; // print left subtree printSorted(arr, start * 2 + 1, end); // print root Console.Write(arr[start] + \" \"); // print right subtree printSorted(arr, start * 2 + 2, end); } // Driver Codestatic public void Main(String []args){ int []arr= {4, 2, 5, 1, 3}; printSorted(arr, 0, arr.Length - 1);}} // This code is contributed by Arnab Kundu",
"e": 3487,
"s": 2821,
"text": null
},
{
"code": "<?php// PHP Code for Sorted order printing of a// given array that represents a BST function printSorted($arr, $start, $end){ if($start > $end) return; // print left subtree printSorted($arr, $start * 2 + 1, $end); // print root echo($arr[$start] . \" \"); // print right subtree printSorted($arr, $start * 2 + 2, $end);} // Driver Code$arr = array(4, 2, 5, 1, 3); printSorted($arr, 0, sizeof($arr) - 1); // This code is contributed by Code_Mech.",
"e": 3995,
"s": 3487,
"text": null
},
{
"code": "<script> // Javascript Code for Sorted order printing of a// given array that represents a BSTfunction printSorted(arr, start, end){ if (start > end) return; // Print var left subtree printSorted(arr, start * 2 + 1, end); // Print var root document.write(arr[start] + \" \"); // Print var right subtree printSorted(arr, start * 2 + 2, end);} // Driver codevar arr = [4, 2, 5, 1, 3]; printSorted(arr, 0, arr.length - 1); // This code is contributed by shikhasingrajput </script>",
"e": 4534,
"s": 3995,
"text": null
},
{
"code": null,
"e": 4543,
"s": 4534,
"text": "Output: "
},
{
"code": null,
"e": 4554,
"s": 4543,
"text": "1 2 3 4 5 "
},
{
"code": null,
"e": 4576,
"s": 4554,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 5514,
"s": 4576,
"text": "Sorted order printing of a given array that represents a BST | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSorted order printing of a given array that represents a BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:19•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Z_5OpW49Rik\" 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": 5625,
"s": 5514,
"text": "Please write comments if you find the above solution incorrect, or find better ways to solve the same problem."
},
{
"code": null,
"e": 5636,
"s": 5625,
"text": "andrew1234"
},
{
"code": null,
"e": 5652,
"s": 5636,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 5662,
"s": 5652,
"text": "Code_Mech"
},
{
"code": null,
"e": 5675,
"s": 5662,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5692,
"s": 5675,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 5709,
"s": 5692,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5728,
"s": 5709,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5747,
"s": 5728,
"text": "Binary Search Tree"
}
]
|
How to Add padding to a tkinter widget only on one side ? | 15 Mar, 2021
In this article, we will discuss the procedure of adding padding to a Tkinter widget only on one side. Here, we create a widget and use widget.grid() method in tkinter to padding the content of the widget. For example, let’s create a label and use label.grid() method. Below the syntax is given:
label1 = Widget_Name(app, text="text_to_be_written_in_label")
label1.grid(
padx=(padding_from_left_side, padding_from_right_side),
pady=(padding_from_top, padding_from_bottom))
Steps Needed:
First, import the library tkinter
from tkinter import *
Now, create a GUI app using tkinter
app= Tk()
Next, give a title to the app.
app.title(“Name of GUI app”)
Then, create the widget by replacing the #Widget Name with the name of the widget (such as Label, Button, etc.).
l1 =Widget_Name(app, text="Text we want to give in widget")
Moreover, give the padding where we want to give it.
l1.grid(padx=(padding from left side, padding from right side),
pady=(padding from top, padding from bottom))
For instance, if we want to give the padding from the top side only, then enter the padding value at the specified position, and leave the remaining as zero. It will give the padding to a widget from one side only, i.e., top.
l1.grid(padx=(0, 0), pady=(200, 0))
Finally, make the loop for displaying the GUI app on the screen.
app.mainloop( )
It will give the output as follows:
Example 1: Padding at left-side to a widget
Python
# Python program to add padding# to a widget only on left-side # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title("Vinayak App") # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry("%dx%d" % (width, height)) # Construct the label in your appl1 = Label(app, text='Geeks For Geeks') # Give the leftmost paddingl1.grid(padx=(200, 0), pady=(0, 0)) # Make the loop for displaying appapp.mainloop()
Output:
Example 2: Padding from top to a widget
Python
# Python program to add padding# to a widget only from top # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title("Vinayak App") # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry("%dx%d" % (width, height)) # Construct the button in your appb1 = Button(app, text='Click Here!') # Give the topmost paddingb1.grid(padx=(0, 0), pady=(200, 0)) # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 348,
"s": 52,
"text": "In this article, we will discuss the procedure of adding padding to a Tkinter widget only on one side. Here, we create a widget and use widget.grid() method in tkinter to padding the content of the widget. For example, let’s create a label and use label.grid() method. Below the syntax is given:"
},
{
"code": null,
"e": 534,
"s": 348,
"text": "label1 = Widget_Name(app, text=\"text_to_be_written_in_label\")\nlabel1.grid(\n padx=(padding_from_left_side, padding_from_right_side), \n pady=(padding_from_top, padding_from_bottom))"
},
{
"code": null,
"e": 549,
"s": 534,
"text": "Steps Needed: "
},
{
"code": null,
"e": 583,
"s": 549,
"text": "First, import the library tkinter"
},
{
"code": null,
"e": 605,
"s": 583,
"text": "from tkinter import *"
},
{
"code": null,
"e": 641,
"s": 605,
"text": "Now, create a GUI app using tkinter"
},
{
"code": null,
"e": 651,
"s": 641,
"text": "app= Tk()"
},
{
"code": null,
"e": 682,
"s": 651,
"text": "Next, give a title to the app."
},
{
"code": null,
"e": 711,
"s": 682,
"text": "app.title(“Name of GUI app”)"
},
{
"code": null,
"e": 824,
"s": 711,
"text": "Then, create the widget by replacing the #Widget Name with the name of the widget (such as Label, Button, etc.)."
},
{
"code": null,
"e": 884,
"s": 824,
"text": "l1 =Widget_Name(app, text=\"Text we want to give in widget\")"
},
{
"code": null,
"e": 937,
"s": 884,
"text": "Moreover, give the padding where we want to give it."
},
{
"code": null,
"e": 1051,
"s": 937,
"text": "l1.grid(padx=(padding from left side, padding from right side),\n pady=(padding from top, padding from bottom))"
},
{
"code": null,
"e": 1277,
"s": 1051,
"text": "For instance, if we want to give the padding from the top side only, then enter the padding value at the specified position, and leave the remaining as zero. It will give the padding to a widget from one side only, i.e., top."
},
{
"code": null,
"e": 1313,
"s": 1277,
"text": "l1.grid(padx=(0, 0), pady=(200, 0))"
},
{
"code": null,
"e": 1378,
"s": 1313,
"text": "Finally, make the loop for displaying the GUI app on the screen."
},
{
"code": null,
"e": 1394,
"s": 1378,
"text": "app.mainloop( )"
},
{
"code": null,
"e": 1430,
"s": 1394,
"text": "It will give the output as follows:"
},
{
"code": null,
"e": 1474,
"s": 1430,
"text": "Example 1: Padding at left-side to a widget"
},
{
"code": null,
"e": 1481,
"s": 1474,
"text": "Python"
},
{
"code": "# Python program to add padding# to a widget only on left-side # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title(\"Vinayak App\") # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry(\"%dx%d\" % (width, height)) # Construct the label in your appl1 = Label(app, text='Geeks For Geeks') # Give the leftmost paddingl1.grid(padx=(200, 0), pady=(0, 0)) # Make the loop for displaying appapp.mainloop()",
"e": 2000,
"s": 1481,
"text": null
},
{
"code": null,
"e": 2008,
"s": 2000,
"text": "Output:"
},
{
"code": null,
"e": 2048,
"s": 2008,
"text": "Example 2: Padding from top to a widget"
},
{
"code": null,
"e": 2055,
"s": 2048,
"text": "Python"
},
{
"code": "# Python program to add padding# to a widget only from top # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title(\"Vinayak App\") # Maximize the window screenwidth = app.winfo_screenwidth()height = app.winfo_screenheight()app.geometry(\"%dx%d\" % (width, height)) # Construct the button in your appb1 = Button(app, text='Click Here!') # Give the topmost paddingb1.grid(padx=(0, 0), pady=(200, 0)) # Make the loop for displaying appapp.mainloop()",
"e": 2567,
"s": 2055,
"text": null
},
{
"code": null,
"e": 2575,
"s": 2567,
"text": "Output:"
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": "Picked"
},
{
"code": null,
"e": 2607,
"s": 2582,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 2622,
"s": 2607,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2629,
"s": 2622,
"text": "Python"
}
]
|
Create pandas dataframe from lists using dictionary | 13 Dec, 2018
Creating pandas data-frame from lists using dictionary can be achieved in multiple ways.
Method #1: Using pandas.DataFrame
With this method in Pandas we can transform a dictionary of list to a dataframe.
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict) df
Output:
Method #2: Using from_dict() function.
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame.from_dict(dict) df
Output:With the use of this function, we get some flexibility in arranging our data, such as the orientation of data, data type and name of the columns can be entered as parameter in the function.
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2018"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "Creating pandas data-frame from lists using dictionary can be achieved in multiple ways."
},
{
"code": null,
"e": 151,
"s": 117,
"text": "Method #1: Using pandas.DataFrame"
},
{
"code": null,
"e": 232,
"s": 151,
"text": "With this method in Pandas we can transform a dictionary of list to a dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict) df",
"e": 466,
"s": 232,
"text": null
},
{
"code": null,
"e": 475,
"s": 466,
"text": "Output: "
},
{
"code": null,
"e": 514,
"s": 475,
"text": "Method #2: Using from_dict() function."
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame.from_dict(dict) df",
"e": 758,
"s": 514,
"text": null
},
{
"code": null,
"e": 955,
"s": 758,
"text": "Output:With the use of this function, we get some flexibility in arranging our data, such as the orientation of data, data type and name of the columns can be entered as parameter in the function."
},
{
"code": null,
"e": 980,
"s": 955,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 987,
"s": 980,
"text": "Picked"
},
{
"code": null,
"e": 1011,
"s": 987,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1025,
"s": 1011,
"text": "Python-pandas"
},
{
"code": null,
"e": 1032,
"s": 1025,
"text": "Python"
}
]
|
List addAll() Method in Java with Examples | 02 Jan, 2019
This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
Syntax:
boolean addAll(Collection c)
Parameters: This function has a single parameter, i.e, Collection c, whose elements are to be appended to the list.
Returns: It returns true if the elements of specified list is appended and list changes.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type arraylist List<Integer> l = new ArrayList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing a collection to be appended to list ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(100); arr.add(200); arr.add(300); System.out.println(arr); l.addAll(arr); System.out.println(l); }}
[10, 15, 20]
[100, 200, 300]
[10, 15, 20, 100, 200, 300]
Program 2: Below is the code to show implementation of list.addAll() using Linkedlist.
// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing a collection to be appended to list ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(100); arr.add(200); arr.add(300); System.out.println(arr); l.addAll(arr); System.out.println(l); }}
[10, 15, 20]
[100, 200, 300]
[10, 15, 20, 100, 200, 300]
Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Initializing a List in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 221,
"s": 52,
"text": "This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator."
},
{
"code": null,
"e": 229,
"s": 221,
"text": "Syntax:"
},
{
"code": null,
"e": 258,
"s": 229,
"text": "boolean addAll(Collection c)"
},
{
"code": null,
"e": 374,
"s": 258,
"text": "Parameters: This function has a single parameter, i.e, Collection c, whose elements are to be appended to the list."
},
{
"code": null,
"e": 463,
"s": 374,
"text": "Returns: It returns true if the elements of specified list is appended and list changes."
},
{
"code": null,
"e": 518,
"s": 463,
"text": "Below programs show the implementation of this method."
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type arraylist List<Integer> l = new ArrayList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing a collection to be appended to list ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(100); arr.add(200); arr.add(300); System.out.println(arr); l.addAll(arr); System.out.println(l); }}",
"e": 1164,
"s": 529,
"text": null
},
{
"code": null,
"e": 1222,
"s": 1164,
"text": "[10, 15, 20]\n[100, 200, 300]\n[10, 15, 20, 100, 200, 300]\n"
},
{
"code": null,
"e": 1309,
"s": 1222,
"text": "Program 2: Below is the code to show implementation of list.addAll() using Linkedlist."
},
{
"code": "// Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing a collection to be appended to list ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(100); arr.add(200); arr.add(300); System.out.println(arr); l.addAll(arr); System.out.println(l); }}",
"e": 1946,
"s": 1309,
"text": null
},
{
"code": null,
"e": 2004,
"s": 1946,
"text": "[10, 15, 20]\n[100, 200, 300]\n[10, 15, 20, 100, 200, 300]\n"
},
{
"code": null,
"e": 2026,
"s": 2004,
"text": "Reference:Oracle Docs"
},
{
"code": null,
"e": 2046,
"s": 2026,
"text": "Java - util package"
},
{
"code": null,
"e": 2063,
"s": 2046,
"text": "Java-Collections"
},
{
"code": null,
"e": 2078,
"s": 2063,
"text": "Java-Functions"
},
{
"code": null,
"e": 2088,
"s": 2078,
"text": "java-list"
},
{
"code": null,
"e": 2093,
"s": 2088,
"text": "Java"
},
{
"code": null,
"e": 2098,
"s": 2093,
"text": "Java"
},
{
"code": null,
"e": 2115,
"s": 2098,
"text": "Java-Collections"
},
{
"code": null,
"e": 2213,
"s": 2115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2232,
"s": 2213,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2250,
"s": 2232,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2270,
"s": 2250,
"text": "Collections in Java"
},
{
"code": null,
"e": 2285,
"s": 2270,
"text": "Stream In Java"
},
{
"code": null,
"e": 2317,
"s": 2285,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2341,
"s": 2317,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2369,
"s": 2341,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 2389,
"s": 2369,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 2410,
"s": 2389,
"text": "Introduction to Java"
}
]
|
Working with Excel Spreadsheets in Python | 12 May, 2021
You all must have worked with Excel at some time in your life and must have felt the need for automating some repetitive or tedious task. Don’t worry in this tutorial we are going to learn about how to work with Excel using Python, or automating Excel using Python. We will be covering this with the help of the Openpyxl module.
Openpyxl is a Python library that provides various methods to interact with Excel Files using Python. It allows operations like reading, writing, arithmetic operations, plotting graphs, etc.
This module does not come in-built with Python. To install this type the below command in the terminal.
pip install openpyxl
To read an Excel file you have to open the spreadsheet using the load_workbook() method. After that, you can use the active to select the first sheet available and the cell attribute to select the cell by passing the row and column parameter. The value attribute prints the value of the particular cell. See the below example to get a better understanding.
Note: The first row or column integer is 1, not 0.
Dataset Used: It can be downloaded from here.
Example:
Python3
# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = "gfg.xlsx" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Cell objects also have a row, column, # and coordinate attributes that provide # location information for the cell. # Note: The first row or # column integer is 1, not 0. # Cell object is created by using # sheet object's cell() method. cell_obj = sheet_obj.cell(row = 1, column = 1) # Print value of cell object # using the value attribute print(cell_obj.value)
Output:
Name
There can be two ways of reading from multiple cells.
Method 1: We can get the count of the total rows and columns using the max_row and max_column respectively. We can use these values inside the for loop to get the value of the desired row or column or any cell depending upon the situation. Let’s see how to get the value of the first column and first row.
Example:
Python3
# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = "gfg.xlsx" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Getting the value of maximum rows# and columnrow = sheet_obj.max_rowcolumn = sheet_obj.max_column print("Total Rows:", row)print("Total Columns:", column) # printing the value of first column# Loop will print all values # of first column print("\nValue of first column")for i in range(1, row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) print(cell_obj.value) # printing the value of first column# Loop will print all values # of first rowprint("\nValue of first row")for i in range(1, column + 1): cell_obj = sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = " ")
Output:
Total Rows: 6
Total Columns: 4
Value of first column
Name
Ankit
Rahul
Priya
Nikhil
Nisha
Value of first row
Ankit B.Tech CSE 4
Method 2: We can also read from multiple cells using the cell name. This can be seen as the list slicing of Python.
Python3
# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = "gfg.xlsx" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Cell object is created by using # sheet object's cell() method. cell_obj = sheet_obj['A1': 'B6'] # Print value of cell object # using the value attribute for cell1, cell2 in cell_obj: print(cell1.value, cell2.value)
Output:
Name Course
Ankit B.Tech
Rahul M.Tech
Priya MBA
Nikhil B.Tech
Nisha B.Tech
Refer to the below article to get detailed information about reading excel files using openpyxl.
Reading an excel file using Python openpyxl module
First, let’s create a new spreadsheet, and then we will write some data to the newly created file. An empty spreadsheet can be created using the Workbook() method. Let’s see the below example.
Example:
Python3
from openpyxl import Workbook # Call a Workbook() function of openpyxl # to create a new blank Workbook object workbook = Workbook() # Anytime you modify the Workbook object # or its sheets and cells, the spreadsheet # file will not be saved until you call # the save() workbook method. workbook.save(filename="sample.xlsx")
Output:
After creating an empty file, let’s see how to add some data to it using Python. To add data first we need to select the active sheet and then using the cell() method we can select any particular cell by passing the row and column number as its parameter. We can also write using cell names. See the below example for a better understanding.
Example:
Python3
# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute sheet = wb.active # Cell objects also have row, column # and coordinate attributes that provide # location information for the cell. # Note: The first row or column integer # is 1, not 0. Cell object is created by # using sheet object's cell() method. c1 = sheet.cell(row = 1, column = 1) # writing values to cells c1.value = "Hello" c2 = sheet.cell(row= 1 , column = 2) c2.value = "World" # Once have a Worksheet object, one can # access a cell object by its name also. # A2 means column = 1 & row = 2. c3 = sheet['A2'] c3.value = "Welcome" # B2 means column = 2 & row = 2. c4 = sheet['B2'] c4.value = "Everyone" # Anytime you modify the Workbook object # or its sheets and cells, the spreadsheet # file will not be saved until you call # the save() workbook method. wb.save("sample.xlsx")
Output:
Refer to the below article to get detailed information about writing to excel.
Writing to an excel file using openpyxl module
In the above example, you will see that every time you try to write to a spreadsheet the existing data gets overwritten, and the file is saved as a new file. This happens because the Workbook() method always creates a new workbook file object. To write to an existing workbook you must open the file with the load_workbook() method. We will use the above-created workbook.
Example:
Python3
# import openpyxl module import openpyxl wb = openpyxl.load_workbook("sample.xlsx") sheet = wb.active c = sheet['A3'] c.value = "New Data" wb.save("sample.xlsx")
Output:
We can also use the append() method to append multiple data at the end of the sheet.
Example:
Python3
# import openpyxl module import openpyxl wb = openpyxl.load_workbook("sample.xlsx") sheet = wb.active data = ( (1, 2, 3), (4, 5, 6)) for row in data: sheet.append(row) wb.save('sample.xlsx')
Output:
Arithmetic operations can be performed by typing the formula in a particular cell of the spreadsheet. For example, if we want to find the sum then =Sum() formula of the excel file is used.
Example:
Python3
# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # writing to the cell of an excel sheet sheet['A1'] = 200sheet['A2'] = 300sheet['A3'] = 400sheet['A4'] = 500sheet['A5'] = 600 # The value in cell A7 is set to a formula # that sums the values in A1, A2, A3, A4, A5 . sheet['A7'] = '= SUM(A1:A5)' # save the file wb.save("sum.xlsx")
Output:
Refer to the below article to get detailed information about the Arithmetic operations on Spreadsheet.
Arithmetic operations in excel file using openpyxl
Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimensions contains ColumnDimension objects. In row_dimensions, one can access one of the objects using the number of the row (in this case, 1 or 2). In column_dimensions, one can access one of the objects using the letter of the column (in this case, A or B).
Example:
Python3
# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # writing to the specified cell sheet.cell(row = 1, column = 1).value = ' hello ' sheet.cell(row = 2, column = 2).value = ' everyone ' # set the height of the row sheet.row_dimensions[1].height = 70 # set the width of the column sheet.column_dimensions['B'].width = 20 # save the file wb.save('sample.xlsx')
Output:
A rectangular area of cells can be merged into a single cell with the merge_cells() sheet method. The argument to merge_cells() is a single string of the top-left and bottom-right cells of the rectangular area to be merged.
Example:
Python3
import openpyxl wb = openpyxl.Workbook() sheet = wb.active # merge cell from A2 to D4 i.e. # A2, B2, C2, D2, A3, B3, C3, D3, A4, B4, C4 and D4 . # A2:D4' merges 12 cells into a single cell. sheet.merge_cells('A2:D4') sheet.cell(row = 2, column = 1).value = 'Twelve cells join together.' # merge cell C6 and D6 sheet.merge_cells('C6:D6') sheet.cell(row = 6, column = 6).value = 'Two merge cells.' wb.save('sample.xlsx')
Output:
To unmerge cells, call the unmerge_cells() sheet method.
Example:
Python3
import openpyxl wb = openpyxl.load_workbook('sample.xlsx') sheet = wb.active # unmerge the cells sheet.unmerge_cells('A2:D4') sheet.unmerge_cells('C6:D6') wb.save('sample.xlsx')
Output:
To customize font styles in cells, important, import the Font() function from the openpyxl.styles module.
Example:
Python3
import openpyxl # import Font function from openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb.active sheet.cell(row = 1, column = 1).value = "GeeksforGeeks" # set the size of the cell to 24 sheet.cell(row = 1, column = 1).font = Font(size = 24 ) sheet.cell(row = 2, column = 2).value = "GeeksforGeeks" # set the font style to italic sheet.cell(row = 2, column = 2).font = Font(size = 24, italic = True) sheet.cell(row = 3, column = 3).value = "GeeksforGeeks" # set the font style to bold sheet.cell(row = 3, column = 3).font = Font(size = 24, bold = True) sheet.cell(row = 4, column = 4).value = "GeeksforGeeks" # set the font name to 'Times New Roman' sheet.cell(row = 4, column = 4).font = Font(size = 24, name = 'Times New Roman') wb.save('sample.xlsx')
Output:
Refer to the below article to get detailed information about adjusting rows and columns.
Adjusting rows and columns of an excel file using openpyxl module
Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart objects of specific chart class( i.e BarChart, LineChart, etc.). After creating chart objects, insert data in it, and lastly, add that chart object in the sheet object.
Example 1:
Python3
# import openpyxl moduleimport openpyxl # import BarChart class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart, Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet# from the active attribute.sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) # create data for plottingvalues = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) # Create object of BarChart classchart = BarChart() # adding data to the Bar chart objectchart.add_data(values) # set the title of the chartchart.title = " BAR-CHART " # set the title of the x-axischart.x_axis.title = " X_AXIS " # set the title of the y-axischart.y_axis.title = " Y_AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("sample.xlsx")
Output:
Example 2:
Python3
# import openpyxl moduleimport openpyxl # import LineChart class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart, Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) # Create object of LineChart classchart = LineChart() chart.add_data(values) # set the title of the chartchart.title = " LINE-CHART " # set the title of the x-axischart.x_axis.title = " X-AXIS " # set the title of the y-axischart.y_axis.title = " Y-AXIS " # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, "E2") # save the filewb.save("sample.xlsx")
Output:
Refer to the below articles to get detailed information about plotting in excel using Python.
Plotting charts in excel sheet using openpyxl module | Set 1
Plotting charts in excel sheet using openpyxl module | Set 2
Plotting charts in excel sheet using openpyxl module | Set 3
For the purpose of importing images inside our worksheet, we would be using openpyxl.drawing.image.Image. The method is a wrapper over PIL.Image method found in PIL (pillow) library. Due to which it is necessary for the PIL (pillow) library to be installed in order to use this method.
Image Used:
Example:
Python3
import openpyxl from openpyxl.drawing.image import Image wb = openpyxl.Workbook() sheet = wb.active # Adding a row of data to the worksheet (used to # distinguish previous excel data from the image) sheet.append([10, 2010, "Geeks", 4, "life"]) # A wrapper over PIL.Image, used to provide image # inclusion properties to openpyxl library img = Image("geek.jpg") # Adding the image to the worksheet # (with attributes like position) sheet.add_image(img, 'A2') # Saving the workbook createdwb.save('sample.xlsx')
Output:
Refer to the below article to get detailed information about adding images.
Openpyxl – Adding Image
How to delete one or more rows in excel using Openpyxl?
Trigonometric operations in excel file using openpyxl
How to copy data from one excel sheet to another
How to Automate an Excel Sheet in Python?
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 357,
"s": 28,
"text": "You all must have worked with Excel at some time in your life and must have felt the need for automating some repetitive or tedious task. Don’t worry in this tutorial we are going to learn about how to work with Excel using Python, or automating Excel using Python. We will be covering this with the help of the Openpyxl module."
},
{
"code": null,
"e": 550,
"s": 359,
"text": "Openpyxl is a Python library that provides various methods to interact with Excel Files using Python. It allows operations like reading, writing, arithmetic operations, plotting graphs, etc."
},
{
"code": null,
"e": 654,
"s": 550,
"text": "This module does not come in-built with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 675,
"s": 654,
"text": "pip install openpyxl"
},
{
"code": null,
"e": 1033,
"s": 675,
"text": "To read an Excel file you have to open the spreadsheet using the load_workbook() method. After that, you can use the active to select the first sheet available and the cell attribute to select the cell by passing the row and column parameter. The value attribute prints the value of the particular cell. See the below example to get a better understanding. "
},
{
"code": null,
"e": 1084,
"s": 1033,
"text": "Note: The first row or column integer is 1, not 0."
},
{
"code": null,
"e": 1130,
"s": 1084,
"text": "Dataset Used: It can be downloaded from here."
},
{
"code": null,
"e": 1139,
"s": 1130,
"text": "Example:"
},
{
"code": null,
"e": 1147,
"s": 1139,
"text": "Python3"
},
{
"code": "# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = \"gfg.xlsx\" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Cell objects also have a row, column, # and coordinate attributes that provide # location information for the cell. # Note: The first row or # column integer is 1, not 0. # Cell object is created by using # sheet object's cell() method. cell_obj = sheet_obj.cell(row = 1, column = 1) # Print value of cell object # using the value attribute print(cell_obj.value) ",
"e": 1837,
"s": 1147,
"text": null
},
{
"code": null,
"e": 1845,
"s": 1837,
"text": "Output:"
},
{
"code": null,
"e": 1850,
"s": 1845,
"text": "Name"
},
{
"code": null,
"e": 1905,
"s": 1850,
"text": "There can be two ways of reading from multiple cells. "
},
{
"code": null,
"e": 2211,
"s": 1905,
"text": "Method 1: We can get the count of the total rows and columns using the max_row and max_column respectively. We can use these values inside the for loop to get the value of the desired row or column or any cell depending upon the situation. Let’s see how to get the value of the first column and first row."
},
{
"code": null,
"e": 2220,
"s": 2211,
"text": "Example:"
},
{
"code": null,
"e": 2228,
"s": 2220,
"text": "Python3"
},
{
"code": "# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = \"gfg.xlsx\" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Getting the value of maximum rows# and columnrow = sheet_obj.max_rowcolumn = sheet_obj.max_column print(\"Total Rows:\", row)print(\"Total Columns:\", column) # printing the value of first column# Loop will print all values # of first column print(\"\\nValue of first column\")for i in range(1, row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) print(cell_obj.value) # printing the value of first column# Loop will print all values # of first rowprint(\"\\nValue of first row\")for i in range(1, column + 1): cell_obj = sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = \" \")",
"e": 3159,
"s": 2228,
"text": null
},
{
"code": null,
"e": 3167,
"s": 3159,
"text": "Output:"
},
{
"code": null,
"e": 3298,
"s": 3167,
"text": "Total Rows: 6\nTotal Columns: 4\n\nValue of first column\nName\nAnkit\nRahul\nPriya\nNikhil\nNisha\n\nValue of first row\nAnkit B.Tech CSE 4 "
},
{
"code": null,
"e": 3414,
"s": 3298,
"text": "Method 2: We can also read from multiple cells using the cell name. This can be seen as the list slicing of Python."
},
{
"code": null,
"e": 3422,
"s": 3414,
"text": "Python3"
},
{
"code": "# Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = \"gfg.xlsx\" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Cell object is created by using # sheet object's cell() method. cell_obj = sheet_obj['A1': 'B6'] # Print value of cell object # using the value attribute for cell1, cell2 in cell_obj: print(cell1.value, cell2.value)",
"e": 3962,
"s": 3422,
"text": null
},
{
"code": null,
"e": 3970,
"s": 3962,
"text": "Output:"
},
{
"code": null,
"e": 4046,
"s": 3970,
"text": "Name Course\nAnkit B.Tech\nRahul M.Tech\nPriya MBA\nNikhil B.Tech\nNisha B.Tech"
},
{
"code": null,
"e": 4143,
"s": 4046,
"text": "Refer to the below article to get detailed information about reading excel files using openpyxl."
},
{
"code": null,
"e": 4194,
"s": 4143,
"text": "Reading an excel file using Python openpyxl module"
},
{
"code": null,
"e": 4387,
"s": 4194,
"text": "First, let’s create a new spreadsheet, and then we will write some data to the newly created file. An empty spreadsheet can be created using the Workbook() method. Let’s see the below example."
},
{
"code": null,
"e": 4396,
"s": 4387,
"text": "Example:"
},
{
"code": null,
"e": 4404,
"s": 4396,
"text": "Python3"
},
{
"code": "from openpyxl import Workbook # Call a Workbook() function of openpyxl # to create a new blank Workbook object workbook = Workbook() # Anytime you modify the Workbook object # or its sheets and cells, the spreadsheet # file will not be saved until you call # the save() workbook method. workbook.save(filename=\"sample.xlsx\")",
"e": 4732,
"s": 4404,
"text": null
},
{
"code": null,
"e": 4740,
"s": 4732,
"text": "Output:"
},
{
"code": null,
"e": 5082,
"s": 4740,
"text": "After creating an empty file, let’s see how to add some data to it using Python. To add data first we need to select the active sheet and then using the cell() method we can select any particular cell by passing the row and column number as its parameter. We can also write using cell names. See the below example for a better understanding."
},
{
"code": null,
"e": 5091,
"s": 5082,
"text": "Example:"
},
{
"code": null,
"e": 5099,
"s": 5091,
"text": "Python3"
},
{
"code": "# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute sheet = wb.active # Cell objects also have row, column # and coordinate attributes that provide # location information for the cell. # Note: The first row or column integer # is 1, not 0. Cell object is created by # using sheet object's cell() method. c1 = sheet.cell(row = 1, column = 1) # writing values to cells c1.value = \"Hello\" c2 = sheet.cell(row= 1 , column = 2) c2.value = \"World\" # Once have a Worksheet object, one can # access a cell object by its name also. # A2 means column = 1 & row = 2. c3 = sheet['A2'] c3.value = \"Welcome\" # B2 means column = 2 & row = 2. c4 = sheet['B2'] c4.value = \"Everyone\" # Anytime you modify the Workbook object # or its sheets and cells, the spreadsheet # file will not be saved until you call # the save() workbook method. wb.save(\"sample.xlsx\") ",
"e": 6108,
"s": 5099,
"text": null
},
{
"code": null,
"e": 6116,
"s": 6108,
"text": "Output:"
},
{
"code": null,
"e": 6195,
"s": 6116,
"text": "Refer to the below article to get detailed information about writing to excel."
},
{
"code": null,
"e": 6242,
"s": 6195,
"text": "Writing to an excel file using openpyxl module"
},
{
"code": null,
"e": 6615,
"s": 6242,
"text": "In the above example, you will see that every time you try to write to a spreadsheet the existing data gets overwritten, and the file is saved as a new file. This happens because the Workbook() method always creates a new workbook file object. To write to an existing workbook you must open the file with the load_workbook() method. We will use the above-created workbook."
},
{
"code": null,
"e": 6624,
"s": 6615,
"text": "Example:"
},
{
"code": null,
"e": 6632,
"s": 6624,
"text": "Python3"
},
{
"code": "# import openpyxl module import openpyxl wb = openpyxl.load_workbook(\"sample.xlsx\") sheet = wb.active c = sheet['A3'] c.value = \"New Data\" wb.save(\"sample.xlsx\")",
"e": 6801,
"s": 6632,
"text": null
},
{
"code": null,
"e": 6809,
"s": 6801,
"text": "Output:"
},
{
"code": null,
"e": 6894,
"s": 6809,
"text": "We can also use the append() method to append multiple data at the end of the sheet."
},
{
"code": null,
"e": 6903,
"s": 6894,
"text": "Example:"
},
{
"code": null,
"e": 6911,
"s": 6903,
"text": "Python3"
},
{
"code": "# import openpyxl module import openpyxl wb = openpyxl.load_workbook(\"sample.xlsx\") sheet = wb.active data = ( (1, 2, 3), (4, 5, 6)) for row in data: sheet.append(row) wb.save('sample.xlsx')",
"e": 7119,
"s": 6911,
"text": null
},
{
"code": null,
"e": 7127,
"s": 7119,
"text": "Output:"
},
{
"code": null,
"e": 7316,
"s": 7127,
"text": "Arithmetic operations can be performed by typing the formula in a particular cell of the spreadsheet. For example, if we want to find the sum then =Sum() formula of the excel file is used."
},
{
"code": null,
"e": 7325,
"s": 7316,
"text": "Example:"
},
{
"code": null,
"e": 7333,
"s": 7325,
"text": "Python3"
},
{
"code": "# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # writing to the cell of an excel sheet sheet['A1'] = 200sheet['A2'] = 300sheet['A3'] = 400sheet['A4'] = 500sheet['A5'] = 600 # The value in cell A7 is set to a formula # that sums the values in A1, A2, A3, A4, A5 . sheet['A7'] = '= SUM(A1:A5)' # save the file wb.save(\"sum.xlsx\") ",
"e": 7845,
"s": 7333,
"text": null
},
{
"code": null,
"e": 7853,
"s": 7845,
"text": "Output:"
},
{
"code": null,
"e": 7956,
"s": 7853,
"text": "Refer to the below article to get detailed information about the Arithmetic operations on Spreadsheet."
},
{
"code": null,
"e": 8007,
"s": 7956,
"text": "Arithmetic operations in excel file using openpyxl"
},
{
"code": null,
"e": 8514,
"s": 8007,
"text": "Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimensions contains ColumnDimension objects. In row_dimensions, one can access one of the objects using the number of the row (in this case, 1 or 2). In column_dimensions, one can access one of the objects using the letter of the column (in this case, A or B)."
},
{
"code": null,
"e": 8523,
"s": 8514,
"text": "Example:"
},
{
"code": null,
"e": 8531,
"s": 8523,
"text": "Python3"
},
{
"code": "# import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # writing to the specified cell sheet.cell(row = 1, column = 1).value = ' hello ' sheet.cell(row = 2, column = 2).value = ' everyone ' # set the height of the row sheet.row_dimensions[1].height = 70 # set the width of the column sheet.column_dimensions['B'].width = 20 # save the file wb.save('sample.xlsx') ",
"e": 9072,
"s": 8531,
"text": null
},
{
"code": null,
"e": 9080,
"s": 9072,
"text": "Output:"
},
{
"code": null,
"e": 9304,
"s": 9080,
"text": "A rectangular area of cells can be merged into a single cell with the merge_cells() sheet method. The argument to merge_cells() is a single string of the top-left and bottom-right cells of the rectangular area to be merged."
},
{
"code": null,
"e": 9313,
"s": 9304,
"text": "Example:"
},
{
"code": null,
"e": 9321,
"s": 9313,
"text": "Python3"
},
{
"code": "import openpyxl wb = openpyxl.Workbook() sheet = wb.active # merge cell from A2 to D4 i.e. # A2, B2, C2, D2, A3, B3, C3, D3, A4, B4, C4 and D4 . # A2:D4' merges 12 cells into a single cell. sheet.merge_cells('A2:D4') sheet.cell(row = 2, column = 1).value = 'Twelve cells join together.' # merge cell C6 and D6 sheet.merge_cells('C6:D6') sheet.cell(row = 6, column = 6).value = 'Two merge cells.' wb.save('sample.xlsx')",
"e": 9748,
"s": 9321,
"text": null
},
{
"code": null,
"e": 9756,
"s": 9748,
"text": "Output:"
},
{
"code": null,
"e": 9813,
"s": 9756,
"text": "To unmerge cells, call the unmerge_cells() sheet method."
},
{
"code": null,
"e": 9822,
"s": 9813,
"text": "Example:"
},
{
"code": null,
"e": 9830,
"s": 9822,
"text": "Python3"
},
{
"code": "import openpyxl wb = openpyxl.load_workbook('sample.xlsx') sheet = wb.active # unmerge the cells sheet.unmerge_cells('A2:D4') sheet.unmerge_cells('C6:D6') wb.save('sample.xlsx')",
"e": 10018,
"s": 9830,
"text": null
},
{
"code": null,
"e": 10026,
"s": 10018,
"text": "Output:"
},
{
"code": null,
"e": 10132,
"s": 10026,
"text": "To customize font styles in cells, important, import the Font() function from the openpyxl.styles module."
},
{
"code": null,
"e": 10141,
"s": 10132,
"text": "Example:"
},
{
"code": null,
"e": 10149,
"s": 10141,
"text": "Python3"
},
{
"code": "import openpyxl # import Font function from openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb.active sheet.cell(row = 1, column = 1).value = \"GeeksforGeeks\" # set the size of the cell to 24 sheet.cell(row = 1, column = 1).font = Font(size = 24 ) sheet.cell(row = 2, column = 2).value = \"GeeksforGeeks\" # set the font style to italic sheet.cell(row = 2, column = 2).font = Font(size = 24, italic = True) sheet.cell(row = 3, column = 3).value = \"GeeksforGeeks\" # set the font style to bold sheet.cell(row = 3, column = 3).font = Font(size = 24, bold = True) sheet.cell(row = 4, column = 4).value = \"GeeksforGeeks\" # set the font name to 'Times New Roman' sheet.cell(row = 4, column = 4).font = Font(size = 24, name = 'Times New Roman') wb.save('sample.xlsx') ",
"e": 10955,
"s": 10149,
"text": null
},
{
"code": null,
"e": 10963,
"s": 10955,
"text": "Output:"
},
{
"code": null,
"e": 11052,
"s": 10963,
"text": "Refer to the below article to get detailed information about adjusting rows and columns."
},
{
"code": null,
"e": 11118,
"s": 11052,
"text": "Adjusting rows and columns of an excel file using openpyxl module"
},
{
"code": null,
"e": 11485,
"s": 11118,
"text": "Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart objects of specific chart class( i.e BarChart, LineChart, etc.). After creating chart objects, insert data in it, and lastly, add that chart object in the sheet object."
},
{
"code": null,
"e": 11496,
"s": 11485,
"text": "Example 1:"
},
{
"code": null,
"e": 11504,
"s": 11496,
"text": "Python3"
},
{
"code": "# import openpyxl moduleimport openpyxl # import BarChart class from openpyxl.chart sub_modulefrom openpyxl.chart import BarChart, Reference # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet# from the active attribute.sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) # create data for plottingvalues = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) # Create object of BarChart classchart = BarChart() # adding data to the Bar chart objectchart.add_data(values) # set the title of the chartchart.title = \" BAR-CHART \" # set the title of the x-axischart.x_axis.title = \" X_AXIS \" # set the title of the y-axischart.y_axis.title = \" Y_AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"sample.xlsx\")",
"e": 12477,
"s": 11504,
"text": null
},
{
"code": null,
"e": 12485,
"s": 12477,
"text": "Output:"
},
{
"code": null,
"e": 12496,
"s": 12485,
"text": "Example 2:"
},
{
"code": null,
"e": 12504,
"s": 12496,
"text": "Python3"
},
{
"code": "# import openpyxl moduleimport openpyxl # import LineChart class from openpyxl.chart sub_modulefrom openpyxl.chart import LineChart, Reference wb = openpyxl.Workbook()sheet = wb.active # write o to 9 in 1st column of the active sheetfor i in range(10): sheet.append([i]) values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) # Create object of LineChart classchart = LineChart() chart.add_data(values) # set the title of the chartchart.title = \" LINE-CHART \" # set the title of the x-axischart.x_axis.title = \" X-AXIS \" # set the title of the y-axischart.y_axis.title = \" Y-AXIS \" # add chart to the sheet# the top-left corner of a chart# is anchored to cell E2 .sheet.add_chart(chart, \"E2\") # save the filewb.save(\"sample.xlsx\")",
"e": 13283,
"s": 12504,
"text": null
},
{
"code": null,
"e": 13291,
"s": 13283,
"text": "Output:"
},
{
"code": null,
"e": 13385,
"s": 13291,
"text": "Refer to the below articles to get detailed information about plotting in excel using Python."
},
{
"code": null,
"e": 13447,
"s": 13385,
"text": "Plotting charts in excel sheet using openpyxl module | Set 1"
},
{
"code": null,
"e": 13509,
"s": 13447,
"text": "Plotting charts in excel sheet using openpyxl module | Set 2"
},
{
"code": null,
"e": 13570,
"s": 13509,
"text": "Plotting charts in excel sheet using openpyxl module | Set 3"
},
{
"code": null,
"e": 13856,
"s": 13570,
"text": "For the purpose of importing images inside our worksheet, we would be using openpyxl.drawing.image.Image. The method is a wrapper over PIL.Image method found in PIL (pillow) library. Due to which it is necessary for the PIL (pillow) library to be installed in order to use this method."
},
{
"code": null,
"e": 13868,
"s": 13856,
"text": "Image Used:"
},
{
"code": null,
"e": 13877,
"s": 13868,
"text": "Example:"
},
{
"code": null,
"e": 13885,
"s": 13877,
"text": "Python3"
},
{
"code": "import openpyxl from openpyxl.drawing.image import Image wb = openpyxl.Workbook() sheet = wb.active # Adding a row of data to the worksheet (used to # distinguish previous excel data from the image) sheet.append([10, 2010, \"Geeks\", 4, \"life\"]) # A wrapper over PIL.Image, used to provide image # inclusion properties to openpyxl library img = Image(\"geek.jpg\") # Adding the image to the worksheet # (with attributes like position) sheet.add_image(img, 'A2') # Saving the workbook createdwb.save('sample.xlsx')",
"e": 14404,
"s": 13885,
"text": null
},
{
"code": null,
"e": 14412,
"s": 14404,
"text": "Output:"
},
{
"code": null,
"e": 14488,
"s": 14412,
"text": "Refer to the below article to get detailed information about adding images."
},
{
"code": null,
"e": 14512,
"s": 14488,
"text": "Openpyxl – Adding Image"
},
{
"code": null,
"e": 14568,
"s": 14512,
"text": "How to delete one or more rows in excel using Openpyxl?"
},
{
"code": null,
"e": 14622,
"s": 14568,
"text": "Trigonometric operations in excel file using openpyxl"
},
{
"code": null,
"e": 14671,
"s": 14622,
"text": "How to copy data from one excel sheet to another"
},
{
"code": null,
"e": 14713,
"s": 14671,
"text": "How to Automate an Excel Sheet in Python?"
},
{
"code": null,
"e": 14720,
"s": 14713,
"text": "Python"
}
]
|
TypeScript | Array splice() Method | 18 Jun, 2020
The Array.splice() is an inbuilt TypeScript function which is used to change the content of an array, adding new elements while removing old elements.Syntax:
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter: This method accept three parameter as mentioned above and described below:
index : This parameter is the index at which to start changing the array.
howMany : This parameter is the integer indicating the number of old array elements to remove.
element1, ..., elementN : This parameter is the elements to add to the array.
Return Value: This method returns the extracted array. Below example illustrate the Array splice() method in TypeScriptJS:Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of splice() method var removed = arr.splice(2, 0, 11); // printing console.log(removed);</script>
Output:
[]
Example 2:
JavaScript
<script> // Driver code var arr = ["G", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]; var val; // use of splice() method val = arr.splice(0,5); console.log( val ); console.log( arr );</script>
Output:
[ 'G', 'e', 'e', 'k', 's' ]
[ 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' ]
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "The Array.splice() is an inbuilt TypeScript function which is used to change the content of an array, adding new elements while removing old elements.Syntax: "
},
{
"code": null,
"e": 247,
"s": 187,
"text": "array.splice(index, howMany, [element1][, ..., elementN]); "
},
{
"code": null,
"e": 334,
"s": 247,
"text": "Parameter: This method accept three parameter as mentioned above and described below: "
},
{
"code": null,
"e": 408,
"s": 334,
"text": "index : This parameter is the index at which to start changing the array."
},
{
"code": null,
"e": 503,
"s": 408,
"text": "howMany : This parameter is the integer indicating the number of old array elements to remove."
},
{
"code": null,
"e": 581,
"s": 503,
"text": "element1, ..., elementN : This parameter is the elements to add to the array."
},
{
"code": null,
"e": 716,
"s": 581,
"text": "Return Value: This method returns the extracted array. Below example illustrate the Array splice() method in TypeScriptJS:Example 1: "
},
{
"code": null,
"e": 727,
"s": 716,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of splice() method var removed = arr.splice(2, 0, 11); // printing console.log(removed);</script>",
"e": 918,
"s": 727,
"text": null
},
{
"code": null,
"e": 927,
"s": 918,
"text": "Output: "
},
{
"code": null,
"e": 931,
"s": 927,
"text": "[]\n"
},
{
"code": null,
"e": 943,
"s": 931,
"text": "Example 2: "
},
{
"code": null,
"e": 954,
"s": 943,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [\"G\", \"e\", \"e\", \"k\", \"s\", \"f\", \"o\", \"r\", \"g\", \"e\", \"e\", \"k\", \"s\"]; var val; // use of splice() method val = arr.splice(0,5); console.log( val ); console.log( arr );</script>",
"e": 1203,
"s": 954,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1203,
"text": "Output: "
},
{
"code": null,
"e": 1284,
"s": 1212,
"text": "[ 'G', 'e', 'e', 'k', 's' ]\n[ 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' ]\n"
},
{
"code": null,
"e": 1297,
"s": 1286,
"text": "TypeScript"
},
{
"code": null,
"e": 1308,
"s": 1297,
"text": "JavaScript"
},
{
"code": null,
"e": 1325,
"s": 1308,
"text": "Web Technologies"
},
{
"code": null,
"e": 1423,
"s": 1325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1484,
"s": 1423,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1556,
"s": 1484,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1596,
"s": 1556,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1637,
"s": 1596,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1689,
"s": 1637,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1722,
"s": 1689,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1784,
"s": 1722,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1845,
"s": 1784,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1895,
"s": 1845,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Permutation with Spaces | Practice | GeeksforGeeks | Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. The output should be printed in sorted increasing order of strings
Example 1:
Input:
S = "ABC"
Output: (A B C)(A BC)(AB C)(ABC)
Explanation:
ABC
AB C
A BC
A B C
These are the possible combination of "ABC".
Example 2:
Input:
S = "AB"
Output: (A B)(AB)
Your Task:
You don't need to read input or print anything. Your task is to complete the function permutation() which takes the string S as input parameters and returns the sorted array of the string denoting the different permutation (DON'T ADD '(' and ')' it will be handled by the driver code only).
Expected Time Complexity: O(2^n)
Expected Auxiliary Space: O(1)
CONSTRAINTS:
1 <= |S| < 10
S only contains lowercase and Uppercase English letters.
0
samyakm511 week ago
Python solution in 0.03/1.02 secs
def solve(self,n,ip,op,l):
if len(op)==0:
l.append(ip)
return
if len(op)==n:
self.solve(n,ip+op[0],op[1:],l)
else:
self.solve(n,ip+' '+op[0],op[1:],l)
self.solve(n,ip+op[0],op[1:],l)
def permutation (self, S):
# code here
n=len(S)
l=[]
self.solve(n,'',S,l)
return l
0
mrpalashbharati2 weeks ago
C++ || Run Time : 0.01
vector<string> v;
void solve(string s, string output){
if(s.empty()){
v.push_back(output);
return;
}
output.push_back(' ');
output.push_back(s[0]);
solve(s.substr(1),output);
output.pop_back();
output.pop_back();
output.push_back(s[0]);
solve(s.substr(1),output);
}
vector<string> permutation(string s){
// Code Here
// vector<string> v;
string output="";
output.push_back(s[0]);
solve(s.substr(1),output);
return v;
}
0
hellosoham20012 weeks ago
Python Solution - 0.06 seconds :
class Solution:
def permutation (self, S):
ip=S
op=''
ans=[]
def solve(ip,op):
if len(ip)==0:
ans.append(op)
return
op1=op
op2=op
op1=op1+ip[0]
op2=op2+ip[0]+' '
ip=ip[1:]
solve(ip,op1)
solve(ip,op2)
solve(ip,op)
for i in ans:
if i[-1]==' ':
ans.remove(i)
ans.sort()
return ans
0
piyush9534972 weeks ago
Java 0.36/1.48
ArrayList<String> permutation(String S){ if(S.length() == 0){ ArrayList<String> a = new ArrayList<>(); a.add(""); return a; }
char ch = S.charAt(0); ArrayList<String> b = permutation(S.substring(1));
ArrayList<String> ans = new ArrayList<>();
for(String s1 : b){ if(!s1.isEmpty()) ans.add(ch + " " + s1); }
for(String s1 : b){ ans.add(ch + s1); } return ans; }
0
damamrajeev2 weeks ago
Easy solution using c++ - 0.01 seconds
void helper(string s,string out,vector<string> &res){
if(s.length()==0){
res.push_back(out);
return;
}
// including space
helper(s.substr(1),out+" "+s[0],res);
// without space
helper(s.substr(1),out+s[0],res);
}
vector<string> permutation(string s){
// Code Here
vector<string> out;
// if string length is 0 then no need to do anything
if(s.length()==0){
return out;
}
// store is just used to convert char to string
string store="";
store+=s[0];
// passing first char of string inorder to reduce complication in recursive calls
// if we just pass s[0] to helper functin in place of store we will be passing character instead of string
helper(s.substr(1),store,out);
return out;
}
0
rajsinghrathour02 weeks ago
void solve(string S, int index,vector<string>&s,string t){ if(index==S.length()) { s.push_back(t); return; } t+=S[index]; if(index<S.length()-1){t+=" "; solve(S,index+1,s,t);} if(index!=S.length()-1)t.pop_back(); solve(S,index+1,s,t);}
vector<string> permutation(string S){ vector<string>s; string t=""; solve(S,0,s,t); // sort(s.begin(),s.end()); return s; // Code Here }};
0
roytanupriya212 weeks ago
Using Aditya Verma's Approach:
#include<bits/stdc++.h>
using namespace std;
vector<string> subset(string ip, string op, vector<string> &ans){
//Base Condition
if(ip.size()==0){
ans.push_back(op);
return ans;
}
//Hypothesis
string op1=op;
string op2=op;
op2.push_back('_');
op2.push_back(ip[0]);
op1.push_back(ip[0]);
ip.erase(ip.begin()+0);
//Induction
subset(ip,op1,ans);
subset(ip,op2,ans);
return ans;
}
int main()
{
string ip;
cin>>ip;
string op="";
op.push_back(ip[0]);
ip.erase(ip.begin()+0);
vector<string> ans;
subset(ip,op,ans);
for(int i=0;i<ans.size();i++){
cout<<ans[i]<<" ";
}
return 0;
}
+2
avinashdhn19043 weeks ago
public:
void solve(vector<string>&ans,string s,int n,int i,string temp){
if(i==n){
ans.push_back(temp);
return;
}
if(s[i]==' '){
solve(ans,s,n,i+1,temp+' ');
solve(ans,s,n,i+1,temp);
return;
}
else {
solve(ans,s,n,i+1,temp+s[i]);
return;
}
return;
}
vector<string> permutation(string S){
vector<string>ans;
string s;
int n=S.length();
for(int i=0;i<n;i++){
s+=S[i];
if(i!=n-1)s+=' ';
}
solve(ans,s,s.length(),0,"");
return ans;
}
+1
lasthoneybadger4 weeks ago
C++
vector<string> res;
void perm(string &S, int i, string curr){
if(i == S.size()){
res.push_back(curr);
return;
}
if(i)
perm(S, i + 1, curr + " " + S[i]);
perm(S, i + 1, curr + S[i]);
}
vector<string> permutation(string S){
// Code Here
perm(S, 0, "");
return res;
}
0
swapniltayal1 month ago
void perWithSpace(string &s, vector<string> &ans, string ds, int index){ if(index == s.size()){ ans.push_back(ds); return; } perWithSpace(s, ans, ds+s[index], index+1); if(index != s.size()-1){ perWithSpace(s, ans, ds+s[index] + " ", index+1); } }
vector<string> permutation(string S){ // Code Here vector<string> ans; string ds; perWithSpace(S, ans, ds, 0); reverse(ans.begin(), ans.end()); 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 string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. The output should be printed in sorted increasing order of strings"
},
{
"code": null,
"e": 436,
"s": 425,
"text": "Example 1:"
},
{
"code": null,
"e": 564,
"s": 436,
"text": "Input:\nS = \"ABC\"\nOutput: (A B C)(A BC)(AB C)(ABC)\nExplanation:\nABC\nAB C\nA BC\nA B C\nThese are the possible combination of \"ABC\"."
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Example 2:"
},
{
"code": null,
"e": 612,
"s": 577,
"text": "Input:\nS = \"AB\"\nOutput: (A B)(AB)\n"
},
{
"code": null,
"e": 982,
"s": 612,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function permutation() which takes the string S as input parameters and returns the sorted array of the string denoting the different permutation (DON'T ADD '(' and ')' it will be handled by the driver code only).\n\nExpected Time Complexity: O(2^n)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1068,
"s": 984,
"text": "CONSTRAINTS:\n1 <= |S| < 10\nS only contains lowercase and Uppercase English letters."
},
{
"code": null,
"e": 1070,
"s": 1068,
"text": "0"
},
{
"code": null,
"e": 1090,
"s": 1070,
"text": "samyakm511 week ago"
},
{
"code": null,
"e": 1124,
"s": 1090,
"text": "Python solution in 0.03/1.02 secs"
},
{
"code": null,
"e": 1562,
"s": 1124,
"text": " def solve(self,n,ip,op,l):\n if len(op)==0:\n l.append(ip)\n return\n if len(op)==n:\n self.solve(n,ip+op[0],op[1:],l)\n else:\n self.solve(n,ip+' '+op[0],op[1:],l)\n self.solve(n,ip+op[0],op[1:],l)\n \n def permutation (self, S):\n # code here\n \n n=len(S)\n l=[]\n self.solve(n,'',S,l)\n return l\n \n "
},
{
"code": null,
"e": 1564,
"s": 1562,
"text": "0"
},
{
"code": null,
"e": 1591,
"s": 1564,
"text": "mrpalashbharati2 weeks ago"
},
{
"code": null,
"e": 1614,
"s": 1591,
"text": "C++ || Run Time : 0.01"
},
{
"code": null,
"e": 2250,
"s": 1614,
"text": "vector<string> v;\n \n void solve(string s, string output){\n \n if(s.empty()){\n v.push_back(output);\n return;\n }\n\n output.push_back(' ');\n output.push_back(s[0]);\n solve(s.substr(1),output);\n \n output.pop_back();\n output.pop_back();\n output.push_back(s[0]);\n solve(s.substr(1),output);\n\n }\n \n vector<string> permutation(string s){\n // Code Here\n // vector<string> v;\n \n string output=\"\";\n output.push_back(s[0]);\n \n solve(s.substr(1),output);\n \n return v;\n }"
},
{
"code": null,
"e": 2252,
"s": 2250,
"text": "0"
},
{
"code": null,
"e": 2278,
"s": 2252,
"text": "hellosoham20012 weeks ago"
},
{
"code": null,
"e": 2311,
"s": 2278,
"text": "Python Solution - 0.06 seconds :"
},
{
"code": null,
"e": 2329,
"s": 2313,
"text": "class Solution:"
},
{
"code": null,
"e": 2360,
"s": 2329,
"text": " def permutation (self, S):"
},
{
"code": null,
"e": 2375,
"s": 2362,
"text": " ip=S"
},
{
"code": null,
"e": 2389,
"s": 2375,
"text": " op=''"
},
{
"code": null,
"e": 2404,
"s": 2389,
"text": " ans=[]"
},
{
"code": null,
"e": 2439,
"s": 2413,
"text": " def solve(ip,op):"
},
{
"code": null,
"e": 2466,
"s": 2439,
"text": " if len(ip)==0:"
},
{
"code": null,
"e": 2497,
"s": 2466,
"text": " ans.append(op)"
},
{
"code": null,
"e": 2521,
"s": 2497,
"text": " return "
},
{
"code": null,
"e": 2540,
"s": 2521,
"text": " op1=op"
},
{
"code": null,
"e": 2559,
"s": 2540,
"text": " op2=op"
},
{
"code": null,
"e": 2598,
"s": 2572,
"text": " op1=op1+ip[0]"
},
{
"code": null,
"e": 2628,
"s": 2598,
"text": " op2=op2+ip[0]+' '"
},
{
"code": null,
"e": 2652,
"s": 2630,
"text": " ip=ip[1:]"
},
{
"code": null,
"e": 2678,
"s": 2652,
"text": " solve(ip,op1)"
},
{
"code": null,
"e": 2704,
"s": 2678,
"text": " solve(ip,op2)"
},
{
"code": null,
"e": 2740,
"s": 2719,
"text": " solve(ip,op)"
},
{
"code": null,
"e": 2764,
"s": 2742,
"text": " for i in ans:"
},
{
"code": null,
"e": 2791,
"s": 2764,
"text": " if i[-1]==' ':"
},
{
"code": null,
"e": 2821,
"s": 2791,
"text": " ans.remove(i)"
},
{
"code": null,
"e": 2853,
"s": 2834,
"text": " ans.sort()"
},
{
"code": null,
"e": 2872,
"s": 2853,
"text": " return ans"
},
{
"code": null,
"e": 2874,
"s": 2872,
"text": "0"
},
{
"code": null,
"e": 2898,
"s": 2874,
"text": "piyush9534972 weeks ago"
},
{
"code": null,
"e": 2913,
"s": 2898,
"text": "Java 0.36/1.48"
},
{
"code": null,
"e": 3088,
"s": 2913,
"text": "ArrayList<String> permutation(String S){ if(S.length() == 0){ ArrayList<String> a = new ArrayList<>(); a.add(\"\"); return a; }"
},
{
"code": null,
"e": 3175,
"s": 3088,
"text": " char ch = S.charAt(0); ArrayList<String> b = permutation(S.substring(1));"
},
{
"code": null,
"e": 3225,
"s": 3175,
"text": " ArrayList<String> ans = new ArrayList<>();"
},
{
"code": null,
"e": 3326,
"s": 3225,
"text": " for(String s1 : b){ if(!s1.isEmpty()) ans.add(ch + \" \" + s1); }"
},
{
"code": null,
"e": 3411,
"s": 3326,
"text": " for(String s1 : b){ ans.add(ch + s1); } return ans; }"
},
{
"code": null,
"e": 3413,
"s": 3411,
"text": "0"
},
{
"code": null,
"e": 3436,
"s": 3413,
"text": "damamrajeev2 weeks ago"
},
{
"code": null,
"e": 3475,
"s": 3436,
"text": "Easy solution using c++ - 0.01 seconds"
},
{
"code": null,
"e": 4361,
"s": 3477,
"text": "void helper(string s,string out,vector<string> &res){\n if(s.length()==0){\n res.push_back(out);\n return;\n }\n // including space\n helper(s.substr(1),out+\" \"+s[0],res);\n // without space\n helper(s.substr(1),out+s[0],res);\n }\n\n vector<string> permutation(string s){\n // Code Here\n \n vector<string> out;\n // if string length is 0 then no need to do anything\n if(s.length()==0){\n return out;\n }\n // store is just used to convert char to string\n string store=\"\";\n store+=s[0];\n // passing first char of string inorder to reduce complication in recursive calls\n // if we just pass s[0] to helper functin in place of store we will be passing character instead of string\n helper(s.substr(1),store,out);\n return out;\n }"
},
{
"code": null,
"e": 4367,
"s": 4365,
"text": "0"
},
{
"code": null,
"e": 4395,
"s": 4367,
"text": "rajsinghrathour02 weeks ago"
},
{
"code": null,
"e": 4659,
"s": 4395,
"text": "void solve(string S, int index,vector<string>&s,string t){ if(index==S.length()) { s.push_back(t); return; } t+=S[index]; if(index<S.length()-1){t+=\" \"; solve(S,index+1,s,t);} if(index!=S.length()-1)t.pop_back(); solve(S,index+1,s,t);}"
},
{
"code": null,
"e": 4838,
"s": 4659,
"text": " vector<string> permutation(string S){ vector<string>s; string t=\"\"; solve(S,0,s,t); // sort(s.begin(),s.end()); return s; // Code Here }};"
},
{
"code": null,
"e": 4840,
"s": 4838,
"text": "0"
},
{
"code": null,
"e": 4866,
"s": 4840,
"text": "roytanupriya212 weeks ago"
},
{
"code": null,
"e": 4897,
"s": 4866,
"text": "Using Aditya Verma's Approach:"
},
{
"code": null,
"e": 5592,
"s": 4899,
"text": "#include<bits/stdc++.h>\nusing namespace std;\n\nvector<string> subset(string ip, string op, vector<string> &ans){\n //Base Condition\n if(ip.size()==0){\n ans.push_back(op);\n return ans;\n }\n //Hypothesis\n string op1=op;\n string op2=op;\n op2.push_back('_');\n op2.push_back(ip[0]);\n op1.push_back(ip[0]);\n ip.erase(ip.begin()+0);\n //Induction\n subset(ip,op1,ans);\n subset(ip,op2,ans);\n return ans;\n}\n\nint main()\n{\n string ip;\n cin>>ip;\n string op=\"\";\n op.push_back(ip[0]);\n ip.erase(ip.begin()+0);\n vector<string> ans;\n subset(ip,op,ans);\n for(int i=0;i<ans.size();i++){\n cout<<ans[i]<<\" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 5595,
"s": 5592,
"text": "+2"
},
{
"code": null,
"e": 5621,
"s": 5595,
"text": "avinashdhn19043 weeks ago"
},
{
"code": null,
"e": 6246,
"s": 5621,
"text": "public:\nvoid solve(vector<string>&ans,string s,int n,int i,string temp){\n if(i==n){\n ans.push_back(temp);\n return;\n }\n if(s[i]==' '){\n solve(ans,s,n,i+1,temp+' ');\n solve(ans,s,n,i+1,temp);\n return;\n }\n else {\n solve(ans,s,n,i+1,temp+s[i]);\n return;\n }\n return;\n}\n\n vector<string> permutation(string S){\n vector<string>ans;\n string s;\n int n=S.length();\n for(int i=0;i<n;i++){\n s+=S[i];\n if(i!=n-1)s+=' ';\n }\n \n solve(ans,s,s.length(),0,\"\");\n return ans;\n }"
},
{
"code": null,
"e": 6249,
"s": 6246,
"text": "+1"
},
{
"code": null,
"e": 6276,
"s": 6249,
"text": "lasthoneybadger4 weeks ago"
},
{
"code": null,
"e": 6280,
"s": 6276,
"text": "C++"
},
{
"code": null,
"e": 6659,
"s": 6280,
"text": "\tvector<string> res;\n void perm(string &S, int i, string curr){\n if(i == S.size()){\n res.push_back(curr);\n return;\n }\n if(i)\n perm(S, i + 1, curr + \" \" + S[i]);\n perm(S, i + 1, curr + S[i]);\n \n }\n vector<string> permutation(string S){\n // Code Here\n perm(S, 0, \"\");\n return res;\n }"
},
{
"code": null,
"e": 6661,
"s": 6659,
"text": "0"
},
{
"code": null,
"e": 6685,
"s": 6661,
"text": "swapniltayal1 month ago"
},
{
"code": null,
"e": 6999,
"s": 6685,
"text": " void perWithSpace(string &s, vector<string> &ans, string ds, int index){ if(index == s.size()){ ans.push_back(ds); return; } perWithSpace(s, ans, ds+s[index], index+1); if(index != s.size()-1){ perWithSpace(s, ans, ds+s[index] + \" \", index+1); } }"
},
{
"code": null,
"e": 7198,
"s": 6999,
"text": " vector<string> permutation(string S){ // Code Here vector<string> ans; string ds; perWithSpace(S, ans, ds, 0); reverse(ans.begin(), ans.end()); return ans; }"
},
{
"code": null,
"e": 7344,
"s": 7198,
"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": 7380,
"s": 7344,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7390,
"s": 7380,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7400,
"s": 7390,
"text": "\nContest\n"
},
{
"code": null,
"e": 7463,
"s": 7400,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7648,
"s": 7463,
"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": 7932,
"s": 7648,
"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": 8078,
"s": 7932,
"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": 8155,
"s": 8078,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8196,
"s": 8155,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8224,
"s": 8196,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8295,
"s": 8224,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 8482,
"s": 8295,
"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."
}
]
|
Scala Set foreach() method with example | 18 Oct, 2019
The foreach() method is utilized to apply the given function to all the elements of the set.
Method Definition: def foreach(f: (A) => Unit): Unit
Return Type: It returns all the elements of the set after applying the given function to each of them.
Example #1:
// Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(3, 7, 12, 9, 21) // Applying foreach method s1.foreach(x => println(x)) } }
21
9
12
7
3
Example #2:
// Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) // Applying foreach method s1.foreach(x => println(x + " times " + x + " = " + x*x)) } }
5 times 5 = 25
1 times 1 = 1
2 times 2 = 4
3 times 3 = 9
4 times 4 = 16
Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Lambda Expression in Scala
Scala Singleton and Companion Objects
How to Install Scala with VSCode?
Inheritance in Scala | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "The foreach() method is utilized to apply the given function to all the elements of the set."
},
{
"code": null,
"e": 174,
"s": 121,
"text": "Method Definition: def foreach(f: (A) => Unit): Unit"
},
{
"code": null,
"e": 277,
"s": 174,
"text": "Return Type: It returns all the elements of the set after applying the given function to each of them."
},
{
"code": null,
"e": 289,
"s": 277,
"text": "Example #1:"
},
{
"code": "// Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(3, 7, 12, 9, 21) // Applying foreach method s1.foreach(x => println(x)) } } ",
"e": 583,
"s": 289,
"text": null
},
{
"code": null,
"e": 596,
"s": 583,
"text": "21\n9\n12\n7\n3\n"
},
{
"code": null,
"e": 608,
"s": 596,
"text": "Example #2:"
},
{
"code": "// Scala program of foreach() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) // Applying foreach method s1.foreach(x => println(x + \" times \" + x + \" = \" + x*x)) } } ",
"e": 930,
"s": 608,
"text": null
},
{
"code": null,
"e": 1003,
"s": 930,
"text": "5 times 5 = 25\n1 times 1 = 1\n2 times 2 = 4\n3 times 3 = 9\n4 times 4 = 16\n"
},
{
"code": null,
"e": 1009,
"s": 1003,
"text": "Scala"
},
{
"code": null,
"e": 1026,
"s": 1009,
"text": "scala-collection"
},
{
"code": null,
"e": 1039,
"s": 1026,
"text": "Scala-Method"
},
{
"code": null,
"e": 1049,
"s": 1039,
"text": "Scala-Set"
},
{
"code": null,
"e": 1055,
"s": 1049,
"text": "Scala"
},
{
"code": null,
"e": 1153,
"s": 1055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1179,
"s": 1153,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1232,
"s": 1179,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1244,
"s": 1232,
"text": "Scala Lists"
},
{
"code": null,
"e": 1263,
"s": 1244,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1278,
"s": 1263,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1297,
"s": 1278,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1324,
"s": 1297,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 1362,
"s": 1324,
"text": "Scala Singleton and Companion Objects"
},
{
"code": null,
"e": 1396,
"s": 1362,
"text": "How to Install Scala with VSCode?"
}
]
|
Why Matplotlib can’t be installed in Visual Studio Code | by Xue Wang | Towards Data Science | We know “Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python”. If Anaconda is permitted to be installed, normally there is no problem using Matplotlib. But recently there are Terms of Service updates for commercial users from Anaconda. The detailed info is explained as below:
“As a response to the dramatic increase in usage and adoption of Python and Anaconda among commercial users over the last few years, we updated our Terms of Service. Moving forward, we are asking commercial users who rely on our packaging & distribution efforts to purchase one of our commercial offerings.” — https://www.anaconda.com/blog/anaconda-commercial-edition-faq
In case the company isn’t ready to pay for Anaconda yet, some engineers might turn to VS Code.
Before python can run properly in VSC, there are some settings that will bother the users. Most of them are the error to ask you to install the library, like “Import Error: No module named numpy”, which can be solved by the commands like “pip” or “pip3” or “python pip” or “python3 -m pip” etc. to solve.
But today, I would like to focus on Matplotlib problem, which might not be solved just by the pip command.
In case:
You have a windows systemAnaconda isn’t installed on your computerPython extension has been installed in VSCThe interpreter (at the bottom left corner of VSC) has been chosen correctlyNo visual studio build tool has been installed (you might also have no idea why you need it until the problem happens, for an engineer (like a mechanical engineer) to write python code.
You have a windows system
Anaconda isn’t installed on your computer
Python extension has been installed in VSC
The interpreter (at the bottom left corner of VSC) has been chosen correctly
No visual studio build tool has been installed (you might also have no idea why you need it until the problem happens, for an engineer (like a mechanical engineer) to write python code.
Now let’s take an example.
Try to test the below py file: standardplot.py:
import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the rangeplt.plot(x, np.sin(x)) # Plot the sine of each x pointplt.show() # Display the plot
Whether you get the below beautiful figure:
Or do you get errors? Like below:
Import Error: No module named numpy
Google it, the solution could be:
pip install numpyor pip3 install numpyorpython3 -m pip install numpyorpython3 -m pip install numpy
Similar problems like “no module for sklean” can be solved with a similar solution.
Run it again, now no problem with NumPy, but there might have an error as:
ERROR: Command errored out with exit status 1:......error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
This is because Microsoft C++Build Tools hasn’t been installed in your computer. In order to run matplotlib or a similar interactive interface in Microsoft for Python, Build Tools is needed, not only Microsoft C++ Redistributable.
How:
Click the link, it leads you to the below window:
Download build tools, run the .exe file, do cross C++ build tools as below during the installation. Be sure to choose the correct items.
It takes a bit long time, drink water or walks around during the process. :-)
If the build tool is installed correctly, now install Matplotlib in the normal way.
Run the py file, you will get the beautiful figure as above.
Takeaways:
I wrote this story because when I searched for the solution, most mentioned installing it but very few mentioned this case. Yes, it could be a rare case ( thinking about Anaconda can’t be installed...), but when it happens, it might take your time to solve it. Hope it helps to remind you of the case.The possible reason why Microsoft Visual C++ build tool is a prerequisite to run Matplotlib in python in VSC, I found below an explanation, but please feel free to correct me if I am wrong.
I wrote this story because when I searched for the solution, most mentioned installing it but very few mentioned this case. Yes, it could be a rare case ( thinking about Anaconda can’t be installed...), but when it happens, it might take your time to solve it. Hope it helps to remind you of the case.
The possible reason why Microsoft Visual C++ build tool is a prerequisite to run Matplotlib in python in VSC, I found below an explanation, but please feel free to correct me if I am wrong.
Windows Python needs Visual C++ libraries installed via the SDK to build code, such as via setuptools.extension.Extension or numpy.distutils.core.Extension. For example, building f2py modules in Windows with Python requires Visual C++ SDK as installed above. On Linux and Mac, the C++ libraries are installed with the compiler. -https://www.scivision.dev/python-windows-visual-c-14-required/
Thanks for your time. Hope it helps to solve your Matplotlib problem in VSC. | [
{
"code": null,
"e": 507,
"s": 172,
"text": "We know “Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python”. If Anaconda is permitted to be installed, normally there is no problem using Matplotlib. But recently there are Terms of Service updates for commercial users from Anaconda. The detailed info is explained as below:"
},
{
"code": null,
"e": 879,
"s": 507,
"text": "“As a response to the dramatic increase in usage and adoption of Python and Anaconda among commercial users over the last few years, we updated our Terms of Service. Moving forward, we are asking commercial users who rely on our packaging & distribution efforts to purchase one of our commercial offerings.” — https://www.anaconda.com/blog/anaconda-commercial-edition-faq"
},
{
"code": null,
"e": 974,
"s": 879,
"text": "In case the company isn’t ready to pay for Anaconda yet, some engineers might turn to VS Code."
},
{
"code": null,
"e": 1279,
"s": 974,
"text": "Before python can run properly in VSC, there are some settings that will bother the users. Most of them are the error to ask you to install the library, like “Import Error: No module named numpy”, which can be solved by the commands like “pip” or “pip3” or “python pip” or “python3 -m pip” etc. to solve."
},
{
"code": null,
"e": 1386,
"s": 1279,
"text": "But today, I would like to focus on Matplotlib problem, which might not be solved just by the pip command."
},
{
"code": null,
"e": 1395,
"s": 1386,
"text": "In case:"
},
{
"code": null,
"e": 1765,
"s": 1395,
"text": "You have a windows systemAnaconda isn’t installed on your computerPython extension has been installed in VSCThe interpreter (at the bottom left corner of VSC) has been chosen correctlyNo visual studio build tool has been installed (you might also have no idea why you need it until the problem happens, for an engineer (like a mechanical engineer) to write python code."
},
{
"code": null,
"e": 1791,
"s": 1765,
"text": "You have a windows system"
},
{
"code": null,
"e": 1833,
"s": 1791,
"text": "Anaconda isn’t installed on your computer"
},
{
"code": null,
"e": 1876,
"s": 1833,
"text": "Python extension has been installed in VSC"
},
{
"code": null,
"e": 1953,
"s": 1876,
"text": "The interpreter (at the bottom left corner of VSC) has been chosen correctly"
},
{
"code": null,
"e": 2139,
"s": 1953,
"text": "No visual studio build tool has been installed (you might also have no idea why you need it until the problem happens, for an engineer (like a mechanical engineer) to write python code."
},
{
"code": null,
"e": 2166,
"s": 2139,
"text": "Now let’s take an example."
},
{
"code": null,
"e": 2214,
"s": 2166,
"text": "Try to test the below py file: standardplot.py:"
},
{
"code": null,
"e": 2455,
"s": 2214,
"text": "import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the rangeplt.plot(x, np.sin(x)) # Plot the sine of each x pointplt.show() # Display the plot"
},
{
"code": null,
"e": 2499,
"s": 2455,
"text": "Whether you get the below beautiful figure:"
},
{
"code": null,
"e": 2533,
"s": 2499,
"text": "Or do you get errors? Like below:"
},
{
"code": null,
"e": 2569,
"s": 2533,
"text": "Import Error: No module named numpy"
},
{
"code": null,
"e": 2603,
"s": 2569,
"text": "Google it, the solution could be:"
},
{
"code": null,
"e": 2702,
"s": 2603,
"text": "pip install numpyor pip3 install numpyorpython3 -m pip install numpyorpython3 -m pip install numpy"
},
{
"code": null,
"e": 2786,
"s": 2702,
"text": "Similar problems like “no module for sklean” can be solved with a similar solution."
},
{
"code": null,
"e": 2861,
"s": 2786,
"text": "Run it again, now no problem with NumPy, but there might have an error as:"
},
{
"code": null,
"e": 3070,
"s": 2861,
"text": "ERROR: Command errored out with exit status 1:......error: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/"
},
{
"code": null,
"e": 3301,
"s": 3070,
"text": "This is because Microsoft C++Build Tools hasn’t been installed in your computer. In order to run matplotlib or a similar interactive interface in Microsoft for Python, Build Tools is needed, not only Microsoft C++ Redistributable."
},
{
"code": null,
"e": 3306,
"s": 3301,
"text": "How:"
},
{
"code": null,
"e": 3356,
"s": 3306,
"text": "Click the link, it leads you to the below window:"
},
{
"code": null,
"e": 3493,
"s": 3356,
"text": "Download build tools, run the .exe file, do cross C++ build tools as below during the installation. Be sure to choose the correct items."
},
{
"code": null,
"e": 3571,
"s": 3493,
"text": "It takes a bit long time, drink water or walks around during the process. :-)"
},
{
"code": null,
"e": 3655,
"s": 3571,
"text": "If the build tool is installed correctly, now install Matplotlib in the normal way."
},
{
"code": null,
"e": 3716,
"s": 3655,
"text": "Run the py file, you will get the beautiful figure as above."
},
{
"code": null,
"e": 3727,
"s": 3716,
"text": "Takeaways:"
},
{
"code": null,
"e": 4218,
"s": 3727,
"text": "I wrote this story because when I searched for the solution, most mentioned installing it but very few mentioned this case. Yes, it could be a rare case ( thinking about Anaconda can’t be installed...), but when it happens, it might take your time to solve it. Hope it helps to remind you of the case.The possible reason why Microsoft Visual C++ build tool is a prerequisite to run Matplotlib in python in VSC, I found below an explanation, but please feel free to correct me if I am wrong."
},
{
"code": null,
"e": 4520,
"s": 4218,
"text": "I wrote this story because when I searched for the solution, most mentioned installing it but very few mentioned this case. Yes, it could be a rare case ( thinking about Anaconda can’t be installed...), but when it happens, it might take your time to solve it. Hope it helps to remind you of the case."
},
{
"code": null,
"e": 4710,
"s": 4520,
"text": "The possible reason why Microsoft Visual C++ build tool is a prerequisite to run Matplotlib in python in VSC, I found below an explanation, but please feel free to correct me if I am wrong."
},
{
"code": null,
"e": 5102,
"s": 4710,
"text": "Windows Python needs Visual C++ libraries installed via the SDK to build code, such as via setuptools.extension.Extension or numpy.distutils.core.Extension. For example, building f2py modules in Windows with Python requires Visual C++ SDK as installed above. On Linux and Mac, the C++ libraries are installed with the compiler. -https://www.scivision.dev/python-windows-visual-c-14-required/"
}
]
|
Longest Non-Increasing Subsequence in a Binary String - GeeksforGeeks | 21 May, 2021
Given a binary string S of size N, the task is to find the length of the longest non-increasing subsequence in the given string S.
Examples:
Input: S = “0101110110100001011”Output: 12 Explanation: The longest non-increasing subsequence is “111111100000”, having length equal to 12.
Input: S = 10101Output: 3
Approach: The given problem can be solved based on the observation that the string S is a binary string, so a non-increasing subsequence will always consist of 0 with more consecutive 1s or 1 with more consecutive 0s. Follow the steps below to solve the problem:
Initialize an array, say pre[], that stores the number of 1s till each index i for i is over the range [0, N – 1].
Initialize an array, say post[], that stores the number of 0s till each index i to the end of the string for i over the range [0, N – 1].
Initialize a variable, say ans that stores the length of the longest non-increasing subsequence in the given string S.
Iterate over the range [0, N – 1] and update the value of ans to the maximum of ans and (pre[i] + post[i]).
After completing the above steps, print the value of ans as the result.
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 length of the// longest non-increasing subsequenceint findLength(string str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int pre[n], post[n]; // Initialize the array memset(pre, 0, sizeof(pre)); memset(post, 0, sizeof(post)); // Store the number of '1's // up to current index i in pre for (int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for (int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for (int i = 0; i < n; i++) { ans = max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codeint main(){ string S = "0101110110100001011"; cout << findLength(S, S.length()); return 0;}
// Java program for the above approachclass GFG{ // Function to find the length of the// longest non-increasing subsequencestatic int findLength(String str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int pre[] = new int[n]; int post[] = new int[n]; // Initialize the array for(int i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str.charAt(i) == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str.charAt(i) == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for(int i = 0; i < n; i++) { ans = Math.max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codepublic static void main(String[] args){ String S = "0101110110100001011"; System.out.println(findLength(S, S.length()));}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to find the length of the# longest non-increasing subsequencedef findLength(str, n): # Stores the prefix and suffix # count of 1s and 0s respectively pre = [0] * n post = [0] * n # Store the number of '1's # up to current index i in pre for i in range(n): # Find the prefix sum if (i != 0): pre[i] += pre[i - 1] # If the current element # is '1', update the pre[i] if (str[i] == '1'): pre[i] += 1 # Store the number of '0's over # the range [i, N - 1] for i in range(n - 1, -1, -1): # Find the suffix sum if (i != (n - 1)): post[i] += post[i + 1] # If the current element # is '0', update post[i] if (str[i] == '0'): post[i] += 1 # Stores the maximum length ans = 0 # Find the maximum value of # pre[i] + post[i] for i in range(n): ans = max(ans, pre[i] + post[i]) # Return the answer return ans # Driver CodeS = "0101110110100001011"n = len(S) print(findLength(S, n)) # This code is contributed by susmitakundugoaldanga
// C# program for the above approachusing System; class GFG{ // Function to find the length of the// longest non-increasing subsequencestatic int findLength(String str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int []pre = new int[n]; int []post = new int[n]; // Initialize the array for(int i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for(int i = 0; i < n; i++) { ans = Math.Max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codepublic static void Main(String[] args){ String S = "0101110110100001011"; Console.WriteLine(findLength(S, S.Length));}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // Function to find the length of the// longest non-increasing subsequencefunction findLength(str, n){ // Stores the prefix and suffix // count of 1s and 0s respectively let pre = Array.from({length: n}, (_, i) => 0); let post = Array.from({length: n}, (_, i) => 0); // Initialize the array for(let i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(let i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(let i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length let ans = 0; // Find the maximum value of // pre[i] + post[i] for(let i = 0; i < n; i++) { ans = Math.max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Code let S = "0101110110100001011"; document.write(findLength(S, S.length)); </script>
12
Time Complexity: O(N)Auxiliary Space: O(N)
abhinavjain194
princi singh
sanjoy_62
susmitakundugoaldanga
binary-string
frequency-counting
prefix-sum
subsequence
Mathematical
Strings
prefix-sum
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modular multiplicative inverse
Algorithm to solve Rubik's Cube
Count ways to reach the n'th stair
Program to multiply two matrices
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Longest Common Subsequence | DP-4
Reverse a string in Java
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24432,
"s": 24301,
"text": "Given a binary string S of size N, the task is to find the length of the longest non-increasing subsequence in the given string S."
},
{
"code": null,
"e": 24442,
"s": 24432,
"text": "Examples:"
},
{
"code": null,
"e": 24583,
"s": 24442,
"text": "Input: S = “0101110110100001011”Output: 12 Explanation: The longest non-increasing subsequence is “111111100000”, having length equal to 12."
},
{
"code": null,
"e": 24609,
"s": 24583,
"text": "Input: S = 10101Output: 3"
},
{
"code": null,
"e": 24872,
"s": 24609,
"text": "Approach: The given problem can be solved based on the observation that the string S is a binary string, so a non-increasing subsequence will always consist of 0 with more consecutive 1s or 1 with more consecutive 0s. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 24987,
"s": 24872,
"text": "Initialize an array, say pre[], that stores the number of 1s till each index i for i is over the range [0, N – 1]."
},
{
"code": null,
"e": 25125,
"s": 24987,
"text": "Initialize an array, say post[], that stores the number of 0s till each index i to the end of the string for i over the range [0, N – 1]."
},
{
"code": null,
"e": 25244,
"s": 25125,
"text": "Initialize a variable, say ans that stores the length of the longest non-increasing subsequence in the given string S."
},
{
"code": null,
"e": 25352,
"s": 25244,
"text": "Iterate over the range [0, N – 1] and update the value of ans to the maximum of ans and (pre[i] + post[i])."
},
{
"code": null,
"e": 25424,
"s": 25352,
"text": "After completing the above steps, print the value of ans as the result."
},
{
"code": null,
"e": 25475,
"s": 25424,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25479,
"s": 25475,
"text": "C++"
},
{
"code": null,
"e": 25484,
"s": 25479,
"text": "Java"
},
{
"code": null,
"e": 25492,
"s": 25484,
"text": "Python3"
},
{
"code": null,
"e": 25495,
"s": 25492,
"text": "C#"
},
{
"code": null,
"e": 25506,
"s": 25495,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of the// longest non-increasing subsequenceint findLength(string str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int pre[n], post[n]; // Initialize the array memset(pre, 0, sizeof(pre)); memset(post, 0, sizeof(post)); // Store the number of '1's // up to current index i in pre for (int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for (int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for (int i = 0; i < n; i++) { ans = max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codeint main(){ string S = \"0101110110100001011\"; cout << findLength(S, S.length()); return 0;}",
"e": 26874,
"s": 25506,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find the length of the// longest non-increasing subsequencestatic int findLength(String str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int pre[] = new int[n]; int post[] = new int[n]; // Initialize the array for(int i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str.charAt(i) == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str.charAt(i) == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for(int i = 0; i < n; i++) { ans = Math.max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codepublic static void main(String[] args){ String S = \"0101110110100001011\"; System.out.println(findLength(S, S.length()));}} // This code is contributed by abhinavjain194",
"e": 28392,
"s": 26874,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the length of the# longest non-increasing subsequencedef findLength(str, n): # Stores the prefix and suffix # count of 1s and 0s respectively pre = [0] * n post = [0] * n # Store the number of '1's # up to current index i in pre for i in range(n): # Find the prefix sum if (i != 0): pre[i] += pre[i - 1] # If the current element # is '1', update the pre[i] if (str[i] == '1'): pre[i] += 1 # Store the number of '0's over # the range [i, N - 1] for i in range(n - 1, -1, -1): # Find the suffix sum if (i != (n - 1)): post[i] += post[i + 1] # If the current element # is '0', update post[i] if (str[i] == '0'): post[i] += 1 # Stores the maximum length ans = 0 # Find the maximum value of # pre[i] + post[i] for i in range(n): ans = max(ans, pre[i] + post[i]) # Return the answer return ans # Driver CodeS = \"0101110110100001011\"n = len(S) print(findLength(S, n)) # This code is contributed by susmitakundugoaldanga",
"e": 29572,
"s": 28392,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the length of the// longest non-increasing subsequencestatic int findLength(String str, int n){ // Stores the prefix and suffix // count of 1s and 0s respectively int []pre = new int[n]; int []post = new int[n]; // Initialize the array for(int i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(int i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(int i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length int ans = 0; // Find the maximum value of // pre[i] + post[i] for(int i = 0; i < n; i++) { ans = Math.Max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Codepublic static void Main(String[] args){ String S = \"0101110110100001011\"; Console.WriteLine(findLength(S, S.Length));}} // This code is contributed by Princi Singh",
"e": 31083,
"s": 29572,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the length of the// longest non-increasing subsequencefunction findLength(str, n){ // Stores the prefix and suffix // count of 1s and 0s respectively let pre = Array.from({length: n}, (_, i) => 0); let post = Array.from({length: n}, (_, i) => 0); // Initialize the array for(let i = 0; i < n; i++) { pre[i] = 0; post[i] = 0; } // Store the number of '1's // up to current index i in pre for(let i = 0; i < n; i++) { // Find the prefix sum if (i != 0) { pre[i] += pre[i - 1]; } // If the current element // is '1', update the pre[i] if (str[i] == '1') { pre[i] += 1; } } // Store the number of '0's over // the range [i, N - 1] for(let i = n - 1; i >= 0; i--) { // Find the suffix sum if (i != n - 1) post[i] += post[i + 1]; // If the current element // is '0', update post[i] if (str[i] == '0') post[i] += 1; } // Stores the maximum length let ans = 0; // Find the maximum value of // pre[i] + post[i] for(let i = 0; i < n; i++) { ans = Math.max(ans, pre[i] + post[i]); } // Return the answer return ans;} // Driver Code let S = \"0101110110100001011\"; document.write(findLength(S, S.length)); </script>",
"e": 32552,
"s": 31083,
"text": null
},
{
"code": null,
"e": 32555,
"s": 32552,
"text": "12"
},
{
"code": null,
"e": 32600,
"s": 32557,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32615,
"s": 32600,
"text": "abhinavjain194"
},
{
"code": null,
"e": 32628,
"s": 32615,
"text": "princi singh"
},
{
"code": null,
"e": 32638,
"s": 32628,
"text": "sanjoy_62"
},
{
"code": null,
"e": 32660,
"s": 32638,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 32674,
"s": 32660,
"text": "binary-string"
},
{
"code": null,
"e": 32693,
"s": 32674,
"text": "frequency-counting"
},
{
"code": null,
"e": 32704,
"s": 32693,
"text": "prefix-sum"
},
{
"code": null,
"e": 32716,
"s": 32704,
"text": "subsequence"
},
{
"code": null,
"e": 32729,
"s": 32716,
"text": "Mathematical"
},
{
"code": null,
"e": 32737,
"s": 32729,
"text": "Strings"
},
{
"code": null,
"e": 32748,
"s": 32737,
"text": "prefix-sum"
},
{
"code": null,
"e": 32756,
"s": 32748,
"text": "Strings"
},
{
"code": null,
"e": 32769,
"s": 32756,
"text": "Mathematical"
},
{
"code": null,
"e": 32867,
"s": 32769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32876,
"s": 32867,
"text": "Comments"
},
{
"code": null,
"e": 32889,
"s": 32876,
"text": "Old Comments"
},
{
"code": null,
"e": 32920,
"s": 32889,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32952,
"s": 32920,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 32987,
"s": 32952,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 33020,
"s": 32987,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33073,
"s": 33020,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 33107,
"s": 33073,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33132,
"s": 33107,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33168,
"s": 33132,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33221,
"s": 33168,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
]
|
Search Element in a Dictionary using Javascript | We'll implement the get method that searches a given key in the dictionary.
get(key) {
if(this.hasKey(key)) {
return this.container[key];
}
return undefined;
}
Again, JS objects are very much implemented like dictionaries, hence have most of the functionality we can use directly without any more code needed. This is also heavily optimized, so you don't have to worry about the runtime of the function.
You can test this using −
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
console.log(myMap.get("key1"))
console.log(myMap.get("key2"))
console.log(myMap.get("key3"))
This will give the output −
value1
value2
undefined
In ES6, you have the same functionality using the get method. For example,
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
console.log(myMap.get("key1"))
console.log(myMap.get("key2"))
This will give the output −
value1
value2 | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "We'll implement the get method that searches a given key in the dictionary. "
},
{
"code": null,
"e": 1238,
"s": 1139,
"text": "get(key) {\n if(this.hasKey(key)) {\n return this.container[key];\n }\n return undefined;\n}"
},
{
"code": null,
"e": 1482,
"s": 1238,
"text": "Again, JS objects are very much implemented like dictionaries, hence have most of the functionality we can use directly without any more code needed. This is also heavily optimized, so you don't have to worry about the runtime of the function."
},
{
"code": null,
"e": 1509,
"s": 1482,
"text": "You can test this using − "
},
{
"code": null,
"e": 1688,
"s": 1509,
"text": "const myMap = new MyMap();\nmyMap.put(\"key1\", \"value1\");\nmyMap.put(\"key2\", \"value2\");\n\nconsole.log(myMap.get(\"key1\"))\nconsole.log(myMap.get(\"key2\"))\nconsole.log(myMap.get(\"key3\"))"
},
{
"code": null,
"e": 1716,
"s": 1688,
"text": "This will give the output −"
},
{
"code": null,
"e": 1740,
"s": 1716,
"text": "value1\nvalue2\nundefined"
},
{
"code": null,
"e": 1816,
"s": 1740,
"text": "In ES6, you have the same functionality using the get method. For example, "
},
{
"code": null,
"e": 1952,
"s": 1816,
"text": "const myMap = new Map([\n [\"key1\", \"value1\"],\n [\"key2\", \"value2\"]\n]);\n\nconsole.log(myMap.get(\"key1\"))\nconsole.log(myMap.get(\"key2\"))"
},
{
"code": null,
"e": 1980,
"s": 1952,
"text": "This will give the output −"
},
{
"code": null,
"e": 1994,
"s": 1980,
"text": "value1\nvalue2"
}
]
|
Understanding Data Analysis Step-By-Step | by Himanshu Sharma | Towards Data Science | In today’s world, over 2.5 quintillion bytes of data are created every single day. Being a Data Science Engineer/Data Scientist/ML Engineer or whatever you might call the art of data analysis is the first thing that you should master.
It is a process of inspecting, cleansing, transforming, and modeling data so that we can derive some useful information from the data and use it for future predictions.
Data analysis tools make it easier for users to process and manipulate data, analyze the relationships and correlations between data sets, and it also helps to identify patterns and trends for interpretation.
Here, we will be using python to study data analysis in-depth and study all the important aspects of data analysis. Here we will be using a car design dataset which you can download here.
Starting with importing the important libraries and reading the dataset
#importing the important librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns#reading the dataset and creating a dataframedf = pd.DataFrame(pd.read_csv('car_design.csv'))df.head()
As we can see here that the data is loaded in the data frame named ‘df’, so let us start with the data wrangling part like knowing the dimensions of the data, how many rows and columns do data have.
# Dimention of datasetprint("Dataset is of ", df.ndim, " dimension.")# Rows and column of datasetprint("Dataset has ", df.shape[0], " rows.","\nDataset has ", df.shape[1], " columns.")#Knowing the data Types of the columnsprint("Data Types :")print(df.dtypes)
All the above-mentioned steps will help us understand the data and its attributes.
While we go through the data we see that some of the columns contain “?” instead of correct data which is considered as an anomaly in data. We need to replace it with ‘NaN’ to perform further operations.
df = df.replace("?", np.nan)df.head()
Now we will replace the missing data i.e. NaN with the column of that mean, this operation can only be performed on the columns with data type float. So we will convert the selected columns, convert them to float, and replace the missing data with the mean.
# Replacing the missing data with respective column meanfor i in ['normalized-losses', 'bore', 'stroke', 'horsepower', 'peak-rpm', 'price']: df[i] = df[i].fillna(round(df[i].dropna().astype('float64').mean(),2))
As the data is now cleaned and without any anomalies, let us move forward and look at the statistical description of the data. For this, we will use the describe function. Describe function computes the summary of statistics pertaining to the Data Frame columns.
df.describe()
Now let us move forward to the next step.
In this, we will try to visualize different columns according to the problem statement and find out the relation between different attributes if any. As we are doing it for the general purpose we will be visualizing columns of our choice.
# Plotting histograms of the following numerical attributes -- # "engine-size", "peak-rpm","horsepower","price"hist_col_names = ["engine-size", "peak-rpm","horsepower","price"]for i in hist_col_names: df[i] = df[i].astype(float) # It changes data typeplt.figure(figsize=(15,15))cnt=1for i in hist_col_names: plt.subplot(4,2,cnt) sns.distplot(df[i], hist=True, color = 'darkblue', kde_kws={'linewidth': 4}) plt.title(i) cnt=cnt+1plt.tight_layout()plt.show()
With a little knowledge of statistics, we can clearly understand what thee distribution plots are trying to say. After this, we can also find the correlation of the different numerical attributes and visualize them using the Heatmap.
A heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors.
# Creating the correaltion matrixcorr = df.corr()# Plotting the correlation matrix on a heatmapfig, ax = plt.subplots(figsize=(12,9))sns.heatmap(corr, annot=True)ax.set_xticklabels(ax.get_xticklabels(), rotation=45);plt.show()
Another type of Data Visualization plot which is really insightful is known as Box-Plot, it is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending from the boxes indicating variability outside the upper and lower quartiles.
Let us plot a box-plot between ‘drive-wheels’ and ‘price’ attribute of the dataset. This will help us find out the price range for different drive-wheels car.
plt.figure(figsize=(8,8))sns.boxplot(x="drive-wheels", y="price", data=df,linewidth=1.5, palette ='Set2')
Now let us move to the final step that is drawing some insights from the data. Fo this let us imagine that our Problem Statement as “We need to find out the price range for different types of cars launched by a new company?”
In order to solve the problem statement let us first find out the average price of the cars according to Drive-Wheels.
df_group=df[['drive-wheels', 'body-style', 'price']]drive_wheel_avg=df_group.groupby(['drive-wheels'], as_index=False).mean()drive_wheel_avg
Now we will display the average of drive-wheels according to the body-style of the different cars.
group_avg=df_group.groupby(['drive-wheels','body-style'] , as_index=False).mean()group_avg
The final step is to convert the data obtained in the above step to a pivot table for better visualization, precise view, and understanding.
pivot_table=group_avg.pivot(index='drive-wheels', columns='body-style')pivot_table=pivot_table.fillna('Not Applicable')pivot_table
This table can help us find the price segment in which we can launch the car according to the data of other companies that are already in the market. Here we can clearly see that this inference is only based on limited attributes, if we want to get more precise inference we need to consider more attributes.
In this article, I have explained to you the basic steps that you should follow whenever you are working on a dataset. There is no hard and fast rule to follow these steps but they help you to get better insights.
Please find the dataset and the completed python file in my github where I have considered more attributes that you can go through for better understanding.
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can also view the code and data I have used here in my Github. | [
{
"code": null,
"e": 407,
"s": 172,
"text": "In today’s world, over 2.5 quintillion bytes of data are created every single day. Being a Data Science Engineer/Data Scientist/ML Engineer or whatever you might call the art of data analysis is the first thing that you should master."
},
{
"code": null,
"e": 576,
"s": 407,
"text": "It is a process of inspecting, cleansing, transforming, and modeling data so that we can derive some useful information from the data and use it for future predictions."
},
{
"code": null,
"e": 785,
"s": 576,
"text": "Data analysis tools make it easier for users to process and manipulate data, analyze the relationships and correlations between data sets, and it also helps to identify patterns and trends for interpretation."
},
{
"code": null,
"e": 973,
"s": 785,
"text": "Here, we will be using python to study data analysis in-depth and study all the important aspects of data analysis. Here we will be using a car design dataset which you can download here."
},
{
"code": null,
"e": 1045,
"s": 973,
"text": "Starting with importing the important libraries and reading the dataset"
},
{
"code": null,
"e": 1271,
"s": 1045,
"text": "#importing the important librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns#reading the dataset and creating a dataframedf = pd.DataFrame(pd.read_csv('car_design.csv'))df.head()"
},
{
"code": null,
"e": 1470,
"s": 1271,
"text": "As we can see here that the data is loaded in the data frame named ‘df’, so let us start with the data wrangling part like knowing the dimensions of the data, how many rows and columns do data have."
},
{
"code": null,
"e": 1730,
"s": 1470,
"text": "# Dimention of datasetprint(\"Dataset is of \", df.ndim, \" dimension.\")# Rows and column of datasetprint(\"Dataset has \", df.shape[0], \" rows.\",\"\\nDataset has \", df.shape[1], \" columns.\")#Knowing the data Types of the columnsprint(\"Data Types :\")print(df.dtypes)"
},
{
"code": null,
"e": 1813,
"s": 1730,
"text": "All the above-mentioned steps will help us understand the data and its attributes."
},
{
"code": null,
"e": 2017,
"s": 1813,
"text": "While we go through the data we see that some of the columns contain “?” instead of correct data which is considered as an anomaly in data. We need to replace it with ‘NaN’ to perform further operations."
},
{
"code": null,
"e": 2055,
"s": 2017,
"text": "df = df.replace(\"?\", np.nan)df.head()"
},
{
"code": null,
"e": 2313,
"s": 2055,
"text": "Now we will replace the missing data i.e. NaN with the column of that mean, this operation can only be performed on the columns with data type float. So we will convert the selected columns, convert them to float, and replace the missing data with the mean."
},
{
"code": null,
"e": 2528,
"s": 2313,
"text": "# Replacing the missing data with respective column meanfor i in ['normalized-losses', 'bore', 'stroke', 'horsepower', 'peak-rpm', 'price']: df[i] = df[i].fillna(round(df[i].dropna().astype('float64').mean(),2))"
},
{
"code": null,
"e": 2791,
"s": 2528,
"text": "As the data is now cleaned and without any anomalies, let us move forward and look at the statistical description of the data. For this, we will use the describe function. Describe function computes the summary of statistics pertaining to the Data Frame columns."
},
{
"code": null,
"e": 2805,
"s": 2791,
"text": "df.describe()"
},
{
"code": null,
"e": 2847,
"s": 2805,
"text": "Now let us move forward to the next step."
},
{
"code": null,
"e": 3086,
"s": 2847,
"text": "In this, we will try to visualize different columns according to the problem statement and find out the relation between different attributes if any. As we are doing it for the general purpose we will be visualizing columns of our choice."
},
{
"code": null,
"e": 3563,
"s": 3086,
"text": "# Plotting histograms of the following numerical attributes -- # \"engine-size\", \"peak-rpm\",\"horsepower\",\"price\"hist_col_names = [\"engine-size\", \"peak-rpm\",\"horsepower\",\"price\"]for i in hist_col_names: df[i] = df[i].astype(float) # It changes data typeplt.figure(figsize=(15,15))cnt=1for i in hist_col_names: plt.subplot(4,2,cnt) sns.distplot(df[i], hist=True, color = 'darkblue', kde_kws={'linewidth': 4}) plt.title(i) cnt=cnt+1plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 3797,
"s": 3563,
"text": "With a little knowledge of statistics, we can clearly understand what thee distribution plots are trying to say. After this, we can also find the correlation of the different numerical attributes and visualize them using the Heatmap."
},
{
"code": null,
"e": 3947,
"s": 3797,
"text": "A heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors."
},
{
"code": null,
"e": 4174,
"s": 3947,
"text": "# Creating the correaltion matrixcorr = df.corr()# Plotting the correlation matrix on a heatmapfig, ax = plt.subplots(figsize=(12,9))sns.heatmap(corr, annot=True)ax.set_xticklabels(ax.get_xticklabels(), rotation=45);plt.show()"
},
{
"code": null,
"e": 4471,
"s": 4174,
"text": "Another type of Data Visualization plot which is really insightful is known as Box-Plot, it is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending from the boxes indicating variability outside the upper and lower quartiles."
},
{
"code": null,
"e": 4630,
"s": 4471,
"text": "Let us plot a box-plot between ‘drive-wheels’ and ‘price’ attribute of the dataset. This will help us find out the price range for different drive-wheels car."
},
{
"code": null,
"e": 4736,
"s": 4630,
"text": "plt.figure(figsize=(8,8))sns.boxplot(x=\"drive-wheels\", y=\"price\", data=df,linewidth=1.5, palette ='Set2')"
},
{
"code": null,
"e": 4961,
"s": 4736,
"text": "Now let us move to the final step that is drawing some insights from the data. Fo this let us imagine that our Problem Statement as “We need to find out the price range for different types of cars launched by a new company?”"
},
{
"code": null,
"e": 5080,
"s": 4961,
"text": "In order to solve the problem statement let us first find out the average price of the cars according to Drive-Wheels."
},
{
"code": null,
"e": 5221,
"s": 5080,
"text": "df_group=df[['drive-wheels', 'body-style', 'price']]drive_wheel_avg=df_group.groupby(['drive-wheels'], as_index=False).mean()drive_wheel_avg"
},
{
"code": null,
"e": 5320,
"s": 5221,
"text": "Now we will display the average of drive-wheels according to the body-style of the different cars."
},
{
"code": null,
"e": 5411,
"s": 5320,
"text": "group_avg=df_group.groupby(['drive-wheels','body-style'] , as_index=False).mean()group_avg"
},
{
"code": null,
"e": 5552,
"s": 5411,
"text": "The final step is to convert the data obtained in the above step to a pivot table for better visualization, precise view, and understanding."
},
{
"code": null,
"e": 5683,
"s": 5552,
"text": "pivot_table=group_avg.pivot(index='drive-wheels', columns='body-style')pivot_table=pivot_table.fillna('Not Applicable')pivot_table"
},
{
"code": null,
"e": 5992,
"s": 5683,
"text": "This table can help us find the price segment in which we can launch the car according to the data of other companies that are already in the market. Here we can clearly see that this inference is only based on limited attributes, if we want to get more precise inference we need to consider more attributes."
},
{
"code": null,
"e": 6206,
"s": 5992,
"text": "In this article, I have explained to you the basic steps that you should follow whenever you are working on a dataset. There is no hard and fast rule to follow these steps but they help you to get better insights."
},
{
"code": null,
"e": 6363,
"s": 6206,
"text": "Please find the dataset and the completed python file in my github where I have considered more attributes that you can go through for better understanding."
},
{
"code": null,
"e": 6386,
"s": 6363,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6409,
"s": 6386,
"text": "towardsdatascience.com"
}
]
|
C++ Program to Check Whether a Number is Palindrome or Not | A palindrome number remains the same if its digits are reversed i.e its value does not change. A palindrome number can also be called symmetric. For example: The numbers 12321, 1551, 11 etc are palindromes as they do not change even if their digits are reversed.
A program that checks if a number is palindrome or not is as follows.
Live Demo
#include<iostream>
using namespace std;
void palindrome(int num) {
int rev=0,val;
val = num;
while(num > 0) {
rev = rev * 10 + num % 10;
num = num / 10;
}
if(val==rev)
cout<<val<<" is a palindrome"<<endl;
else
cout<<val<<" is not a palindrome"<<endl;
}
int main() {
palindrome(12321);
palindrome(1234);
return 0;
}
12321 is a palindrome
1234 is not a palindrome
In the above program, the function palindrome finds out if the number is palindrome or not. The function takes one parameter i.e num. Before any process takes place, a duplicate of num is made i.e val. The value of num is reversed and stored in rev.
This is shown by the following code snippet −
int rev=0,val;
val = num;
while(num > 0) {
rev = rev * 10 + num % 10;
num = num / 10;
}
After this, the value of rev is compared to val and not num. This is because the value of num is 0 by now. If rev is equal to val, then the number is a palindrome and this is printed, else the number is not a palindrome.
This can be seen in the following code snippet.
if(val==rev)
cout<<val<<" is a palindrome"<<endl;
else
cout<<val<<" is not a palindrome"<<endl; | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "A palindrome number remains the same if its digits are reversed i.e its value does not change. A palindrome number can also be called symmetric. For example: The numbers 12321, 1551, 11 etc are palindromes as they do not change even if their digits are reversed."
},
{
"code": null,
"e": 1395,
"s": 1325,
"text": "A program that checks if a number is palindrome or not is as follows."
},
{
"code": null,
"e": 1406,
"s": 1395,
"text": " Live Demo"
},
{
"code": null,
"e": 1766,
"s": 1406,
"text": "#include<iostream>\nusing namespace std;\nvoid palindrome(int num) {\n int rev=0,val;\n val = num;\n while(num > 0) {\n rev = rev * 10 + num % 10;\n num = num / 10;\n }\n if(val==rev)\n cout<<val<<\" is a palindrome\"<<endl;\n else\n cout<<val<<\" is not a palindrome\"<<endl;\n}\nint main() {\n palindrome(12321);\n palindrome(1234);\n return 0;\n}"
},
{
"code": null,
"e": 1813,
"s": 1766,
"text": "12321 is a palindrome\n1234 is not a palindrome"
},
{
"code": null,
"e": 2063,
"s": 1813,
"text": "In the above program, the function palindrome finds out if the number is palindrome or not. The function takes one parameter i.e num. Before any process takes place, a duplicate of num is made i.e val. The value of num is reversed and stored in rev."
},
{
"code": null,
"e": 2109,
"s": 2063,
"text": "This is shown by the following code snippet −"
},
{
"code": null,
"e": 2203,
"s": 2109,
"text": "int rev=0,val;\nval = num;\nwhile(num > 0) {\n rev = rev * 10 + num % 10;\n num = num / 10;\n}"
},
{
"code": null,
"e": 2424,
"s": 2203,
"text": "After this, the value of rev is compared to val and not num. This is because the value of num is 0 by now. If rev is equal to val, then the number is a palindrome and this is printed, else the number is not a palindrome."
},
{
"code": null,
"e": 2472,
"s": 2424,
"text": "This can be seen in the following code snippet."
},
{
"code": null,
"e": 2568,
"s": 2472,
"text": "if(val==rev)\ncout<<val<<\" is a palindrome\"<<endl;\nelse\ncout<<val<<\" is not a palindrome\"<<endl;"
}
]
|
Map of list and forward_list in C++ STL with Examples - GeeksforGeeks | 10 Jan, 2022
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. A list simply means a doubly-linked list and for a singly linked list forward List is used.
Map of List in STL
A map of lists can be very useful in designing complex data structures.
Syntax:
map<datatype, list<datatype>> map_of_list
This stores a list corresponding to a datatype
or
map<list<datatype>, datatype> map_of_list
This stores a datatype corresponding to a list
Below is the implementation of the Map of List in C++-
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; void printMapContent1(map<list<int>, int>& mapOfList){ cout << " Key Value" << "\n\n"; for (auto p : mapOfList) { // Key is a list of integers list<int> ourList = p.first; // Value is an integer int val = p.second; // Printing list elements cout << "[ "; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << " "; // Printing value cout << mapOfList[ourList] << '\n'; }} void printMapContent2(map<int, list<int> >& mapOfList){ cout << " Key Value" << "\n\n"; for (auto p : mapOfList) { // Key is an integer int key = p.first; // Value is a list of integers list<int> ourList = p.second; cout << " "; cout << key << " "; // Printing list elements cout << "[ "; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a list of integers list<int> ourList1; // Inserting elements at the // back of list ourList1.push_back(2); ourList1.push_back(10); ourList1.push_back(13); // Declaring another list list<int> ourList2; // Inserting elements at the back // of list ourList2.push_back(7); ourList2.push_back(14); ourList2.push_back(22); // Declaring a map where key is a list // and value is integer itself map<list<int>, int> mapOfList1; mapOfList1[ourList1] = 5; mapOfList1[ourList2] = 10; // Printing the contents of the map printMapContent1(mapOfList1); // Declaring a map where key is integer // and value is a list of integers map<int, list<int> > mapOfList2; cout << "\n\n"; mapOfList2[3] = ourList1; mapOfList2[7] = ourList2; printMapContent2(mapOfList2); return 0;}
Key Value
[ 2 10 13 ] 5
[ 7 14 22 ] 10
Key Value
3 [ 2 10 13 ]
7 [ 7 14 22 ]
Forward List in STL
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. forward_list can also be used with the map container.
Syntax:
map<datatype, forward_list<datatype>> map_of_list
This stores a forward list corresponding to a datatype
or
map<forward_list<datatype>, datatype> map_of_list
This stores a datatype corresponding to a forward list
Below is the implementation of forward_list in C++-
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; void printMapContent1(map<forward_list<int>, int>& mapOfList){ cout << " Key Value" << "\n\n"; for (auto p : mapOfList) { // Key is a list of integers forward_list<int> ourList = p.first; // Value is an integer int val = p.second; // Printing list elements cout << "[ "; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << " "; // Printing value cout << mapOfList[ourList] << '\n'; }} void printMapContent2(map<int, forward_list<int> >& mapOfList){ cout << " Key Value" << "\n\n"; for (auto p : mapOfList) { // Key is an integer int key = p.first; // Value is a list of integers forward_list<int> ourList = p.second; cout << " "; cout << key << " "; // Printing list elements cout << "[ "; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << "\n"; }} // Driver codeint main(){ // Declaring forward list forward_list<int> forwardList1; // Declaring another forward list forward_list<int> forwardList2; // Assigning values using assign() forwardList1.assign({ 5, 3, 13 }); forwardList2.assign({ 8, 9, 13 }); map<forward_list<int>, int> mapOfList1; mapOfList1[forwardList1] = 3; mapOfList1[forwardList2] = 7; printMapContent1(mapOfList1); cout << "\n\n"; map<int, forward_list<int> > mapOfList2; mapOfList2[3] = forwardList1; mapOfList2[7] = forwardList2; printMapContent2(mapOfList2); return 0;}
Key Value
[ 5 3 13 ] 3
[ 8 9 13 ] 7
Key Value
3 [ 5 3 13 ]
7 [ 8 9 13 ]
surindertarika1234
simmytarika5
cpp-list
cpp-map
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
Pair in C++ Standard Template Library (STL)
Destructors in C++
new and delete operators in C++ for dynamic memory
Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 23707,
"s": 23679,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 23880,
"s": 23707,
"text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values."
},
{
"code": null,
"e": 24170,
"s": 23880,
"text": "Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. A list simply means a doubly-linked list and for a singly linked list forward List is used. "
},
{
"code": null,
"e": 24189,
"s": 24170,
"text": "Map of List in STL"
},
{
"code": null,
"e": 24261,
"s": 24189,
"text": "A map of lists can be very useful in designing complex data structures."
},
{
"code": null,
"e": 24269,
"s": 24261,
"text": "Syntax:"
},
{
"code": null,
"e": 24453,
"s": 24269,
"text": "map<datatype, list<datatype>> map_of_list \nThis stores a list corresponding to a datatype\n\nor\n\nmap<list<datatype>, datatype> map_of_list\nThis stores a datatype corresponding to a list"
},
{
"code": null,
"e": 24508,
"s": 24453,
"text": "Below is the implementation of the Map of List in C++-"
},
{
"code": null,
"e": 24512,
"s": 24508,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; void printMapContent1(map<list<int>, int>& mapOfList){ cout << \" Key Value\" << \"\\n\\n\"; for (auto p : mapOfList) { // Key is a list of integers list<int> ourList = p.first; // Value is an integer int val = p.second; // Printing list elements cout << \"[ \"; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << \" \"; // Printing value cout << mapOfList[ourList] << '\\n'; }} void printMapContent2(map<int, list<int> >& mapOfList){ cout << \" Key Value\" << \"\\n\\n\"; for (auto p : mapOfList) { // Key is an integer int key = p.first; // Value is a list of integers list<int> ourList = p.second; cout << \" \"; cout << key << \" \"; // Printing list elements cout << \"[ \"; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a list of integers list<int> ourList1; // Inserting elements at the // back of list ourList1.push_back(2); ourList1.push_back(10); ourList1.push_back(13); // Declaring another list list<int> ourList2; // Inserting elements at the back // of list ourList2.push_back(7); ourList2.push_back(14); ourList2.push_back(22); // Declaring a map where key is a list // and value is integer itself map<list<int>, int> mapOfList1; mapOfList1[ourList1] = 5; mapOfList1[ourList2] = 10; // Printing the contents of the map printMapContent1(mapOfList1); // Declaring a map where key is integer // and value is a list of integers map<int, list<int> > mapOfList2; cout << \"\\n\\n\"; mapOfList2[3] = ourList1; mapOfList2[7] = ourList2; printMapContent2(mapOfList2); return 0;}",
"e": 26825,
"s": 24512,
"text": null
},
{
"code": null,
"e": 26960,
"s": 26825,
"text": " Key Value\n\n[ 2 10 13 ] 5\n[ 7 14 22 ] 10\n\n\n Key Value\n\n 3 [ 2 10 13 ]\n 7 [ 7 14 22 ]"
},
{
"code": null,
"e": 26981,
"s": 26960,
"text": "Forward List in STL "
},
{
"code": null,
"e": 27277,
"s": 26981,
"text": "Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. forward_list can also be used with the map container."
},
{
"code": null,
"e": 27286,
"s": 27277,
"text": "Syntax: "
},
{
"code": null,
"e": 27501,
"s": 27286,
"text": "map<datatype, forward_list<datatype>> map_of_list\nThis stores a forward list corresponding to a datatype\n\nor\n\nmap<forward_list<datatype>, datatype> map_of_list\nThis stores a datatype corresponding to a forward list"
},
{
"code": null,
"e": 27554,
"s": 27501,
"text": "Below is the implementation of forward_list in C++- "
},
{
"code": null,
"e": 27558,
"s": 27554,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; void printMapContent1(map<forward_list<int>, int>& mapOfList){ cout << \" Key Value\" << \"\\n\\n\"; for (auto p : mapOfList) { // Key is a list of integers forward_list<int> ourList = p.first; // Value is an integer int val = p.second; // Printing list elements cout << \"[ \"; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << \" \"; // Printing value cout << mapOfList[ourList] << '\\n'; }} void printMapContent2(map<int, forward_list<int> >& mapOfList){ cout << \" Key Value\" << \"\\n\\n\"; for (auto p : mapOfList) { // Key is an integer int key = p.first; // Value is a list of integers forward_list<int> ourList = p.second; cout << \" \"; cout << key << \" \"; // Printing list elements cout << \"[ \"; for (auto it = ourList.begin(); it != ourList.end(); it++) { // Dereferencing value pointed by // iterator cout << (*it) << ' '; } cout << ']'; cout << \"\\n\"; }} // Driver codeint main(){ // Declaring forward list forward_list<int> forwardList1; // Declaring another forward list forward_list<int> forwardList2; // Assigning values using assign() forwardList1.assign({ 5, 3, 13 }); forwardList2.assign({ 8, 9, 13 }); map<forward_list<int>, int> mapOfList1; mapOfList1[forwardList1] = 3; mapOfList1[forwardList2] = 7; printMapContent1(mapOfList1); cout << \"\\n\\n\"; map<int, forward_list<int> > mapOfList2; mapOfList2[3] = forwardList1; mapOfList2[7] = forwardList2; printMapContent2(mapOfList2); return 0;}",
"e": 29638,
"s": 27558,
"text": null
},
{
"code": null,
"e": 29768,
"s": 29638,
"text": " Key Value\n\n[ 5 3 13 ] 3\n[ 8 9 13 ] 7\n\n\n Key Value\n\n 3 [ 5 3 13 ]\n 7 [ 8 9 13 ]"
},
{
"code": null,
"e": 29789,
"s": 29770,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29802,
"s": 29789,
"text": "simmytarika5"
},
{
"code": null,
"e": 29811,
"s": 29802,
"text": "cpp-list"
},
{
"code": null,
"e": 29819,
"s": 29811,
"text": "cpp-map"
},
{
"code": null,
"e": 29823,
"s": 29819,
"text": "C++"
},
{
"code": null,
"e": 29827,
"s": 29823,
"text": "CPP"
},
{
"code": null,
"e": 29925,
"s": 29827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29934,
"s": 29925,
"text": "Comments"
},
{
"code": null,
"e": 29947,
"s": 29934,
"text": "Old Comments"
},
{
"code": null,
"e": 29975,
"s": 29947,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29999,
"s": 29975,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30019,
"s": 29999,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30052,
"s": 30019,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30096,
"s": 30052,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30132,
"s": 30096,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 30176,
"s": 30132,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30195,
"s": 30176,
"text": "Destructors in C++"
},
{
"code": null,
"e": 30246,
"s": 30195,
"text": "new and delete operators in C++ for dynamic memory"
}
]
|
Check if the given Binary Expressions are valid - GeeksforGeeks | 01 Oct, 2021
Given n expressions of the type x = y and x != y where 1 ≤ x, y ≤ n, the task is to check whether the integers from 1 to n can be assigned to x and y such that all the equations are satisfied.
Examples:
Input: x[] = {1, 2, 3}, op[] = {“=”, “=”, “!=”}, y[] = {2, 3, 1} Output: Invalid If 1 = 2 and 2 = 3 then 3 must be equal to 1.
Input: x[] = {1, 2}, op[] = {“=”, “=”}, y[] = {2, 3} Output: Valid
Approach: The idea is to use union-find. For each statement check if there exists “=” sign then find the parent values for the two variables and union them using the rank method. Now once the union has been done for all the variables having “=” operator between them, start checking for “!=” operator, if this operator exists between any two variables whose parents are the same then the expressions are invalid, else they are valid.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the parent of an integerint findParent(int i, vector<int> parent){ if (parent[i] == i) return i; return findParent(parent[i], parent);} // Find union for both the integers x and y// using rank methodvoid findUnion(int x, int y, vector<int>& parent, vector<int>& rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if (rank[xroot] > rank[yroot]) { parent[y] = x; rank[xroot]++; } else if (rank[x] < rank[y]) { parent[x] = y; rank[yroot]++; } else { parent[y] = x; rank[xroot]++; } }} // Function that returns true if// the expression is invalidbool isInvalid(vector<int> u, vector<int> v, vector<string> op, int n){ // Vector to store parent values // of each integer vector<int> parent; // Vector to store rank // of each integer vector<int> rank; parent.push_back(-1); rank.push_back(-1); // Initialize parent values for // each of the integers for (int i = 1; i <= n; i++) parent.push_back(i); // Initialize rank values for // each of the integers for (int i = 1; i <= n; i++) rank.push_back(0); // Check for = operator and find union // for them for (int i = 0; i < n; i++) if (op[i] == "=") findUnion(u[i], v[i], parent, rank); // Check for != operator for (int i = 0; i < n; i++) { if (op[i] == "!=") { // If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)) return true; } } // Expression is valid return false;} // Driver codeint main(){ vector<int> u; vector<int> v; vector<string> op; // Store the first integer u.push_back(1); u.push_back(2); u.push_back(3); // Store the second integer v.push_back(2); v.push_back(3); v.push_back(1); // Store the operators op.push_back("="); op.push_back("="); op.push_back("!="); // Number of expressions int n = u.size(); if (isInvalid(u, v, op, n)) cout << "Invalid"; else cout << "Valid"; return 0;}
// Java implementation of// the above approachimport java.util.*;class GFG{ // Function to return the parent// of an integerpublic static int findParent(int i, Vector parent){ if ((int)parent.get(i) == i) return i; return findParent((int)parent.get(i), parent);} // Find union for both the integers x and y// using rank methodpublic static void findUnion(int x, int y, Vector parent, Vector rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if ((int)rank.get(xroot) > (int)rank.get(yroot)) { parent.set(y,x); rank.set(xroot, (int)rank.get(xroot) + 1); } else if ((int)rank.get(x) < (int)rank.get(y)) { parent.set(x,y); rank.set(yroot, (int)rank.get(yroot) + 1); } else { parent.set(y,x); rank.set(xroot, (int)rank.get(xroot) + 1); } }} // Function that returns true if// the expression is invalidpublic static boolean isInvalid(Vector u, Vector v, Vector op, int n){ // To store parent values // of each integer Vector parent = new Vector(); // To store rank // of each integer Vector rank = new Vector(); parent.add(-1); rank.add(-1); // Initialize parent values for // each of the integers for(int i = 1; i <= n; i++) parent.add(i); // Initialize rank values for // each of the integers for(int i = 1; i <= n; i++) rank.add(0); // Check for = operator and find union // for them for(int i = 0; i < n; i++) if ((String)op.get(i) == "=") findUnion((int)u.get(i), (int)v.get(i), parent, rank); // Check for != operator for(int i = 0; i < n; i++) { if ((String)op.get(i) == "!=") { // If the expression is invalid if (findParent((int)u.get(i), parent) == findParent((int)v.get(i), parent)) return true; } } // Expression is valid return false;} // Driver codepublic static void main(String[] args){ Vector u = new Vector(); Vector v = new Vector(); Vector op = new Vector(); // Store the first integer u.add(1); u.add(2); u.add(3); // Store the second integer v.add(2); v.add(3); v.add(1); // Store the operators op.add("="); op.add("="); op.add("!="); // Number of expressions int n = u.size(); if (isInvalid(u, v, op, n)) System.out.print("Invalid"); else System.out.print("Valid");}} // This code is contributed by divyeshrabadiya07
# Python3 implementation of the approach # Function to return the parent of an integerdef findParent(i, parent): if parent[i] == i: return i return findParent(parent[i], parent) # Find union for both the integers# x and y using rank methoddef findUnion(x, y, parent, rank): xroot = findParent(x, parent) yroot = findParent(y, parent) # Union using rank method if xroot != yroot: if rank[xroot] > rank[yroot]: parent[y] = x rank[xroot] += 1 elif rank[x] < rank[y]: parent[x] = y rank[yroot] += 1 else: parent[y] = x rank[xroot] += 1 # Function that returns true if# the expression is invaliddef isInvalid(u, v, op, n): # Vector to store parent values # of each integer parent = [] # Vector to store rank # of each integer rank = [] parent.append(-1) rank.append(-1) # Initialize parent values for # each of the integers for i in range(1, n + 1): parent.append(i) # Initialize rank values for # each of the integers for i in range(1, n + 1): rank.append(0) # Check for = operator and # find union for them for i in range(0, n): if op[i] == "=": findUnion(u[i], v[i], parent, rank) # Check for != operator for i in range(0, n): if op[i] == "!=": # If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)): return True # Expression is valid return False # Driver codeif __name__ == "__main__": u = [1, 2, 3] v = [2, 3, 1] op = ["=", "=", "!="] # Number of expressions n = len(u) if isInvalid(u, v, op, n): print("Invalid") else: print("Valid") # This code is contributed by Rituraj Jain
// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the parent of an integerstatic int findParent(int i, ArrayList parent){ if ((int)parent[i] == i) return i; return findParent((int)parent[i], parent);} // Find union for both the integers x and y// using rank methodstatic void findUnion(int x, int y, ArrayList parent, ArrayList rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if ((int)rank[xroot] > (int)rank[yroot]) { parent[y] = x; rank[xroot] = (int)rank[xroot] + 1; } else if ((int)rank[x] < (int)rank[y]) { parent[x] = y; rank[yroot] = (int)rank[yroot] + 1; } else { parent[y] = x; rank[xroot] = (int)rank[xroot] + 1; } }} // Function that returns true if// the expression is invalidstatic bool isInvalid(ArrayList u, ArrayList v, ArrayList op, int n){ // To store parent values // of each integer ArrayList parent = new ArrayList(); // To store rank // of each integer ArrayList rank = new ArrayList(); parent.Add(-1); rank.Add(-1); // Initialize parent values for // each of the integers for(int i = 1; i <= n; i++) parent.Add(i); // Initialize rank values for // each of the integers for(int i = 1; i <= n; i++) rank.Add(0); // Check for = operator and find union // for them for(int i = 0; i < n; i++) if ((string)op[i] == "=") findUnion((int)u[i], (int)v[i], parent, rank); // Check for != operator for(int i = 0; i < n; i++) { if ((string)op[i] == "!=") { // If the expression is invalid if (findParent((int)u[i], parent) == findParent((int)v[i], parent)) return true; } } // Expression is valid return false;} // Driver Codepublic static void Main(string[] args){ ArrayList u = new ArrayList(); ArrayList v = new ArrayList(); ArrayList op = new ArrayList(); // Store the first integer u.Add(1); u.Add(2); u.Add(3); // Store the second integer v.Add(2); v.Add(3); v.Add(1); // Store the operators op.Add("="); op.Add("="); op.Add("!="); // Number of expressions int n = u.Count; if (isInvalid(u, v, op, n)) Console.Write("Invalid"); else Console.Write("Valid");}} // This code is contributed by rutvik_56
<script>// Javascript implementation of the approach // Function to return the parent of an integerfunction findParent(i, parent){ if (parent[i] == i) return i; return findParent(parent[i], parent);} // Find union for both the integers x and y// using rank methodfunction findUnion(x, y, parent, rank) { let xroot = findParent(x, parent); let yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if (rank[xroot] > rank[yroot]) { parent[y] = x; rank[xroot]++; } else if (rank[x] < rank[y]) { parent[x] = y; rank[yroot]++; } else { parent[y] = x; rank[xroot]++; } }} // Function that returns true if// the expression is invalidfunction isInvalid(u, v, op, n) { // Vector to store parent values // of each integer let parent = []; // Vector to store rank // of each integer let rank = []; parent.push(-1); rank.push(-1); // Initialize parent values for // each of the integers for (let i = 1; i <= n; i++) parent.push(i); // Initialize rank values for // each of the integers for (let i = 1; i <= n; i++) rank.push(0); // Check for = operator and find union // for them for (let i = 0; i < n; i++) if (op[i] == "=") findUnion(u[i], v[i], parent, rank); // Check for != operator for (let i = 0; i < n; i++) { if (op[i] == "!=") { // If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)) return true; } } // Expression is valid return false;} // Driver code let u = [];let v = [];let op = []; // Store the first integeru.push(1);u.push(2);u.push(3); // Store the second integerv.push(2);v.push(3);v.push(1); // Store the operatorsop.push("=");op.push("=");op.push("!="); // Number of expressionslet n = u.length;if (isInvalid(u, v, op, n)) document.write("Invalid");else document.write("Valid"); // This code is contributed by _saurabh_jaiswal</script>
Invalid
rituraj_jain
rutvik_56
divyeshrabadiya07
_saurabh_jaiswal
arorakashish0911
union-find
Arrays
Graph
Mathematical
Arrays
Mathematical
Graph
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 25015,
"s": 24822,
"text": "Given n expressions of the type x = y and x != y where 1 ≤ x, y ≤ n, the task is to check whether the integers from 1 to n can be assigned to x and y such that all the equations are satisfied."
},
{
"code": null,
"e": 25026,
"s": 25015,
"text": "Examples: "
},
{
"code": null,
"e": 25153,
"s": 25026,
"text": "Input: x[] = {1, 2, 3}, op[] = {“=”, “=”, “!=”}, y[] = {2, 3, 1} Output: Invalid If 1 = 2 and 2 = 3 then 3 must be equal to 1."
},
{
"code": null,
"e": 25221,
"s": 25153,
"text": "Input: x[] = {1, 2}, op[] = {“=”, “=”}, y[] = {2, 3} Output: Valid "
},
{
"code": null,
"e": 25655,
"s": 25221,
"text": "Approach: The idea is to use union-find. For each statement check if there exists “=” sign then find the parent values for the two variables and union them using the rank method. Now once the union has been done for all the variables having “=” operator between them, start checking for “!=” operator, if this operator exists between any two variables whose parents are the same then the expressions are invalid, else they are valid."
},
{
"code": null,
"e": 25706,
"s": 25655,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25710,
"s": 25706,
"text": "C++"
},
{
"code": null,
"e": 25715,
"s": 25710,
"text": "Java"
},
{
"code": null,
"e": 25723,
"s": 25715,
"text": "Python3"
},
{
"code": null,
"e": 25726,
"s": 25723,
"text": "C#"
},
{
"code": null,
"e": 25737,
"s": 25726,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the parent of an integerint findParent(int i, vector<int> parent){ if (parent[i] == i) return i; return findParent(parent[i], parent);} // Find union for both the integers x and y// using rank methodvoid findUnion(int x, int y, vector<int>& parent, vector<int>& rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if (rank[xroot] > rank[yroot]) { parent[y] = x; rank[xroot]++; } else if (rank[x] < rank[y]) { parent[x] = y; rank[yroot]++; } else { parent[y] = x; rank[xroot]++; } }} // Function that returns true if// the expression is invalidbool isInvalid(vector<int> u, vector<int> v, vector<string> op, int n){ // Vector to store parent values // of each integer vector<int> parent; // Vector to store rank // of each integer vector<int> rank; parent.push_back(-1); rank.push_back(-1); // Initialize parent values for // each of the integers for (int i = 1; i <= n; i++) parent.push_back(i); // Initialize rank values for // each of the integers for (int i = 1; i <= n; i++) rank.push_back(0); // Check for = operator and find union // for them for (int i = 0; i < n; i++) if (op[i] == \"=\") findUnion(u[i], v[i], parent, rank); // Check for != operator for (int i = 0; i < n; i++) { if (op[i] == \"!=\") { // If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)) return true; } } // Expression is valid return false;} // Driver codeint main(){ vector<int> u; vector<int> v; vector<string> op; // Store the first integer u.push_back(1); u.push_back(2); u.push_back(3); // Store the second integer v.push_back(2); v.push_back(3); v.push_back(1); // Store the operators op.push_back(\"=\"); op.push_back(\"=\"); op.push_back(\"!=\"); // Number of expressions int n = u.size(); if (isInvalid(u, v, op, n)) cout << \"Invalid\"; else cout << \"Valid\"; return 0;}",
"e": 28113,
"s": 25737,
"text": null
},
{
"code": "// Java implementation of// the above approachimport java.util.*;class GFG{ // Function to return the parent// of an integerpublic static int findParent(int i, Vector parent){ if ((int)parent.get(i) == i) return i; return findParent((int)parent.get(i), parent);} // Find union for both the integers x and y// using rank methodpublic static void findUnion(int x, int y, Vector parent, Vector rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if ((int)rank.get(xroot) > (int)rank.get(yroot)) { parent.set(y,x); rank.set(xroot, (int)rank.get(xroot) + 1); } else if ((int)rank.get(x) < (int)rank.get(y)) { parent.set(x,y); rank.set(yroot, (int)rank.get(yroot) + 1); } else { parent.set(y,x); rank.set(xroot, (int)rank.get(xroot) + 1); } }} // Function that returns true if// the expression is invalidpublic static boolean isInvalid(Vector u, Vector v, Vector op, int n){ // To store parent values // of each integer Vector parent = new Vector(); // To store rank // of each integer Vector rank = new Vector(); parent.add(-1); rank.add(-1); // Initialize parent values for // each of the integers for(int i = 1; i <= n; i++) parent.add(i); // Initialize rank values for // each of the integers for(int i = 1; i <= n; i++) rank.add(0); // Check for = operator and find union // for them for(int i = 0; i < n; i++) if ((String)op.get(i) == \"=\") findUnion((int)u.get(i), (int)v.get(i), parent, rank); // Check for != operator for(int i = 0; i < n; i++) { if ((String)op.get(i) == \"!=\") { // If the expression is invalid if (findParent((int)u.get(i), parent) == findParent((int)v.get(i), parent)) return true; } } // Expression is valid return false;} // Driver codepublic static void main(String[] args){ Vector u = new Vector(); Vector v = new Vector(); Vector op = new Vector(); // Store the first integer u.add(1); u.add(2); u.add(3); // Store the second integer v.add(2); v.add(3); v.add(1); // Store the operators op.add(\"=\"); op.add(\"=\"); op.add(\"!=\"); // Number of expressions int n = u.size(); if (isInvalid(u, v, op, n)) System.out.print(\"Invalid\"); else System.out.print(\"Valid\");}} // This code is contributed by divyeshrabadiya07",
"e": 30747,
"s": 28113,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the parent of an integerdef findParent(i, parent): if parent[i] == i: return i return findParent(parent[i], parent) # Find union for both the integers# x and y using rank methoddef findUnion(x, y, parent, rank): xroot = findParent(x, parent) yroot = findParent(y, parent) # Union using rank method if xroot != yroot: if rank[xroot] > rank[yroot]: parent[y] = x rank[xroot] += 1 elif rank[x] < rank[y]: parent[x] = y rank[yroot] += 1 else: parent[y] = x rank[xroot] += 1 # Function that returns true if# the expression is invaliddef isInvalid(u, v, op, n): # Vector to store parent values # of each integer parent = [] # Vector to store rank # of each integer rank = [] parent.append(-1) rank.append(-1) # Initialize parent values for # each of the integers for i in range(1, n + 1): parent.append(i) # Initialize rank values for # each of the integers for i in range(1, n + 1): rank.append(0) # Check for = operator and # find union for them for i in range(0, n): if op[i] == \"=\": findUnion(u[i], v[i], parent, rank) # Check for != operator for i in range(0, n): if op[i] == \"!=\": # If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)): return True # Expression is valid return False # Driver codeif __name__ == \"__main__\": u = [1, 2, 3] v = [2, 3, 1] op = [\"=\", \"=\", \"!=\"] # Number of expressions n = len(u) if isInvalid(u, v, op, n): print(\"Invalid\") else: print(\"Valid\") # This code is contributed by Rituraj Jain",
"e": 32613,
"s": 30747,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the parent of an integerstatic int findParent(int i, ArrayList parent){ if ((int)parent[i] == i) return i; return findParent((int)parent[i], parent);} // Find union for both the integers x and y// using rank methodstatic void findUnion(int x, int y, ArrayList parent, ArrayList rank){ int xroot = findParent(x, parent); int yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if ((int)rank[xroot] > (int)rank[yroot]) { parent[y] = x; rank[xroot] = (int)rank[xroot] + 1; } else if ((int)rank[x] < (int)rank[y]) { parent[x] = y; rank[yroot] = (int)rank[yroot] + 1; } else { parent[y] = x; rank[xroot] = (int)rank[xroot] + 1; } }} // Function that returns true if// the expression is invalidstatic bool isInvalid(ArrayList u, ArrayList v, ArrayList op, int n){ // To store parent values // of each integer ArrayList parent = new ArrayList(); // To store rank // of each integer ArrayList rank = new ArrayList(); parent.Add(-1); rank.Add(-1); // Initialize parent values for // each of the integers for(int i = 1; i <= n; i++) parent.Add(i); // Initialize rank values for // each of the integers for(int i = 1; i <= n; i++) rank.Add(0); // Check for = operator and find union // for them for(int i = 0; i < n; i++) if ((string)op[i] == \"=\") findUnion((int)u[i], (int)v[i], parent, rank); // Check for != operator for(int i = 0; i < n; i++) { if ((string)op[i] == \"!=\") { // If the expression is invalid if (findParent((int)u[i], parent) == findParent((int)v[i], parent)) return true; } } // Expression is valid return false;} // Driver Codepublic static void Main(string[] args){ ArrayList u = new ArrayList(); ArrayList v = new ArrayList(); ArrayList op = new ArrayList(); // Store the first integer u.Add(1); u.Add(2); u.Add(3); // Store the second integer v.Add(2); v.Add(3); v.Add(1); // Store the operators op.Add(\"=\"); op.Add(\"=\"); op.Add(\"!=\"); // Number of expressions int n = u.Count; if (isInvalid(u, v, op, n)) Console.Write(\"Invalid\"); else Console.Write(\"Valid\");}} // This code is contributed by rutvik_56",
"e": 35357,
"s": 32613,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to return the parent of an integerfunction findParent(i, parent){ if (parent[i] == i) return i; return findParent(parent[i], parent);} // Find union for both the integers x and y// using rank methodfunction findUnion(x, y, parent, rank) { let xroot = findParent(x, parent); let yroot = findParent(y, parent); // Union using rank method if (xroot != yroot) { if (rank[xroot] > rank[yroot]) { parent[y] = x; rank[xroot]++; } else if (rank[x] < rank[y]) { parent[x] = y; rank[yroot]++; } else { parent[y] = x; rank[xroot]++; } }} // Function that returns true if// the expression is invalidfunction isInvalid(u, v, op, n) { // Vector to store parent values // of each integer let parent = []; // Vector to store rank // of each integer let rank = []; parent.push(-1); rank.push(-1); // Initialize parent values for // each of the integers for (let i = 1; i <= n; i++) parent.push(i); // Initialize rank values for // each of the integers for (let i = 1; i <= n; i++) rank.push(0); // Check for = operator and find union // for them for (let i = 0; i < n; i++) if (op[i] == \"=\") findUnion(u[i], v[i], parent, rank); // Check for != operator for (let i = 0; i < n; i++) { if (op[i] == \"!=\") { // If the expression is invalid if (findParent(u[i], parent) == findParent(v[i], parent)) return true; } } // Expression is valid return false;} // Driver code let u = [];let v = [];let op = []; // Store the first integeru.push(1);u.push(2);u.push(3); // Store the second integerv.push(2);v.push(3);v.push(1); // Store the operatorsop.push(\"=\");op.push(\"=\");op.push(\"!=\"); // Number of expressionslet n = u.length;if (isInvalid(u, v, op, n)) document.write(\"Invalid\");else document.write(\"Valid\"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 37480,
"s": 35357,
"text": null
},
{
"code": null,
"e": 37488,
"s": 37480,
"text": "Invalid"
},
{
"code": null,
"e": 37503,
"s": 37490,
"text": "rituraj_jain"
},
{
"code": null,
"e": 37513,
"s": 37503,
"text": "rutvik_56"
},
{
"code": null,
"e": 37531,
"s": 37513,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 37548,
"s": 37531,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 37565,
"s": 37548,
"text": "arorakashish0911"
},
{
"code": null,
"e": 37576,
"s": 37565,
"text": "union-find"
},
{
"code": null,
"e": 37583,
"s": 37576,
"text": "Arrays"
},
{
"code": null,
"e": 37589,
"s": 37583,
"text": "Graph"
},
{
"code": null,
"e": 37602,
"s": 37589,
"text": "Mathematical"
},
{
"code": null,
"e": 37609,
"s": 37602,
"text": "Arrays"
},
{
"code": null,
"e": 37622,
"s": 37609,
"text": "Mathematical"
},
{
"code": null,
"e": 37628,
"s": 37622,
"text": "Graph"
},
{
"code": null,
"e": 37639,
"s": 37628,
"text": "union-find"
},
{
"code": null,
"e": 37737,
"s": 37639,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37762,
"s": 37737,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37782,
"s": 37762,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 37820,
"s": 37782,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 37905,
"s": 37820,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 37954,
"s": 37905,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 37994,
"s": 37954,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 38045,
"s": 37994,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 38083,
"s": 38045,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 38141,
"s": 38083,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
]
|
Android FrameLayout in Kotlin - GeeksforGeeks | 21 Feb, 2022
Android Framelayout is a ViewGroup subclass which is used to specify the position of multiple views placed on the top of each other to represent a single view screen.
Generally, we can say FrameLayout simply blocks a particular area on the screen to display a single view. Here, all the child views or elements are added in stack format means the most recently added child will be shown on the top of the screen.
But, we can add multiple children view and control their positions only by using gravity attributes in FrameLayout.
The FrameLayout can be defined using the code below:
xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> // Add items or widgets here</FrameLayout>
In this file, we declare the FrameLayout and start adding multiple view like textView, editText, and Button etc. All the view are placed on each other but we displace according to our requirement.
First, we add an image in the background and add other widgets on the top. On the screen, we can see the beautiful login page having an image in the background.
xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp"> <ImageView android:id="@+id/imgvw1" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/img" /> <TextView android:id="@+id/txtvw1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="#286F24" android:padding="10dp" android:text="Login Details" android:textColor="#FFFFFF" android:textSize="20sp" android:layout_marginLeft="100dp"/> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="80dp" android:background="#ECEEE8" android:padding="10dp" android:hint="Enter your email" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="150dp" android:background="#ECEEE8" android:padding="10dp" android:hint="Enter password"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text= "Submit" android:layout_marginTop="240dp" android:layout_marginLeft="110dp"/> </FrameLayout>
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById.
Kotlin
package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements }}
We need to run using Android Virtual Device(AVD) to see the output.
ayushpandey3july
Kotlin Android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
How to Build a Weather App in Android?
ImageView in Android with Example
Kotlin extension function
Kotlin Coroutines on Android
ScrollView in Android
How to Send Data From Activity to Fragment in Android?
Dagger Hilt in Android with Example
Suspend Function In Kotlin Coroutines | [
{
"code": null,
"e": 24518,
"s": 24490,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 24685,
"s": 24518,
"text": "Android Framelayout is a ViewGroup subclass which is used to specify the position of multiple views placed on the top of each other to represent a single view screen."
},
{
"code": null,
"e": 24931,
"s": 24685,
"text": "Generally, we can say FrameLayout simply blocks a particular area on the screen to display a single view. Here, all the child views or elements are added in stack format means the most recently added child will be shown on the top of the screen."
},
{
"code": null,
"e": 25047,
"s": 24931,
"text": "But, we can add multiple children view and control their positions only by using gravity attributes in FrameLayout."
},
{
"code": null,
"e": 25100,
"s": 25047,
"text": "The FrameLayout can be defined using the code below:"
},
{
"code": null,
"e": 25104,
"s": 25100,
"text": "xml"
},
{
"code": "<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> // Add items or widgets here</FrameLayout>",
"e": 25337,
"s": 25104,
"text": null
},
{
"code": null,
"e": 25534,
"s": 25337,
"text": "In this file, we declare the FrameLayout and start adding multiple view like textView, editText, and Button etc. All the view are placed on each other but we displace according to our requirement."
},
{
"code": null,
"e": 25695,
"s": 25534,
"text": "First, we add an image in the background and add other widgets on the top. On the screen, we can see the beautiful login page having an image in the background."
},
{
"code": null,
"e": 25699,
"s": 25695,
"text": "xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"5dp\"> <ImageView android:id=\"@+id/imgvw1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scaleType=\"centerCrop\" android:src=\"@drawable/img\" /> <TextView android:id=\"@+id/txtvw1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:background=\"#286F24\" android:padding=\"10dp\" android:text=\"Login Details\" android:textColor=\"#FFFFFF\" android:textSize=\"20sp\" android:layout_marginLeft=\"100dp\"/> <EditText android:id=\"@+id/editText1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"80dp\" android:background=\"#ECEEE8\" android:padding=\"10dp\" android:hint=\"Enter your email\" /> <EditText android:id=\"@+id/editText2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"150dp\" android:background=\"#ECEEE8\" android:padding=\"10dp\" android:hint=\"Enter password\"/> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text= \"Submit\" android:layout_marginTop=\"240dp\" android:layout_marginLeft=\"110dp\"/> </FrameLayout>",
"e": 27432,
"s": 25699,
"text": null
},
{
"code": null,
"e": 27605,
"s": 27432,
"text": "When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById."
},
{
"code": null,
"e": 27612,
"s": 27605,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the UI elements }}",
"e": 27964,
"s": 27612,
"text": null
},
{
"code": null,
"e": 28032,
"s": 27964,
"text": "We need to run using Android Virtual Device(AVD) to see the output."
},
{
"code": null,
"e": 28049,
"s": 28032,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 28064,
"s": 28049,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28071,
"s": 28064,
"text": "Kotlin"
},
{
"code": null,
"e": 28169,
"s": 28071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28211,
"s": 28169,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28251,
"s": 28211,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 28290,
"s": 28251,
"text": "How to Build a Weather App in Android?"
},
{
"code": null,
"e": 28324,
"s": 28290,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 28350,
"s": 28324,
"text": "Kotlin extension function"
},
{
"code": null,
"e": 28379,
"s": 28350,
"text": "Kotlin Coroutines on Android"
},
{
"code": null,
"e": 28401,
"s": 28379,
"text": "ScrollView in Android"
},
{
"code": null,
"e": 28456,
"s": 28401,
"text": "How to Send Data From Activity to Fragment in Android?"
},
{
"code": null,
"e": 28492,
"s": 28456,
"text": "Dagger Hilt in Android with Example"
}
]
|
A Comprehensive Case-Study of GraphSage with Hands-on-Experience using PyTorchGeometric Library and Open-Graph-Benchmark’s Amazon Product Recommendation Dataset | by Sachin Sharma | Towards Data Science | This blogpost provides a comprehensive study on theoretical and practical understanding of GraphSage which is an inductive graph representation learning algorithm. For a practical application we are going to use the popular PyTorch Geometric library and Open-Graph-Benchmark dataset. We use ogbn-products dataset which is an undirected and unweighted graph, representing an Amazon product co-purchasing network to predict shopping preferences. Nodes represent products sold in Amazon, and edges between two products indicate that the products are purchased together. The goal is to predict the category of a product in a multi-class classification setup, where the 47 top-level categories are used for target labels making it a Node Classification Task.
So in brief here is the outline of the blog:
What is GraphSage
Importance of Neighbourhood Sampling
Getting Hands-on Experience with GraphSage and PyTorch Geometric Library
Open-Graph-Benchmark’s Amazon Product Recommendation Dataset
Creating and Saving a model
Generating Graph Embeddings Visualisations and Observations
Power Up!!
I have conducted a Workshop on the topic “Machine Learning on Graphs with PyTorch Geometric, NVIDIA Triton, and ArangoDB: Thinking Beyond Euclidean Space”. This workshop digs deeper into the Importance of Graph Data Structures, Applications of Graph ML, Motivation behind Graph Representation Learning, How to use Graph ML in Production with Nvidia Triton Inference Server and ArangoDB using a real world application.
Once the graph is created after incorporating meaningful relationships (edges) between all the entities (nodes) of the graph. The next question comes into mind is finding a way to integrate the information about graph structure (for e.g. information about the node’s global position in the graph or its local neighbourhood structure) into a machine learning model. One way to extract structural information from the graph is to compute its graph statistics using node degrees, clustering coefficients, kernel functions or hand-engineered features to estimate local neighbourhood structures. However, with these methods we can not perform an end-to-end learning i.e features cannot be learned with the help of loss function during the training process.To tackle the above problem, representation learning approaches have been adopted to encode the structural information about the graphs into the euclidean space (vector/embedding space).
The key idea behind the graph representation learning is to learn a mapping function that embeds nodes, or entire (sub)graphs (from non-euclidean), as points in low-dimensional vector space (to embedding space). The aim is to optimize this mapping so that nodes which are nearby in the original network should also remain close to each other in the embedding space (vector space), while shoving unconnected nodes apart. Therefore by doing this, we can preserve the geometric relationships of the original network inside the embedding space by learning a mapping function. Below diagram depicts the mapping process, encoder enc maps node u and v to low-dimensional vector zu and zv :
Let’s understand this more intuitively with an interesting example from the graph structure of the Zachary Karate Club social network. In this graph, the nodes represent the persons and there exists an edge between the two persons if they are friends. The colouring in the graph represents different communities. In the below figure A) represents the Zachary Karate Club social network and B) illustrates the 2D visualisation of node embeddings created from the Karate graph using a DeepWalk method. If you analyse both the diagrams you will find that the mapping of nodes from a graph structure (non-euclidean or irregular domain) to an embedding space (figure B) is done in such a manner that the distances between nodes in the embedding space mirrors closeness in the original graph (preserving the structure of the node’s neighbourhood). For e.g the community of the people marked as violet and green shares close proximity in the karate graph as compared to the communities violet and seagreen which are far away from each other. When the DeepWalk method is applied on the karate graph (in order to learn the node embeddings) we can observe the same proximity behaviour when the learned node embeddings are visualised on 2D space.
1) It can be used as a feature inputs for downstream ML tasks (eg. community detection via node classification or link prediction)
2) We could construct a KNN/Cosine similarity graph from embeddings. The graph could be used to make recommendations (e.g product recommedation)
3) Visual exploration of data by reducing them to 2 or 3 dimensions using U-Map, t-SNE algorithms (eg. performing clustering).
4) Dataset Comparisons
5) Transfer Learning
In this blogpost/notebook, we will cover a GraphSage (Sample and Aggregate) algorithm which is an inductive (it can generalize to unseen nodes) deep learning method developed by Hamilton, Ying, and Leskovec (2017) for graphs used to generate low-dimensional vector representations for nodes. This is in contrast with the previous graph machine learning methods like Graph Convolutional Networks or DeepWalk which are inherently transductive i.e they can only generate embeddings for the nodes present in the fixed graph during the training.This implies that, if in future the graph evolves and new nodes (unseen during the training) make their way into the graph then we need to retrain the whole graph in order to compute the embeddings for the new node. This limitation makes the transductive approaches inefficient to get applied on the ever evolving graphs (like social networks, protein-protein networks, etc) because of their inability to generalize on unseen nodes. The other main limitation of transductive approaches (mainly DeepWalk or Node2Vec) is that they cannot leverage the node features e.g text attributes, node profile information, node degrees, etc.On the other hand, the GraphSage algorithm exploits both the rich node features and the topological structure of each node’s neighbourhood simultaneously to efficiently generate representations for new nodes without retraining.
1) Dynamic Graphs: These are graphs which evolve over time like social network graphs from facebook, linkedin or twitter or posts on Reddit, users and videos on Youtube.
2) Generated node embeddings via unsupervised loss function can be used for various downstream machine learning tasks like node classification, clustering, and link prediction.
3) Real-World applications which requires to compute embeddings for their subgraphs
4) Protein-Protein interaction graphs: Here, the trained embedding generator can predict the node embeddings for the data collected on new species/organisms
5) UberEats: It uses the power of Graph ML to suggest to its users the dishes, restaurants, and cuisines they might like next. To make these recommendations Uber eats uses the GraphSAGE algorithm because of its inductive nature and the power to scale up-to billion of nodes
6) Pinterest: It uses the power of PinSage (another version of GraphSage) for making visual recommendations (pins are visual bookmarks e.g. for buying clothes or other products). PinSage is a random-walk based GraphSage algorithm which learns embeddings for nodes (in billions) in web scale graphs.
The working process of GraphSage is mainly divided into two steps, first performing neighbourhood sampling of an input graph and the second one is learning aggregation functions at each search depth. We will discuss each of these steps in detail starting with a little motivation of what was the need to perform the sampling of nodes neighbourhood. Afterwards, we will discuss the importance of learning aggregator functions which basically had helped GraphSage algorithm to achieve its property of inductiveness.
Let’s understand this from the perspective of Graph Convolutional Network diagram (GCNs) described below. GCNs is an algorithm which can leverage both the graph topological information (i.e. node’s neighbourhood) and node features and then distill this information in order to generate node representations or dense vector embeddings. The below diagram represents the working process of GCNs intuitively. On the left hand side we have a sample input graph where its nodes are represented by their corresponding feature vectors (for e.g. node degree or text embeddings, etc). We start with defining a search depth (K) which informs the algorithm upto what depth it should gather the information from the neighbourhood of a target node. Here, K is a hyperparameter and it also depicts the number of layers used in the GCNs.
At K=0, GCNs initialises all the node embeddings to their original feature vector. Now, let’s say we want to compute the embeddings for the target node 0 at layer K=1, then we aggregate (it is permutation invariant function to its neighbours) all the feature vectors of nodes (including itself) which are at 1-hop distance from the node 0 (at this timestep or layer we are aggregating the original feature representations of nodes which are at K=0). For the target node 0, GCNs uses a mean aggregator to compute the mean of the neighbourhood node features along with its own features (self-loop). After K=1, the target node 0 now knows about the information about its immediate neighbourhood; this process is shown below in the GCNs image (r.h.s). We repeat this process for all the nodes in the graph (i.e. for every node, we aggregate over the 1-hop neighbourhood) in order to find the new representations for each node at each layer.
Note: As the search depth increases, the reach of the target node in terms of aggregating features from its local neighbourhood also increases. For e.g. at K=1 the target node knows the information about its local neighbourhood which are 1-hop distance, at K=2 the target node knows the information about its local neighbourhood which are at 1-hop distance and the neighbours of the nodes of 1-hop distance i.e upto 2-hop distance.
As we have discussed above, that GCNs compute node representations using neighbourhood aggregation. For the training purposes, we can represent the k-hop neighbourhood of a target node as a computational graph and send these computational graphs in a mini-batch fashion in order to learn the weights of the network (i.e. applying stochastic gradient descent). The below diagram illustrates a computational graph for the target node 0 upto 2-hop neighbourhood. Now, the problem with this is that:
1) Computationally Expensive: Since for each node, we need to generate the complete K-hop neighbourhood computational graph and then need to aggregate plenty of information from its surroundings. As we go deeper into the neighbourhood (large K) computation graph becomes exponentially large. This could lead to a problem while fitting these big computational graphs inside GPU memory.
2) The curse of Hub nodes or Celebrity nodes: Hub nodes are those nodes which are very high degree nodes in the graph for eg. a very popular celebrity having millions of connections. If that is the case then we need to aggregate the information from millions of nodes in order to compute the embeddings for the hub node. Therefore, the generated computational graph for the hub node is very huge. This problem is illustrated below diagrammatically (r.h.s).
Therefore, the idea is not take the entire K-hop neighbourhood of a target node but select few nodes at random from the K-hop neighbourhood in order to generate computational graph. This process is known as neighbourhood sampling which provides the GraphSage algorithm its unique ability of scaling up to billion of nodes in the graph. Therefore, using this approach if we encounter any hub node then we are not going to take its entire K-hop neighbourhood but rather select few nodes at random from each layer or search depth K. Now, the generated computational graph is more efficient to handle by the GPU. Below diagram shows this process by sampling at most 2 neighbours at each hop.
GraphSage is an inductive version of GCNs which implies that it does not require the whole graph structure during learning and it can generalize well to the unseen nodes. It is a branch of graph neural networks that learns node representations by sampling and aggregating neighbours from multiple search depths or hops.Its inductive property is based upon the premises that we don’t need to learn the embeddings for each node but rather learn an aggregation function (could be any differentiable function like mean, pooling or lstm) which when given an information (or features) from the local neighbourhood of a node then it knows how to aggregate those features (learning takes place via stochastic gradient descent) such that the aggregated feature representation of a node v now includes the information about its local surroundings or neighbourhood.
The GraphSage is different from GCNs in two ways: i.e. 1) Instead of taking the entire K-hop neighbourhood of a target node, GraphSage first samples or prune the K-hop neighbourhood computation graph and then perform the feature aggregation operation on this sampled graph in order to generate the embeddings for a target node. 2) During the learning process, in order to generate the node embeddings; GraphSage learns the aggregator function whereas GCNs make use of the symmetrically normalized graph Laplacian.
The below diagram illustrates how GraphSage node 0 aggregates information from its sampled local neighbours at search depth K=1. If we observe the r.h.s graph, we will find out that at K=1 the target node 0 is now having the information about its surroundings upto 1-hop.
As explained above, the key concept of GraphSage is to learn how to aggregate feature information from a node’s local neighbourhood. Now, let’s understand more formally how the GraphSage generates node embedding at each layer (K) using forward propagation. We understand this with the help of visuals and then map this understanding to a pseudocode mentioned in the GraphSage paper. But before that, let’s define some notations which are used in the paper.
Defining Notations:
As seen in the above GraphSage diagram that at K=1, the target node 0 aggregates information (features) from its local neighbours upto 1-hop. Similarly at k=2, the target node 0 aggregates information from its local neighbours upto 2-hops i.e now it knows what lies in its neighbourhood upto 2-hops. Therefore, we can iterate this process where target node 0 incrementally obtain more and more information from further reaches of the graph. We do this process of information gathering for each of the nodes in the original graph (∀v ∈ V). Lets add some visuals to understand this iterative process much more intuitively:
The following image depicts the computation graph of a target node 0 at layer K=0, at this point of time all the nodes in the graph are initialised to their original feature vectors. Our aim is to find the final representation of node 0 (i.e z0) at layer K=2 through an iterative local neighbourhood information gathering process. This iterative process is also sometime known as message passing approach .
Therefore, we can represent this step formally as :
Note: Since medium does not support subscript, I will write the hidden layer (h) representation as: (superscript) h (subscript).
superscript denotes -> Kth layer
subscript denotes -> Node id
Since nodes gather the information incrementally from the deeper depths of the graph, we start our iteration process from search depth 1....K. At K=1, we aggregate neighbouring node representations for our target node 0 (1h0), i.e node 2 and 3 representations which were at previous layer (K-1h2 and K-1h3) into a single vector. Here 1h0 is an aggregated representation. At the same time step, nodes 2, 3, and 9 will also aggregate the feature vectors from their respective local neighbourhoods upto distance of 1-hop. Now at this point of time, each of the nodes in a computation graph knows what kind of information lies in their immediate surroundings.
Therefore, we can represent this step formally as :
Once we achieve the aggregated representation i.e 1h0, the next step would be to concatenate or combine this aggregated representation with its previous layer representation (0h0). Then transformation is applied on this concatenated output by multiplying it with a weight matrix WK, you can think of this process similar to applying convolutional kernels (learnable weight matrices) on images in order to extract features from it. At the end, we apply a non-linear activation function on this transformed output making it capable to learn and perform more complex tasks.
Important Note: The GraphSage algorithm learns the weight matrix individually at each search depth K or you can also say that it learns how to aggregate information from a node’s neighbourhood at each search depth.
Hence, we can represent this step formally as :
Subsequently, normalization is applied on node representation khv (or at this time step 1h0) which helps the algorithm to maintain the general distribution of node embeddings. This step is computed as :
The information gathering from node’s local neighbourhood at K=1 is completed. At K=2, nodes explore the further reaches of the graph i.e going beyond their immediate neighbourhoods and looking into a hop distance of 2. Again we perform the node’s local neighbourhood aggregation, but this time the target node 0 will now have the information of its neighbours which are at 1-hop and 2-hop distances. Then again we repeat the process of updation and normalisation for the search depth K=2. Since we have set the value of K=2 for understanding the flow of the GraphSage algorithm therefore, we will stop here. After K=2, each node in the computation graph is represented by their respective final node embeddings i.e. zv.
This workflow is shown below in the image:
Authors have recorded the results in the paper by using two different types of loss functions which are as following:
Unsupervised Case: As described in the graph representation learning section, the aim is to optimize the mapping so that nodes which are nearby in the original network should also remain close to each other in the embedding space (vector space), while shoving unconnected nodes apart.
Supervised Case: Authors use regular cross-entropy loss for performing the task of node classification.
Below is the unsupervised loss function used in the paper:
We will understand the working process of GraphSage in more detail with the help of a real world dataset from the Open Graph Benchmark (OGB) datasets. The OGB is a collection of realistic, large-scale, and diverse benchmark datasets for machine learning on graphs developed by Stanford University.
Lot of code ahead, if you are interested in getting your hands dirty with the code which I would really encourage you to do so, then I have already prepared a google colab notebook with which you can play around....
We use obgn-products dataset which is an undirected and unweighted graph, representing an Amazon product co-purchasing network. Nodes represent products sold in Amazon, and edges between two products indicate that the products are purchased together. Node features represent bag-of-words features taken from the product descriptions. The goal is to predict the category of a product in a multi-class classification setup, where the 47 top-level categories are used for target labels making it a Node Classification Task.
# Installing Pytorch Geometric %%capture!pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-cluster -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-geometric!pip install ogb!pip install umap-learn
Importing Necessary Libraries
import torchimport torch.nn.functional as Ffrom tqdm import tqdmfrom torch_geometric.data import NeighborSamplerfrom torch_geometric.nn import SAGEConvimport os.path as ospimport pandas as pdimport numpy as npimport collectionsfrom pandas.core.common import flatten# importing obg datatsetfrom ogb.nodeproppred import PygNodePropPredDataset, Evaluatorfrom pandas.core.common import flattenimport seaborn as snsimport matplotlib.pyplot as pltsns.set(rc={'figure.figsize':(16.7,8.27)})sns.set_theme(style="ticks")import collectionsfrom scipy.special import softmaximport umap
Download and load dataset
root = osp.join(osp.dirname(osp.realpath('./')), 'data', 'products')dataset = PygNodePropPredDataset('ogbn-products', root)
Getting train, validation and test index
# split_idx contains a dictionary of train, validation and test node indicessplit_idx = dataset.get_idx_split()# predefined ogb evaluator method used for validation of predictionsevaluator = Evaluator(name='ogbn-products')
Let’s check the training, validation and test node split.
# lets check the node ids distribution of train, test and valprint('Number of training nodes:', split_idx['train'].size(0))print('Number of validation nodes:', split_idx['valid'].size(0))print('Number of test nodes:', split_idx['test'].size(0))Number of training nodes: 196615Number of validation nodes: 39323Number of test nodes: 2213091
Loading the dataset
data = dataset[0]
Graph Statistics
# lets check some graph statistics of ogb-product graphprint("Number of nodes in the graph:", data.num_nodes)print("Number of edges in the graph:", data.num_edges)print("Node feature matrix with shape:", data.x.shape) # [num_nodes, num_node_features]print("Graph connectivity in COO format with shape:", data.edge_index.shape) # [2, num_edges]print("Target to train against :", data.y.shape) print("Node feature length", dataset.num_features)Number of nodes in the graph: 2449029Number of edges in the graph: 123718280Node feature matrix with shape: torch.Size([2449029, 100])Graph connectivity in COO format with shape: torch.Size([2, 123718280])Target to train against : torch.Size([2449029, 1])Node feature length 100
Checking the number of unique labels
# there are 47 unique categories of productdata.y.unique()
Load integer to real product category from label mapping provided inside the dataset
df = pd.read_csv('/data/products/ogbn_products/mapping/labelidx2productcategory.csv.gz')
Let’s see some of the product categories
df[:10]
Creating a dictionary of product category and corresponding integer label
label_idx, prod_cat = df.iloc[: ,0].values, df.iloc[: ,1].valueslabel_mapping = dict(zip(label_idx, prod_cat))# counting the numbers of samples for each categoryy = data.y.tolist()y = list(flatten(y))count_y = collections.Counter(y)print(count_y)
This module iteratively samples neighbours (at each layer) and constructs bipartite graphs that simulate the actual computation flow of GNNs.
sizes: denotes how much neighbours we want to sample for each node in each layer.
NeighborSampler holds the current :obj:batch_size, the IDs :obj:n_id of all nodes involved in the computation, and a list of bipartite graph objects via the tuple :obj:(edge_index, e_id, size), where :obj:edge_index represents the bipartite edges between source and target nodes, :obj:e_id denotes the IDs of original edges in the full graph, and :obj:size holds the shape of the bipartite graph.
The actual computation graphs are then returned in reverse-mode, meaning that we pass messages from a larger set of nodes to a smaller one, until we reach the nodes for which we originally wanted to compute embeddings.
train_idx = split_idx['train']train_loader = NeighborSampler(data.edge_index, node_idx=train_idx, sizes=[15, 10, 5], batch_size=1024, shuffle=True)
class SAGE(torch.nn.Module): def __init__(self, in_channels, hidden_channels, out_channels, num_layers=3): super(SAGE, self).__init__() self.num_layers = num_layers self.convs = torch.nn.ModuleList() self.convs.append(SAGEConv(in_channels, hidden_channels)) for _ in range(num_layers - 2): self.convs.append(SAGEConv(hidden_channels, hidden_channels)) self.convs.append(SAGEConv(hidden_channels, out_channels)) def reset_parameters(self): for conv in self.convs: conv.reset_parameters() def forward(self, x, adjs): # `train_loader` computes the k-hop neighborhood of a batch of nodes, # and returns, for each layer, a bipartite graph object, holding the # bipartite edges `edge_index`, the index `e_id` of the original edges, # and the size/shape `size` of the bipartite graph. # Target nodes are also included in the source nodes so that one can # easily apply skip-connections or add self-loops. for i, (edge_index, _, size) in enumerate(adjs): xs = [] x_target = x[:size[1]] # Target nodes are always placed first. x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = F.relu(x) x = F.dropout(x, p=0.5, training=self.training) xs.append(x) if i == 0: x_all = torch.cat(xs, dim=0) layer_1_embeddings = x_all elif i == 1: x_all = torch.cat(xs, dim=0) layer_2_embeddings = x_all elif i == 2: x_all = torch.cat(xs, dim=0) layer_3_embeddings = x_all #return x.log_softmax(dim=-1) return layer_1_embeddings, layer_2_embeddings, layer_3_embeddings def inference(self, x_all): pbar = tqdm(total=x_all.size(0) * self.num_layers) pbar.set_description('Evaluating') # Compute representations of nodes layer by layer, using *all* # available edges. This leads to faster computation in contrast to # immediately computing the final representations of each batch. total_edges = 0 for i in range(self.num_layers): xs = [] for batch_size, n_id, adj in subgraph_loader: edge_index, _, size = adj.to(device) total_edges += edge_index.size(1) x = x_all[n_id].to(device) x_target = x[:size[1]] x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = F.relu(x) xs.append(x) pbar.update(batch_size) if i == 0: x_all = torch.cat(xs, dim=0) layer_1_embeddings = x_all elif i == 1: x_all = torch.cat(xs, dim=0) layer_2_embeddings = x_all elif i == 2: x_all = torch.cat(xs, dim=0) layer_3_embeddings = x_all pbar.close() return layer_1_embeddings, layer_2_embeddings, layer_3_embeddings
Instantiate model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')model = SAGE(dataset.num_features, 256, dataset.num_classes, num_layers=3)model = model.to(device)
Load Node Feature Matrix and Node labels
x = data.x.to(device)y = data.y.squeeze().to(device)
Training
def train(epoch): model.train() #pbar = tqdm(total=train_idx.size(0)) #pbar.set_description(f'Epoch {epoch:02d}') total_loss = total_correct = 0 for batch_size, n_id, adjs in train_loader: # `adjs` holds a list of `(edge_index, e_id, size)` tuples. adjs = [adj.to(device) for adj in adjs] optimizer.zero_grad() l1_emb, l2_emb, l3_emb = model(x[n_id], adjs) #print("Layer 1 embeddings", l1_emb.shape) #print("Layer 2 embeddings", l1_emb.shape) out = l3_emb.log_softmax(dim=-1) loss = F.nll_loss(out, y[n_id[:batch_size]]) loss.backward() optimizer.step() total_loss += float(loss) total_correct += int(out.argmax(dim=-1).eq(y[n_id[:batch_size]]).sum()) #pbar.update(batch_size) #pbar.close() loss = total_loss / len(train_loader) approx_acc = total_correct / train_idx.size(0) return loss, approx_acc
Epochs!!
optimizer = torch.optim.Adam(model.parameters(), lr=0.003)for epoch in range(1, 21): loss, acc = train(epoch) print(f'Epoch {epoch:02d}, Loss: {loss:.4f}, Approx. Train: {acc:.4f}')
We need to save the model for the inference part because google colab cannot create two graph loaders at the same time because of the limitation of the RAM size. Therefore, we first train with train_loader and then make inferences on test data using this saved model.
Here you can either save the model on google MyDrive or locally on your computer.
#torch.save(model, '/content/drive/MyDrive/model_weights/graph_embeddings/model.pt')# saving model in mydrivefrom google.colab import drivedrive.mount('/content/drive')fp = '/content/drive/MyDrive/model.pt'torch.save(model, './model.pt')torch.save(model, fp)
This part includes making the use of trained GraphSage model in order to compute node embeddings and performing node category prediction on test data. Afterwards, we compare the U-Map visualisations of node embeddings at 3 different layers of GraphSage and draw some interesting observations.
It would be much more useful to a reader if he/she runs the inference part of GraphSage in google colab notebook which I have prepared in order to get better intuition on how the visualisations at each layer of GraphSage is computed.
Node embeddings visualization at layer-1 shows that the model is not able to separate the product categories well (as the embeddings of different product categories are very close together ), therefore we cannot predict/estimate with high probability which two products can be bought together in the future or if someone buys one product then which other product he/she might also be interested.
At layer-2 we can see some separate clusters of product categories forming and we can draw some valuable insights from their for e.g. movies&TV vs CDs&Vinyl, Beauty vs health & personal care, video games vs toys & games. However, books and beauty clusters are very far away from each other.
At layer-3 node representations are little more finer than the layer-2 as we can see some more distant clusters for eg. cell phones & accessories vs electronics.
I would like to thanks the whole ML team of ArangoDB for providing me the valuable feedback about the blog.
Want to connect with me: Linkedin
https://www.arangodb.com/2021/08/a-comprehensive-case-study-of-graphsage-using-pytorchgeometric/?utm_content=176620548&utm_medium=social&utm_source=linkedin&hss_channel=lcp-5289249 (The original blogpost)Inductive Representation Learning on Large Graphshttp://web.stanford.edu/class/cs224w/slides/17-scalable.pdfA Voyage through Graph Machine Learning Universe: Motivation, Applications, Datasets, Graph ML Libraries, Graph Databaseshttps://medium.com/pinterest-engineering/pinsage-a-new-graph-convolutional-neural-network-for-web-scale-recommender-systems-88795a107f48https://eng.uber.com/uber-eats-graph-learning/More stuff related to Graph ML
https://www.arangodb.com/2021/08/a-comprehensive-case-study-of-graphsage-using-pytorchgeometric/?utm_content=176620548&utm_medium=social&utm_source=linkedin&hss_channel=lcp-5289249 (The original blogpost)
Inductive Representation Learning on Large Graphs
http://web.stanford.edu/class/cs224w/slides/17-scalable.pdf
A Voyage through Graph Machine Learning Universe: Motivation, Applications, Datasets, Graph ML Libraries, Graph Databases
https://medium.com/pinterest-engineering/pinsage-a-new-graph-convolutional-neural-network-for-web-scale-recommender-systems-88795a107f48
https://eng.uber.com/uber-eats-graph-learning/
More stuff related to Graph ML | [
{
"code": null,
"e": 926,
"s": 172,
"text": "This blogpost provides a comprehensive study on theoretical and practical understanding of GraphSage which is an inductive graph representation learning algorithm. For a practical application we are going to use the popular PyTorch Geometric library and Open-Graph-Benchmark dataset. We use ogbn-products dataset which is an undirected and unweighted graph, representing an Amazon product co-purchasing network to predict shopping preferences. Nodes represent products sold in Amazon, and edges between two products indicate that the products are purchased together. The goal is to predict the category of a product in a multi-class classification setup, where the 47 top-level categories are used for target labels making it a Node Classification Task."
},
{
"code": null,
"e": 971,
"s": 926,
"text": "So in brief here is the outline of the blog:"
},
{
"code": null,
"e": 989,
"s": 971,
"text": "What is GraphSage"
},
{
"code": null,
"e": 1026,
"s": 989,
"text": "Importance of Neighbourhood Sampling"
},
{
"code": null,
"e": 1099,
"s": 1026,
"text": "Getting Hands-on Experience with GraphSage and PyTorch Geometric Library"
},
{
"code": null,
"e": 1160,
"s": 1099,
"text": "Open-Graph-Benchmark’s Amazon Product Recommendation Dataset"
},
{
"code": null,
"e": 1188,
"s": 1160,
"text": "Creating and Saving a model"
},
{
"code": null,
"e": 1248,
"s": 1188,
"text": "Generating Graph Embeddings Visualisations and Observations"
},
{
"code": null,
"e": 1259,
"s": 1248,
"text": "Power Up!!"
},
{
"code": null,
"e": 1677,
"s": 1259,
"text": "I have conducted a Workshop on the topic “Machine Learning on Graphs with PyTorch Geometric, NVIDIA Triton, and ArangoDB: Thinking Beyond Euclidean Space”. This workshop digs deeper into the Importance of Graph Data Structures, Applications of Graph ML, Motivation behind Graph Representation Learning, How to use Graph ML in Production with Nvidia Triton Inference Server and ArangoDB using a real world application."
},
{
"code": null,
"e": 2615,
"s": 1677,
"text": "Once the graph is created after incorporating meaningful relationships (edges) between all the entities (nodes) of the graph. The next question comes into mind is finding a way to integrate the information about graph structure (for e.g. information about the node’s global position in the graph or its local neighbourhood structure) into a machine learning model. One way to extract structural information from the graph is to compute its graph statistics using node degrees, clustering coefficients, kernel functions or hand-engineered features to estimate local neighbourhood structures. However, with these methods we can not perform an end-to-end learning i.e features cannot be learned with the help of loss function during the training process.To tackle the above problem, representation learning approaches have been adopted to encode the structural information about the graphs into the euclidean space (vector/embedding space)."
},
{
"code": null,
"e": 3298,
"s": 2615,
"text": "The key idea behind the graph representation learning is to learn a mapping function that embeds nodes, or entire (sub)graphs (from non-euclidean), as points in low-dimensional vector space (to embedding space). The aim is to optimize this mapping so that nodes which are nearby in the original network should also remain close to each other in the embedding space (vector space), while shoving unconnected nodes apart. Therefore by doing this, we can preserve the geometric relationships of the original network inside the embedding space by learning a mapping function. Below diagram depicts the mapping process, encoder enc maps node u and v to low-dimensional vector zu and zv :"
},
{
"code": null,
"e": 4534,
"s": 3298,
"text": "Let’s understand this more intuitively with an interesting example from the graph structure of the Zachary Karate Club social network. In this graph, the nodes represent the persons and there exists an edge between the two persons if they are friends. The colouring in the graph represents different communities. In the below figure A) represents the Zachary Karate Club social network and B) illustrates the 2D visualisation of node embeddings created from the Karate graph using a DeepWalk method. If you analyse both the diagrams you will find that the mapping of nodes from a graph structure (non-euclidean or irregular domain) to an embedding space (figure B) is done in such a manner that the distances between nodes in the embedding space mirrors closeness in the original graph (preserving the structure of the node’s neighbourhood). For e.g the community of the people marked as violet and green shares close proximity in the karate graph as compared to the communities violet and seagreen which are far away from each other. When the DeepWalk method is applied on the karate graph (in order to learn the node embeddings) we can observe the same proximity behaviour when the learned node embeddings are visualised on 2D space."
},
{
"code": null,
"e": 4665,
"s": 4534,
"text": "1) It can be used as a feature inputs for downstream ML tasks (eg. community detection via node classification or link prediction)"
},
{
"code": null,
"e": 4810,
"s": 4665,
"text": "2) We could construct a KNN/Cosine similarity graph from embeddings. The graph could be used to make recommendations (e.g product recommedation)"
},
{
"code": null,
"e": 4937,
"s": 4810,
"text": "3) Visual exploration of data by reducing them to 2 or 3 dimensions using U-Map, t-SNE algorithms (eg. performing clustering)."
},
{
"code": null,
"e": 4960,
"s": 4937,
"text": "4) Dataset Comparisons"
},
{
"code": null,
"e": 4981,
"s": 4960,
"text": "5) Transfer Learning"
},
{
"code": null,
"e": 6377,
"s": 4981,
"text": "In this blogpost/notebook, we will cover a GraphSage (Sample and Aggregate) algorithm which is an inductive (it can generalize to unseen nodes) deep learning method developed by Hamilton, Ying, and Leskovec (2017) for graphs used to generate low-dimensional vector representations for nodes. This is in contrast with the previous graph machine learning methods like Graph Convolutional Networks or DeepWalk which are inherently transductive i.e they can only generate embeddings for the nodes present in the fixed graph during the training.This implies that, if in future the graph evolves and new nodes (unseen during the training) make their way into the graph then we need to retrain the whole graph in order to compute the embeddings for the new node. This limitation makes the transductive approaches inefficient to get applied on the ever evolving graphs (like social networks, protein-protein networks, etc) because of their inability to generalize on unseen nodes. The other main limitation of transductive approaches (mainly DeepWalk or Node2Vec) is that they cannot leverage the node features e.g text attributes, node profile information, node degrees, etc.On the other hand, the GraphSage algorithm exploits both the rich node features and the topological structure of each node’s neighbourhood simultaneously to efficiently generate representations for new nodes without retraining."
},
{
"code": null,
"e": 6547,
"s": 6377,
"text": "1) Dynamic Graphs: These are graphs which evolve over time like social network graphs from facebook, linkedin or twitter or posts on Reddit, users and videos on Youtube."
},
{
"code": null,
"e": 6724,
"s": 6547,
"text": "2) Generated node embeddings via unsupervised loss function can be used for various downstream machine learning tasks like node classification, clustering, and link prediction."
},
{
"code": null,
"e": 6808,
"s": 6724,
"text": "3) Real-World applications which requires to compute embeddings for their subgraphs"
},
{
"code": null,
"e": 6965,
"s": 6808,
"text": "4) Protein-Protein interaction graphs: Here, the trained embedding generator can predict the node embeddings for the data collected on new species/organisms"
},
{
"code": null,
"e": 7239,
"s": 6965,
"text": "5) UberEats: It uses the power of Graph ML to suggest to its users the dishes, restaurants, and cuisines they might like next. To make these recommendations Uber eats uses the GraphSAGE algorithm because of its inductive nature and the power to scale up-to billion of nodes"
},
{
"code": null,
"e": 7538,
"s": 7239,
"text": "6) Pinterest: It uses the power of PinSage (another version of GraphSage) for making visual recommendations (pins are visual bookmarks e.g. for buying clothes or other products). PinSage is a random-walk based GraphSage algorithm which learns embeddings for nodes (in billions) in web scale graphs."
},
{
"code": null,
"e": 8052,
"s": 7538,
"text": "The working process of GraphSage is mainly divided into two steps, first performing neighbourhood sampling of an input graph and the second one is learning aggregation functions at each search depth. We will discuss each of these steps in detail starting with a little motivation of what was the need to perform the sampling of nodes neighbourhood. Afterwards, we will discuss the importance of learning aggregator functions which basically had helped GraphSage algorithm to achieve its property of inductiveness."
},
{
"code": null,
"e": 8874,
"s": 8052,
"text": "Let’s understand this from the perspective of Graph Convolutional Network diagram (GCNs) described below. GCNs is an algorithm which can leverage both the graph topological information (i.e. node’s neighbourhood) and node features and then distill this information in order to generate node representations or dense vector embeddings. The below diagram represents the working process of GCNs intuitively. On the left hand side we have a sample input graph where its nodes are represented by their corresponding feature vectors (for e.g. node degree or text embeddings, etc). We start with defining a search depth (K) which informs the algorithm upto what depth it should gather the information from the neighbourhood of a target node. Here, K is a hyperparameter and it also depicts the number of layers used in the GCNs."
},
{
"code": null,
"e": 9811,
"s": 8874,
"text": "At K=0, GCNs initialises all the node embeddings to their original feature vector. Now, let’s say we want to compute the embeddings for the target node 0 at layer K=1, then we aggregate (it is permutation invariant function to its neighbours) all the feature vectors of nodes (including itself) which are at 1-hop distance from the node 0 (at this timestep or layer we are aggregating the original feature representations of nodes which are at K=0). For the target node 0, GCNs uses a mean aggregator to compute the mean of the neighbourhood node features along with its own features (self-loop). After K=1, the target node 0 now knows about the information about its immediate neighbourhood; this process is shown below in the GCNs image (r.h.s). We repeat this process for all the nodes in the graph (i.e. for every node, we aggregate over the 1-hop neighbourhood) in order to find the new representations for each node at each layer."
},
{
"code": null,
"e": 10243,
"s": 9811,
"text": "Note: As the search depth increases, the reach of the target node in terms of aggregating features from its local neighbourhood also increases. For e.g. at K=1 the target node knows the information about its local neighbourhood which are 1-hop distance, at K=2 the target node knows the information about its local neighbourhood which are at 1-hop distance and the neighbours of the nodes of 1-hop distance i.e upto 2-hop distance."
},
{
"code": null,
"e": 10739,
"s": 10243,
"text": "As we have discussed above, that GCNs compute node representations using neighbourhood aggregation. For the training purposes, we can represent the k-hop neighbourhood of a target node as a computational graph and send these computational graphs in a mini-batch fashion in order to learn the weights of the network (i.e. applying stochastic gradient descent). The below diagram illustrates a computational graph for the target node 0 upto 2-hop neighbourhood. Now, the problem with this is that:"
},
{
"code": null,
"e": 11124,
"s": 10739,
"text": "1) Computationally Expensive: Since for each node, we need to generate the complete K-hop neighbourhood computational graph and then need to aggregate plenty of information from its surroundings. As we go deeper into the neighbourhood (large K) computation graph becomes exponentially large. This could lead to a problem while fitting these big computational graphs inside GPU memory."
},
{
"code": null,
"e": 11581,
"s": 11124,
"text": "2) The curse of Hub nodes or Celebrity nodes: Hub nodes are those nodes which are very high degree nodes in the graph for eg. a very popular celebrity having millions of connections. If that is the case then we need to aggregate the information from millions of nodes in order to compute the embeddings for the hub node. Therefore, the generated computational graph for the hub node is very huge. This problem is illustrated below diagrammatically (r.h.s)."
},
{
"code": null,
"e": 12269,
"s": 11581,
"text": "Therefore, the idea is not take the entire K-hop neighbourhood of a target node but select few nodes at random from the K-hop neighbourhood in order to generate computational graph. This process is known as neighbourhood sampling which provides the GraphSage algorithm its unique ability of scaling up to billion of nodes in the graph. Therefore, using this approach if we encounter any hub node then we are not going to take its entire K-hop neighbourhood but rather select few nodes at random from each layer or search depth K. Now, the generated computational graph is more efficient to handle by the GPU. Below diagram shows this process by sampling at most 2 neighbours at each hop."
},
{
"code": null,
"e": 13124,
"s": 12269,
"text": "GraphSage is an inductive version of GCNs which implies that it does not require the whole graph structure during learning and it can generalize well to the unseen nodes. It is a branch of graph neural networks that learns node representations by sampling and aggregating neighbours from multiple search depths or hops.Its inductive property is based upon the premises that we don’t need to learn the embeddings for each node but rather learn an aggregation function (could be any differentiable function like mean, pooling or lstm) which when given an information (or features) from the local neighbourhood of a node then it knows how to aggregate those features (learning takes place via stochastic gradient descent) such that the aggregated feature representation of a node v now includes the information about its local surroundings or neighbourhood."
},
{
"code": null,
"e": 13638,
"s": 13124,
"text": "The GraphSage is different from GCNs in two ways: i.e. 1) Instead of taking the entire K-hop neighbourhood of a target node, GraphSage first samples or prune the K-hop neighbourhood computation graph and then perform the feature aggregation operation on this sampled graph in order to generate the embeddings for a target node. 2) During the learning process, in order to generate the node embeddings; GraphSage learns the aggregator function whereas GCNs make use of the symmetrically normalized graph Laplacian."
},
{
"code": null,
"e": 13910,
"s": 13638,
"text": "The below diagram illustrates how GraphSage node 0 aggregates information from its sampled local neighbours at search depth K=1. If we observe the r.h.s graph, we will find out that at K=1 the target node 0 is now having the information about its surroundings upto 1-hop."
},
{
"code": null,
"e": 14367,
"s": 13910,
"text": "As explained above, the key concept of GraphSage is to learn how to aggregate feature information from a node’s local neighbourhood. Now, let’s understand more formally how the GraphSage generates node embedding at each layer (K) using forward propagation. We understand this with the help of visuals and then map this understanding to a pseudocode mentioned in the GraphSage paper. But before that, let’s define some notations which are used in the paper."
},
{
"code": null,
"e": 14387,
"s": 14367,
"text": "Defining Notations:"
},
{
"code": null,
"e": 15008,
"s": 14387,
"text": "As seen in the above GraphSage diagram that at K=1, the target node 0 aggregates information (features) from its local neighbours upto 1-hop. Similarly at k=2, the target node 0 aggregates information from its local neighbours upto 2-hops i.e now it knows what lies in its neighbourhood upto 2-hops. Therefore, we can iterate this process where target node 0 incrementally obtain more and more information from further reaches of the graph. We do this process of information gathering for each of the nodes in the original graph (∀v ∈ V). Lets add some visuals to understand this iterative process much more intuitively:"
},
{
"code": null,
"e": 15415,
"s": 15008,
"text": "The following image depicts the computation graph of a target node 0 at layer K=0, at this point of time all the nodes in the graph are initialised to their original feature vectors. Our aim is to find the final representation of node 0 (i.e z0) at layer K=2 through an iterative local neighbourhood information gathering process. This iterative process is also sometime known as message passing approach ."
},
{
"code": null,
"e": 15467,
"s": 15415,
"text": "Therefore, we can represent this step formally as :"
},
{
"code": null,
"e": 15596,
"s": 15467,
"text": "Note: Since medium does not support subscript, I will write the hidden layer (h) representation as: (superscript) h (subscript)."
},
{
"code": null,
"e": 15629,
"s": 15596,
"text": "superscript denotes -> Kth layer"
},
{
"code": null,
"e": 15658,
"s": 15629,
"text": "subscript denotes -> Node id"
},
{
"code": null,
"e": 16314,
"s": 15658,
"text": "Since nodes gather the information incrementally from the deeper depths of the graph, we start our iteration process from search depth 1....K. At K=1, we aggregate neighbouring node representations for our target node 0 (1h0), i.e node 2 and 3 representations which were at previous layer (K-1h2 and K-1h3) into a single vector. Here 1h0 is an aggregated representation. At the same time step, nodes 2, 3, and 9 will also aggregate the feature vectors from their respective local neighbourhoods upto distance of 1-hop. Now at this point of time, each of the nodes in a computation graph knows what kind of information lies in their immediate surroundings."
},
{
"code": null,
"e": 16366,
"s": 16314,
"text": "Therefore, we can represent this step formally as :"
},
{
"code": null,
"e": 16937,
"s": 16366,
"text": "Once we achieve the aggregated representation i.e 1h0, the next step would be to concatenate or combine this aggregated representation with its previous layer representation (0h0). Then transformation is applied on this concatenated output by multiplying it with a weight matrix WK, you can think of this process similar to applying convolutional kernels (learnable weight matrices) on images in order to extract features from it. At the end, we apply a non-linear activation function on this transformed output making it capable to learn and perform more complex tasks."
},
{
"code": null,
"e": 17152,
"s": 16937,
"text": "Important Note: The GraphSage algorithm learns the weight matrix individually at each search depth K or you can also say that it learns how to aggregate information from a node’s neighbourhood at each search depth."
},
{
"code": null,
"e": 17200,
"s": 17152,
"text": "Hence, we can represent this step formally as :"
},
{
"code": null,
"e": 17403,
"s": 17200,
"text": "Subsequently, normalization is applied on node representation khv (or at this time step 1h0) which helps the algorithm to maintain the general distribution of node embeddings. This step is computed as :"
},
{
"code": null,
"e": 18124,
"s": 17403,
"text": "The information gathering from node’s local neighbourhood at K=1 is completed. At K=2, nodes explore the further reaches of the graph i.e going beyond their immediate neighbourhoods and looking into a hop distance of 2. Again we perform the node’s local neighbourhood aggregation, but this time the target node 0 will now have the information of its neighbours which are at 1-hop and 2-hop distances. Then again we repeat the process of updation and normalisation for the search depth K=2. Since we have set the value of K=2 for understanding the flow of the GraphSage algorithm therefore, we will stop here. After K=2, each node in the computation graph is represented by their respective final node embeddings i.e. zv."
},
{
"code": null,
"e": 18167,
"s": 18124,
"text": "This workflow is shown below in the image:"
},
{
"code": null,
"e": 18285,
"s": 18167,
"text": "Authors have recorded the results in the paper by using two different types of loss functions which are as following:"
},
{
"code": null,
"e": 18570,
"s": 18285,
"text": "Unsupervised Case: As described in the graph representation learning section, the aim is to optimize the mapping so that nodes which are nearby in the original network should also remain close to each other in the embedding space (vector space), while shoving unconnected nodes apart."
},
{
"code": null,
"e": 18674,
"s": 18570,
"text": "Supervised Case: Authors use regular cross-entropy loss for performing the task of node classification."
},
{
"code": null,
"e": 18733,
"s": 18674,
"text": "Below is the unsupervised loss function used in the paper:"
},
{
"code": null,
"e": 19031,
"s": 18733,
"text": "We will understand the working process of GraphSage in more detail with the help of a real world dataset from the Open Graph Benchmark (OGB) datasets. The OGB is a collection of realistic, large-scale, and diverse benchmark datasets for machine learning on graphs developed by Stanford University."
},
{
"code": null,
"e": 19247,
"s": 19031,
"text": "Lot of code ahead, if you are interested in getting your hands dirty with the code which I would really encourage you to do so, then I have already prepared a google colab notebook with which you can play around...."
},
{
"code": null,
"e": 19768,
"s": 19247,
"text": "We use obgn-products dataset which is an undirected and unweighted graph, representing an Amazon product co-purchasing network. Nodes represent products sold in Amazon, and edges between two products indicate that the products are purchased together. Node features represent bag-of-words features taken from the product descriptions. The goal is to predict the category of a product in a multi-class classification setup, where the 47 top-level categories are used for target labels making it a Node Classification Task."
},
{
"code": null,
"e": 20145,
"s": 19768,
"text": "# Installing Pytorch Geometric %%capture!pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-cluster -f https://pytorch-geometric.com/whl/torch-1.9.0+cu102.html!pip install -q torch-geometric!pip install ogb!pip install umap-learn"
},
{
"code": null,
"e": 20175,
"s": 20145,
"text": "Importing Necessary Libraries"
},
{
"code": null,
"e": 20749,
"s": 20175,
"text": "import torchimport torch.nn.functional as Ffrom tqdm import tqdmfrom torch_geometric.data import NeighborSamplerfrom torch_geometric.nn import SAGEConvimport os.path as ospimport pandas as pdimport numpy as npimport collectionsfrom pandas.core.common import flatten# importing obg datatsetfrom ogb.nodeproppred import PygNodePropPredDataset, Evaluatorfrom pandas.core.common import flattenimport seaborn as snsimport matplotlib.pyplot as pltsns.set(rc={'figure.figsize':(16.7,8.27)})sns.set_theme(style=\"ticks\")import collectionsfrom scipy.special import softmaximport umap"
},
{
"code": null,
"e": 20775,
"s": 20749,
"text": "Download and load dataset"
},
{
"code": null,
"e": 20900,
"s": 20775,
"text": " root = osp.join(osp.dirname(osp.realpath('./')), 'data', 'products')dataset = PygNodePropPredDataset('ogbn-products', root)"
},
{
"code": null,
"e": 20941,
"s": 20900,
"text": "Getting train, validation and test index"
},
{
"code": null,
"e": 21164,
"s": 20941,
"text": "# split_idx contains a dictionary of train, validation and test node indicessplit_idx = dataset.get_idx_split()# predefined ogb evaluator method used for validation of predictionsevaluator = Evaluator(name='ogbn-products')"
},
{
"code": null,
"e": 21222,
"s": 21164,
"text": "Let’s check the training, validation and test node split."
},
{
"code": null,
"e": 21561,
"s": 21222,
"text": "# lets check the node ids distribution of train, test and valprint('Number of training nodes:', split_idx['train'].size(0))print('Number of validation nodes:', split_idx['valid'].size(0))print('Number of test nodes:', split_idx['test'].size(0))Number of training nodes: 196615Number of validation nodes: 39323Number of test nodes: 2213091"
},
{
"code": null,
"e": 21581,
"s": 21561,
"text": "Loading the dataset"
},
{
"code": null,
"e": 21599,
"s": 21581,
"text": "data = dataset[0]"
},
{
"code": null,
"e": 21616,
"s": 21599,
"text": "Graph Statistics"
},
{
"code": null,
"e": 22337,
"s": 21616,
"text": "# lets check some graph statistics of ogb-product graphprint(\"Number of nodes in the graph:\", data.num_nodes)print(\"Number of edges in the graph:\", data.num_edges)print(\"Node feature matrix with shape:\", data.x.shape) # [num_nodes, num_node_features]print(\"Graph connectivity in COO format with shape:\", data.edge_index.shape) # [2, num_edges]print(\"Target to train against :\", data.y.shape) print(\"Node feature length\", dataset.num_features)Number of nodes in the graph: 2449029Number of edges in the graph: 123718280Node feature matrix with shape: torch.Size([2449029, 100])Graph connectivity in COO format with shape: torch.Size([2, 123718280])Target to train against : torch.Size([2449029, 1])Node feature length 100"
},
{
"code": null,
"e": 22374,
"s": 22337,
"text": "Checking the number of unique labels"
},
{
"code": null,
"e": 22433,
"s": 22374,
"text": "# there are 47 unique categories of productdata.y.unique()"
},
{
"code": null,
"e": 22518,
"s": 22433,
"text": "Load integer to real product category from label mapping provided inside the dataset"
},
{
"code": null,
"e": 22607,
"s": 22518,
"text": "df = pd.read_csv('/data/products/ogbn_products/mapping/labelidx2productcategory.csv.gz')"
},
{
"code": null,
"e": 22648,
"s": 22607,
"text": "Let’s see some of the product categories"
},
{
"code": null,
"e": 22656,
"s": 22648,
"text": "df[:10]"
},
{
"code": null,
"e": 22730,
"s": 22656,
"text": "Creating a dictionary of product category and corresponding integer label"
},
{
"code": null,
"e": 22977,
"s": 22730,
"text": "label_idx, prod_cat = df.iloc[: ,0].values, df.iloc[: ,1].valueslabel_mapping = dict(zip(label_idx, prod_cat))# counting the numbers of samples for each categoryy = data.y.tolist()y = list(flatten(y))count_y = collections.Counter(y)print(count_y)"
},
{
"code": null,
"e": 23119,
"s": 22977,
"text": "This module iteratively samples neighbours (at each layer) and constructs bipartite graphs that simulate the actual computation flow of GNNs."
},
{
"code": null,
"e": 23201,
"s": 23119,
"text": "sizes: denotes how much neighbours we want to sample for each node in each layer."
},
{
"code": null,
"e": 23598,
"s": 23201,
"text": "NeighborSampler holds the current :obj:batch_size, the IDs :obj:n_id of all nodes involved in the computation, and a list of bipartite graph objects via the tuple :obj:(edge_index, e_id, size), where :obj:edge_index represents the bipartite edges between source and target nodes, :obj:e_id denotes the IDs of original edges in the full graph, and :obj:size holds the shape of the bipartite graph."
},
{
"code": null,
"e": 23817,
"s": 23598,
"text": "The actual computation graphs are then returned in reverse-mode, meaning that we pass messages from a larger set of nodes to a smaller one, until we reach the nodes for which we originally wanted to compute embeddings."
},
{
"code": null,
"e": 24025,
"s": 23817,
"text": "train_idx = split_idx['train']train_loader = NeighborSampler(data.edge_index, node_idx=train_idx, sizes=[15, 10, 5], batch_size=1024, shuffle=True)"
},
{
"code": null,
"e": 27159,
"s": 24025,
"text": "class SAGE(torch.nn.Module): def __init__(self, in_channels, hidden_channels, out_channels, num_layers=3): super(SAGE, self).__init__() self.num_layers = num_layers self.convs = torch.nn.ModuleList() self.convs.append(SAGEConv(in_channels, hidden_channels)) for _ in range(num_layers - 2): self.convs.append(SAGEConv(hidden_channels, hidden_channels)) self.convs.append(SAGEConv(hidden_channels, out_channels)) def reset_parameters(self): for conv in self.convs: conv.reset_parameters() def forward(self, x, adjs): # `train_loader` computes the k-hop neighborhood of a batch of nodes, # and returns, for each layer, a bipartite graph object, holding the # bipartite edges `edge_index`, the index `e_id` of the original edges, # and the size/shape `size` of the bipartite graph. # Target nodes are also included in the source nodes so that one can # easily apply skip-connections or add self-loops. for i, (edge_index, _, size) in enumerate(adjs): xs = [] x_target = x[:size[1]] # Target nodes are always placed first. x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = F.relu(x) x = F.dropout(x, p=0.5, training=self.training) xs.append(x) if i == 0: x_all = torch.cat(xs, dim=0) layer_1_embeddings = x_all elif i == 1: x_all = torch.cat(xs, dim=0) layer_2_embeddings = x_all elif i == 2: x_all = torch.cat(xs, dim=0) layer_3_embeddings = x_all #return x.log_softmax(dim=-1) return layer_1_embeddings, layer_2_embeddings, layer_3_embeddings def inference(self, x_all): pbar = tqdm(total=x_all.size(0) * self.num_layers) pbar.set_description('Evaluating') # Compute representations of nodes layer by layer, using *all* # available edges. This leads to faster computation in contrast to # immediately computing the final representations of each batch. total_edges = 0 for i in range(self.num_layers): xs = [] for batch_size, n_id, adj in subgraph_loader: edge_index, _, size = adj.to(device) total_edges += edge_index.size(1) x = x_all[n_id].to(device) x_target = x[:size[1]] x = self.convs[i]((x, x_target), edge_index) if i != self.num_layers - 1: x = F.relu(x) xs.append(x) pbar.update(batch_size) if i == 0: x_all = torch.cat(xs, dim=0) layer_1_embeddings = x_all elif i == 1: x_all = torch.cat(xs, dim=0) layer_2_embeddings = x_all elif i == 2: x_all = torch.cat(xs, dim=0) layer_3_embeddings = x_all pbar.close() return layer_1_embeddings, layer_2_embeddings, layer_3_embeddings"
},
{
"code": null,
"e": 27177,
"s": 27159,
"text": "Instantiate model"
},
{
"code": null,
"e": 27345,
"s": 27177,
"text": "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')model = SAGE(dataset.num_features, 256, dataset.num_classes, num_layers=3)model = model.to(device)"
},
{
"code": null,
"e": 27386,
"s": 27345,
"text": "Load Node Feature Matrix and Node labels"
},
{
"code": null,
"e": 27439,
"s": 27386,
"text": "x = data.x.to(device)y = data.y.squeeze().to(device)"
},
{
"code": null,
"e": 27448,
"s": 27439,
"text": "Training"
},
{
"code": null,
"e": 28370,
"s": 27448,
"text": "def train(epoch): model.train() #pbar = tqdm(total=train_idx.size(0)) #pbar.set_description(f'Epoch {epoch:02d}') total_loss = total_correct = 0 for batch_size, n_id, adjs in train_loader: # `adjs` holds a list of `(edge_index, e_id, size)` tuples. adjs = [adj.to(device) for adj in adjs] optimizer.zero_grad() l1_emb, l2_emb, l3_emb = model(x[n_id], adjs) #print(\"Layer 1 embeddings\", l1_emb.shape) #print(\"Layer 2 embeddings\", l1_emb.shape) out = l3_emb.log_softmax(dim=-1) loss = F.nll_loss(out, y[n_id[:batch_size]]) loss.backward() optimizer.step() total_loss += float(loss) total_correct += int(out.argmax(dim=-1).eq(y[n_id[:batch_size]]).sum()) #pbar.update(batch_size) #pbar.close() loss = total_loss / len(train_loader) approx_acc = total_correct / train_idx.size(0) return loss, approx_acc"
},
{
"code": null,
"e": 28379,
"s": 28370,
"text": "Epochs!!"
},
{
"code": null,
"e": 28567,
"s": 28379,
"text": "optimizer = torch.optim.Adam(model.parameters(), lr=0.003)for epoch in range(1, 21): loss, acc = train(epoch) print(f'Epoch {epoch:02d}, Loss: {loss:.4f}, Approx. Train: {acc:.4f}')"
},
{
"code": null,
"e": 28835,
"s": 28567,
"text": "We need to save the model for the inference part because google colab cannot create two graph loaders at the same time because of the limitation of the RAM size. Therefore, we first train with train_loader and then make inferences on test data using this saved model."
},
{
"code": null,
"e": 28917,
"s": 28835,
"text": "Here you can either save the model on google MyDrive or locally on your computer."
},
{
"code": null,
"e": 29176,
"s": 28917,
"text": "#torch.save(model, '/content/drive/MyDrive/model_weights/graph_embeddings/model.pt')# saving model in mydrivefrom google.colab import drivedrive.mount('/content/drive')fp = '/content/drive/MyDrive/model.pt'torch.save(model, './model.pt')torch.save(model, fp)"
},
{
"code": null,
"e": 29469,
"s": 29176,
"text": "This part includes making the use of trained GraphSage model in order to compute node embeddings and performing node category prediction on test data. Afterwards, we compare the U-Map visualisations of node embeddings at 3 different layers of GraphSage and draw some interesting observations."
},
{
"code": null,
"e": 29703,
"s": 29469,
"text": "It would be much more useful to a reader if he/she runs the inference part of GraphSage in google colab notebook which I have prepared in order to get better intuition on how the visualisations at each layer of GraphSage is computed."
},
{
"code": null,
"e": 30099,
"s": 29703,
"text": "Node embeddings visualization at layer-1 shows that the model is not able to separate the product categories well (as the embeddings of different product categories are very close together ), therefore we cannot predict/estimate with high probability which two products can be bought together in the future or if someone buys one product then which other product he/she might also be interested."
},
{
"code": null,
"e": 30390,
"s": 30099,
"text": "At layer-2 we can see some separate clusters of product categories forming and we can draw some valuable insights from their for e.g. movies&TV vs CDs&Vinyl, Beauty vs health & personal care, video games vs toys & games. However, books and beauty clusters are very far away from each other."
},
{
"code": null,
"e": 30552,
"s": 30390,
"text": "At layer-3 node representations are little more finer than the layer-2 as we can see some more distant clusters for eg. cell phones & accessories vs electronics."
},
{
"code": null,
"e": 30660,
"s": 30552,
"text": "I would like to thanks the whole ML team of ArangoDB for providing me the valuable feedback about the blog."
},
{
"code": null,
"e": 30694,
"s": 30660,
"text": "Want to connect with me: Linkedin"
},
{
"code": null,
"e": 31340,
"s": 30694,
"text": "https://www.arangodb.com/2021/08/a-comprehensive-case-study-of-graphsage-using-pytorchgeometric/?utm_content=176620548&utm_medium=social&utm_source=linkedin&hss_channel=lcp-5289249 (The original blogpost)Inductive Representation Learning on Large Graphshttp://web.stanford.edu/class/cs224w/slides/17-scalable.pdfA Voyage through Graph Machine Learning Universe: Motivation, Applications, Datasets, Graph ML Libraries, Graph Databaseshttps://medium.com/pinterest-engineering/pinsage-a-new-graph-convolutional-neural-network-for-web-scale-recommender-systems-88795a107f48https://eng.uber.com/uber-eats-graph-learning/More stuff related to Graph ML"
},
{
"code": null,
"e": 31545,
"s": 31340,
"text": "https://www.arangodb.com/2021/08/a-comprehensive-case-study-of-graphsage-using-pytorchgeometric/?utm_content=176620548&utm_medium=social&utm_source=linkedin&hss_channel=lcp-5289249 (The original blogpost)"
},
{
"code": null,
"e": 31595,
"s": 31545,
"text": "Inductive Representation Learning on Large Graphs"
},
{
"code": null,
"e": 31655,
"s": 31595,
"text": "http://web.stanford.edu/class/cs224w/slides/17-scalable.pdf"
},
{
"code": null,
"e": 31777,
"s": 31655,
"text": "A Voyage through Graph Machine Learning Universe: Motivation, Applications, Datasets, Graph ML Libraries, Graph Databases"
},
{
"code": null,
"e": 31914,
"s": 31777,
"text": "https://medium.com/pinterest-engineering/pinsage-a-new-graph-convolutional-neural-network-for-web-scale-recommender-systems-88795a107f48"
},
{
"code": null,
"e": 31961,
"s": 31914,
"text": "https://eng.uber.com/uber-eats-graph-learning/"
}
]
|
HTML - <ilayer> Tag | The HTML <ilayer> tag is used to create a layer that occupies space in the containing text flow. Subsequent content is placed after the space occupied by the <ilayer>.
This is in contrast to the <layer> tag, which creates a layer above the containing text flow, allowing subsequent content to be placed under the layer just created.
<!DOCTYPE html>
<html>
<head>
<title>HTML ilayer Tag</title>
</head>
<body>
This <ilayer top = "4">word</ilayer> is shifted down, while this
<ilayer left = "10">one</ilayer> is shifted over. With a negative value,
words can be moved <ilayer top = "-4">up</ilayer> and to the
<ilayer left = "-10">left</ilayer>.
</body>
</html>
This will produce the following result −
The result will only work on Netscape 4.
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <ilayer> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2542,
"s": 2374,
"text": "The HTML <ilayer> tag is used to create a layer that occupies space in the containing text flow. Subsequent content is placed after the space occupied by the <ilayer>."
},
{
"code": null,
"e": 2707,
"s": 2542,
"text": "This is in contrast to the <layer> tag, which creates a layer above the containing text flow, allowing subsequent content to be placed under the layer just created."
},
{
"code": null,
"e": 3091,
"s": 2707,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML ilayer Tag</title>\n </head>\n\n <body>\n This <ilayer top = \"4\">word</ilayer> is shifted down, while this \n <ilayer left = \"10\">one</ilayer> is shifted over. With a negative value, \n words can be moved <ilayer top = \"-4\">up</ilayer> and to the \n <ilayer left = \"-10\">left</ilayer>.\n </body>\n\n</html>"
},
{
"code": null,
"e": 3132,
"s": 3091,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3173,
"s": 3132,
"text": "The result will only work on Netscape 4."
},
{
"code": null,
"e": 3257,
"s": 3173,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 3332,
"s": 3257,
"text": "The HTML <ilayer> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3412,
"s": 3332,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 3445,
"s": 3412,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3459,
"s": 3445,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3494,
"s": 3459,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3508,
"s": 3494,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3543,
"s": 3508,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3560,
"s": 3543,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3595,
"s": 3560,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3626,
"s": 3595,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3659,
"s": 3626,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3690,
"s": 3659,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3725,
"s": 3690,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3756,
"s": 3725,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3763,
"s": 3756,
"text": " Print"
},
{
"code": null,
"e": 3774,
"s": 3763,
"text": " Add Notes"
}
]
|
Array.prototype.find() method in JavaScript. | The Array.prototype.find() method returns the first element value that satisfy a given
condition in an array.
Following is the code for the Array.prototype.find() method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.find {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Array Find() example</h1>
<div class="find"></div>
<button class="fillArr">CLICK HERE</button>
<h3>Click on the above button to find lion among the animals</h3>
<script>
function findLion(animal) {
return animal === "lion";
}
let fillEle = document.querySelector(".find");
let arr = ["cow", "lion", "bull", "tiger"];
fillEle.innerHTML = arr;
document.querySelector(".fillArr").addEventListener("click", () => {
fillEle.innerHTML = arr.find(findLion);
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “CLICK HERE” button − | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "The Array.prototype.find() method returns the first element value that satisfy a given\ncondition in an array."
},
{
"code": null,
"e": 1234,
"s": 1172,
"text": "Following is the code for the Array.prototype.find() method −"
},
{
"code": null,
"e": 1245,
"s": 1234,
"text": " Live Demo"
},
{
"code": null,
"e": 2114,
"s": 1245,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .find {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Array Find() example</h1>\n<div class=\"find\"></div>\n<button class=\"fillArr\">CLICK HERE</button>\n<h3>Click on the above button to find lion among the animals</h3>\n<script>\n function findLion(animal) {\n return animal === \"lion\";\n }\n let fillEle = document.querySelector(\".find\");\n let arr = [\"cow\", \"lion\", \"bull\", \"tiger\"];\n fillEle.innerHTML = arr;\n document.querySelector(\".fillArr\").addEventListener(\"click\", () => {\n fillEle.innerHTML = arr.find(findLion);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2165,
"s": 2114,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2203,
"s": 2165,
"text": "On clicking the “CLICK HERE” button −"
}
]
|
How can an exception be thrown manually by a programmer in java? | An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
import java.util.Scanner;
public class ExceptionExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int c = a/b;
System.out.println("The result is: "+c);
}
}
Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)
You can throw a user defined exception or, a predefined exception explicitly using the throw keyword.
There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class.
To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.
Following Java program throws a NullPointerException
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Hello");
NullPointerException nullPointer = new NullPointerException();
throw nullPointer;
}
}
Hello
Exception in thread "main" java.lang.NullPointerException
at MyPackage.ExceptionExample.main(ExceptionExample.java:6)
Whenever you throw an exception explicitly you need to make sure that the line with throw keyword is the last line of the program. This is because any code written after it is unreachable code and if you still have code snippets below this line a compile time error will be generated.
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Hello");
NullPointerException nullPointer = new NullPointerException();
throw nullPointer;
System.out.println("How are you");
}
}
D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
System.out.println("How are you");
^
1 error
Usually the throw keyword is mostly used to throw user defined exception. Whenever we need to define your own exception you need to define a class extending the Throwable class, override the required methods.
Instantiate this class, throw it using the throw keyword wherever you want the exception.
In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException.
public class AgeDoesnotMatchException extends Exception{
AgeDoesnotMatchException(String msg){
super(msg);
}
}
Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables.
Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values.
In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24.
public class Student extends RuntimeException {
private String name;
private int age;
public Student(String name, int age){
try {
if (age<17||age>24) {
String msg = "Age is not between 17 and 24";
AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);
throw ex;
}
}catch(AgeDoesnotMatchException e) {
e.printStackTrace();
}
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name of the Student: ");
String name = sc.next();
System.out.println("Enter the age of the Student should be 17 to 24 (including 17 and 24): ");
int age = sc.nextInt();
Student obj = new Student(name, age);
obj.display();
}
}
On executing this program, you need to pass name and age values from keyboard. If the given age value is not between 17 and 24 then exception occurs as shown below −
Enter the name of the Student:
Krishna
Enter the age of the Student should be 17 to 24 (including 17 and 24):
14
AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student: Krishna'
Age of the Student: 14
at Student.<init>(Student.java:18)
at Student.main(Student.java:39) | [
{
"code": null,
"e": 1290,
"s": 1062,
"text": "An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed."
},
{
"code": null,
"e": 1665,
"s": 1290,
"text": "import java.util.Scanner;\npublic class ExceptionExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number: \");\n int a = sc.nextInt();\n System.out.println(\"Enter second number: \");\n int b = sc.nextInt();\n int c = a/b;\n System.out.println(\"The result is: \"+c);\n }\n}"
},
{
"code": null,
"e": 1831,
"s": 1665,
"text": "Enter first number:\n100\nEnter second number:\n0\nException in thread \"main\" java.lang.ArithmeticException: / by zero\nat ExceptionExample.main(ExceptionExample.java:10)"
},
{
"code": null,
"e": 1933,
"s": 1831,
"text": "You can throw a user defined exception or, a predefined exception explicitly using the throw keyword."
},
{
"code": null,
"e": 2076,
"s": 1933,
"text": "There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class."
},
{
"code": null,
"e": 2195,
"s": 2076,
"text": "To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword."
},
{
"code": null,
"e": 2248,
"s": 2195,
"text": "Following Java program throws a NullPointerException"
},
{
"code": null,
"e": 2460,
"s": 2248,
"text": "public class ExceptionExample {\n public static void main(String[] args) {\n System.out.println(\"Hello\");\n NullPointerException nullPointer = new NullPointerException();\n throw nullPointer;\n }\n}"
},
{
"code": null,
"e": 2587,
"s": 2460,
"text": "Hello\nException in thread \"main\" java.lang.NullPointerException\n at MyPackage.ExceptionExample.main(ExceptionExample.java:6)"
},
{
"code": null,
"e": 2872,
"s": 2587,
"text": "Whenever you throw an exception explicitly you need to make sure that the line with throw keyword is the last line of the program. This is because any code written after it is unreachable code and if you still have code snippets below this line a compile time error will be generated."
},
{
"code": null,
"e": 3125,
"s": 2872,
"text": "public class ExceptionExample {\n public static void main(String[] args) {\n System.out.println(\"Hello\");\n NullPointerException nullPointer = new NullPointerException();\n throw nullPointer;\n System.out.println(\"How are you\");\n }\n}"
},
{
"code": null,
"e": 3262,
"s": 3125,
"text": "D:\\>javac ExceptionExample.java\nExceptionExample.java:6: error: unreachable statement\n System.out.println(\"How are you\");\n ^\n1 error"
},
{
"code": null,
"e": 3471,
"s": 3262,
"text": "Usually the throw keyword is mostly used to throw user defined exception. Whenever we need to define your own exception you need to define a class extending the Throwable class, override the required methods."
},
{
"code": null,
"e": 3561,
"s": 3471,
"text": "Instantiate this class, throw it using the throw keyword wherever you want the exception."
},
{
"code": null,
"e": 3669,
"s": 3561,
"text": "In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException."
},
{
"code": null,
"e": 3792,
"s": 3669,
"text": "public class AgeDoesnotMatchException extends Exception{\n AgeDoesnotMatchException(String msg){\n super(msg);\n }\n}"
},
{
"code": null,
"e": 3930,
"s": 3792,
"text": "Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables."
},
{
"code": null,
"e": 4061,
"s": 3930,
"text": "Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values."
},
{
"code": null,
"e": 4248,
"s": 4061,
"text": "In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24."
},
{
"code": null,
"e": 5257,
"s": 4248,
"text": "public class Student extends RuntimeException {\n private String name;\n private int age;\n public Student(String name, int age){\n try {\n if (age<17||age>24) {\n String msg = \"Age is not between 17 and 24\";\n AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);\n throw ex;\n }\n }catch(AgeDoesnotMatchException e) {\n e.printStackTrace();\n }\n this.name = name;\n this.age = age;\n }\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n Scanner sc= new Scanner(System.in);\n System.out.println(\"Enter the name of the Student: \");\n String name = sc.next();\n System.out.println(\"Enter the age of the Student should be 17 to 24 (including 17 and 24): \");\n int age = sc.nextInt();\n Student obj = new Student(name, age);\n obj.display();\n }\n}"
},
{
"code": null,
"e": 5423,
"s": 5257,
"text": "On executing this program, you need to pass name and age values from keyboard. If the given age value is not between 17 and 24 then exception occurs as shown below −"
},
{
"code": null,
"e": 5718,
"s": 5423,
"text": "Enter the name of the Student:\nKrishna\nEnter the age of the Student should be 17 to 24 (including 17 and 24):\n14\nAgeDoesnotMatchException: Age is not between 17 and 24\nName of the Student: Krishna'\nAge of the Student: 14\n at Student.<init>(Student.java:18)\n at Student.main(Student.java:39)"
}
]
|
Python | Convert number to list of integers - GeeksforGeeks | 26 Jan, 2019
The interconversion of data types is a problem that is quite common in programming. Sometimes we need to convert a single number to list of integers and we don’t wish to spend several lines of codes doing it. Hence having ways to perform this task using shorthands comes handy. Let’s discuss ways in which this can be performed.
Method #1 : Using list comprehensionList comprehension can be used as a shorthand to the longer format of naive method. In this method, we convert the number to string and then extract its each character and re convert it to integer.
# Python3 code to demonstrate # conversion of number to list of integers# using list comprehension # initializing number num = 2019 # printing number print ("The original number is " + str(num)) # using list comprehension# to convert number to list of integersres = [int(x) for x in str(num)] # printing result print ("The list from number is " + str(res))
Output:
The original number is 2019
The list from number is [2, 0, 1, 9]
Method #2 : Using map()map function can be used to perform the following task converting each of the string converted number to the desired integer value to be reconverted to the list format.
# Python3 code to demonstrate # conversion of number to list of integers# using map() # initializing number num = 2019 # printing number print ("The original number is " + str(num)) # using map()# to convert number to list of integersres = list(map(int, str(num))) # printing result print ("The list from number is " + str(res))
Output:
The original number is 2019
The list from number is [2, 0, 1, 9]
Python list-programs
Python
Python Programs
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 ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python? | [
{
"code": null,
"e": 24490,
"s": 24462,
"text": "\n26 Jan, 2019"
},
{
"code": null,
"e": 24819,
"s": 24490,
"text": "The interconversion of data types is a problem that is quite common in programming. Sometimes we need to convert a single number to list of integers and we don’t wish to spend several lines of codes doing it. Hence having ways to perform this task using shorthands comes handy. Let’s discuss ways in which this can be performed."
},
{
"code": null,
"e": 25053,
"s": 24819,
"text": "Method #1 : Using list comprehensionList comprehension can be used as a shorthand to the longer format of naive method. In this method, we convert the number to string and then extract its each character and re convert it to integer."
},
{
"code": "# Python3 code to demonstrate # conversion of number to list of integers# using list comprehension # initializing number num = 2019 # printing number print (\"The original number is \" + str(num)) # using list comprehension# to convert number to list of integersres = [int(x) for x in str(num)] # printing result print (\"The list from number is \" + str(res))",
"e": 25414,
"s": 25053,
"text": null
},
{
"code": null,
"e": 25422,
"s": 25414,
"text": "Output:"
},
{
"code": null,
"e": 25487,
"s": 25422,
"text": "The original number is 2019\nThe list from number is [2, 0, 1, 9]"
},
{
"code": null,
"e": 25680,
"s": 25487,
"text": " Method #2 : Using map()map function can be used to perform the following task converting each of the string converted number to the desired integer value to be reconverted to the list format."
},
{
"code": "# Python3 code to demonstrate # conversion of number to list of integers# using map() # initializing number num = 2019 # printing number print (\"The original number is \" + str(num)) # using map()# to convert number to list of integersres = list(map(int, str(num))) # printing result print (\"The list from number is \" + str(res))",
"e": 26013,
"s": 25680,
"text": null
},
{
"code": null,
"e": 26021,
"s": 26013,
"text": "Output:"
},
{
"code": null,
"e": 26086,
"s": 26021,
"text": "The original number is 2019\nThe list from number is [2, 0, 1, 9]"
},
{
"code": null,
"e": 26107,
"s": 26086,
"text": "Python list-programs"
},
{
"code": null,
"e": 26114,
"s": 26107,
"text": "Python"
},
{
"code": null,
"e": 26130,
"s": 26114,
"text": "Python Programs"
},
{
"code": null,
"e": 26228,
"s": 26130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26237,
"s": 26228,
"text": "Comments"
},
{
"code": null,
"e": 26250,
"s": 26237,
"text": "Old Comments"
},
{
"code": null,
"e": 26268,
"s": 26250,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26303,
"s": 26268,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26325,
"s": 26303,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26357,
"s": 26325,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26399,
"s": 26357,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26421,
"s": 26399,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26460,
"s": 26421,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26498,
"s": 26460,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 26555,
"s": 26498,
"text": "Python program to check whether a number is Prime or not"
}
]
|
How to Train StyleGAN2-ADA with Custom Dataset | by Fathy Rashad | Towards Data Science | Have you always wondered how to train your own generative model? The first time I discovered GAN applications like this face generating website, I always wondered how to train GAN on other things. Luckily, I recently had the opportunity to train a bike generating model as part of my research. In this article, I will document my experience on how to train StyleGAN2-ADA on your own images.
StyleGAN is one of the most popular generative models by NVIDIA. Multiple version of StlyeGAN has been released and we will be using the latest version which is StyleGAN2-ADA. To avoid redundancy, I won’t explain StyleGAN as there are many articles that have explained it really well.
jonathan-hui.medium.com
towardsdatascience.com
Training StyleGAN is computationally expensive. Hence, if you don’t have a decent GPU, you may want to train on the cloud. If you decide to train on Google Colab (it’s free), someone has made a nice notebook for this.
In the tutorial, I will be using the bike dataset BIKED. Feel free to use your own dataset. Just make sure all the training images are square and put them inside the same folder.
In this article, I will be using the Tensorflow implementation of StyleGAN2-ADA. Make sure you use Tensorflow version 1, as the code is not compatible with Tensorflow 2. Alternatively, if you prefer PyTorch, you can use the PyTorch version that has been recently released. The PyTorch code seems to be slightly faster in performance. If you use PyTorch, you can still follow this tutorial with a slight difference in the dataset preparation.
64-bit Python 3.6 or 3.7. Anaconda3 with numpy 1.14.3 or newer is recommended.
TensorFlow 1.14 is recommended, but TensorFlow 1.15 is also supported on Linux. TensorFlow 2.x is not supported.
On Windows you need to use TensorFlow 1.14, as the standard 1.15 installation does not include necessary C++ headers.
1–8 high-end NVIDIA GPUs with at least 12 GB of GPU memory, NVIDIA drivers, CUDA 10.0 toolkit and cuDNN 7.5
Clone the StyleGAN2-ADA repository and go inside the directory
Clone the StyleGAN2-ADA repository and go inside the directory
git clone https://github.com/NVlabs/stylegan2-ada.gitcd styelgan2-ada
2. Download or create your own dataset. I will be using BIKED dataset that I already preprocessed. You can download my preprocessed version from dropbox.
# Dowload datasetwget "https://www.dropbox.com/s/0ybsudabqscstf7/biked_dataset.tar.gz" -q -O biked_dataset.tar.gz# extract datasettar -zxvf biked_dataset.tar.gz# Delete the tar.gz filerm biked_dataset.tar.gz
After extracting the content, you will have a folder named BIKED that contains 4510 square images of bike designs.
Note: If you are using your own dataset, create a folder and put all training images inside the folder. Make sure all the images are square and the same size.
3. Preparing Dataset
As the code needs the dataset to be in .tfrecords format. We first need to convert our dataset to this format. StyleGAN2-ADA has made a script that makes this conversion easy.
# first argument is output and second arg is path to datasetpython dataset_tool.py create_from_images ./datasets/biked biked
This will create a multi-resolution .tfrecord file in /datasets/biked/ folder.
4. Training StyleGAN2-ADA
# snap is how often you want to save the model and sample results# res is what image resolution you want to train on# augpipe is augmentation pipes, such as 'blit', 'geom', 'color', 'filter', 'noise', 'cutout' or combination of thesepython train.py --outdir ./results --snap=10 --data=./datasets/biked --augpipe=bgcfnc --res=512
There are many other arguments that you can modify, feel free to check the train.py code to learn more about the arguments.
Once you run the command, it will start training and periodically save the result and the model file (.pkl) based on the snap arguments that you provided (In this case, every 10kimg). Once you think that the result is good enough or the FID starts to plateau, you can stop training and use the last saved .pkl file.
Once you have the model file you can generate images using this command.
python generate.py --outdir=out --trunc=0.5 --seeds=600-605 --network={path_to_pkl_model_file}
You can provide a range or a comma-separated value for the seeds. The trunc is the value for the truncation trick. The higher the truncation value the more diverse or extreme the output, but might lower the image quality. The lower the value, the higher the image quality but might be less diverse. The maximum value is 1.
However, if you want to generate interpolation videos or a grid of images. You can refer to my previous article.
towardsdatascience.com
5. Transfer Learning or Resume Training
If your training stopped or crashed for some reason. You can still resume training from the last saved progress. You just need to add — resume argument with the path to the model (.pkl) file.
Additionally, you can also use this argument for transfer learning. Instead of training from scratch, it is usually best to start with one of the pre-trained models, even if the dataset itself not similar. Just replace the .pkl path with one of the pre-trained models provided by StyleGAN-ADA.
In this example, I will resume training from my pre-trained model on the biked dataset.
python train.py --outdir ./results --snap=10 --data=./datasets/biked --augpipe=bgcfnc --res=512 --resume=full-bike-network-snapshot-004096.pkl
Here is an animation of the training result of 256x256 resolution on the Tesla P100 GPU after training for a day.
If you enjoyed my writings, check out my other articles!
towardsdatascience.com
towardsdatascience.com
[1] Regenwetter, L., Curry, B., & Ahmed, F. (2021). BIKED: A Dataset and Machine Learning Benchmarks for Data-Driven Bicycle Design.
[2] Nobari, A. H., Rashad, M. F., & Ahmed, F. (2021). CreativeGAN: Editing Generative Adversarial Networks for Creative Design Synthesis
[3] Karras, T., Aittala, M., Hellsten, J., Laine, S., Lehtinen, J., & Aila, T. (2020). Training generative adversarial networks with limited data | [
{
"code": null,
"e": 562,
"s": 171,
"text": "Have you always wondered how to train your own generative model? The first time I discovered GAN applications like this face generating website, I always wondered how to train GAN on other things. Luckily, I recently had the opportunity to train a bike generating model as part of my research. In this article, I will document my experience on how to train StyleGAN2-ADA on your own images."
},
{
"code": null,
"e": 847,
"s": 562,
"text": "StyleGAN is one of the most popular generative models by NVIDIA. Multiple version of StlyeGAN has been released and we will be using the latest version which is StyleGAN2-ADA. To avoid redundancy, I won’t explain StyleGAN as there are many articles that have explained it really well."
},
{
"code": null,
"e": 871,
"s": 847,
"text": "jonathan-hui.medium.com"
},
{
"code": null,
"e": 894,
"s": 871,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1112,
"s": 894,
"text": "Training StyleGAN is computationally expensive. Hence, if you don’t have a decent GPU, you may want to train on the cloud. If you decide to train on Google Colab (it’s free), someone has made a nice notebook for this."
},
{
"code": null,
"e": 1291,
"s": 1112,
"text": "In the tutorial, I will be using the bike dataset BIKED. Feel free to use your own dataset. Just make sure all the training images are square and put them inside the same folder."
},
{
"code": null,
"e": 1733,
"s": 1291,
"text": "In this article, I will be using the Tensorflow implementation of StyleGAN2-ADA. Make sure you use Tensorflow version 1, as the code is not compatible with Tensorflow 2. Alternatively, if you prefer PyTorch, you can use the PyTorch version that has been recently released. The PyTorch code seems to be slightly faster in performance. If you use PyTorch, you can still follow this tutorial with a slight difference in the dataset preparation."
},
{
"code": null,
"e": 1812,
"s": 1733,
"text": "64-bit Python 3.6 or 3.7. Anaconda3 with numpy 1.14.3 or newer is recommended."
},
{
"code": null,
"e": 1925,
"s": 1812,
"text": "TensorFlow 1.14 is recommended, but TensorFlow 1.15 is also supported on Linux. TensorFlow 2.x is not supported."
},
{
"code": null,
"e": 2043,
"s": 1925,
"text": "On Windows you need to use TensorFlow 1.14, as the standard 1.15 installation does not include necessary C++ headers."
},
{
"code": null,
"e": 2151,
"s": 2043,
"text": "1–8 high-end NVIDIA GPUs with at least 12 GB of GPU memory, NVIDIA drivers, CUDA 10.0 toolkit and cuDNN 7.5"
},
{
"code": null,
"e": 2214,
"s": 2151,
"text": "Clone the StyleGAN2-ADA repository and go inside the directory"
},
{
"code": null,
"e": 2277,
"s": 2214,
"text": "Clone the StyleGAN2-ADA repository and go inside the directory"
},
{
"code": null,
"e": 2347,
"s": 2277,
"text": "git clone https://github.com/NVlabs/stylegan2-ada.gitcd styelgan2-ada"
},
{
"code": null,
"e": 2501,
"s": 2347,
"text": "2. Download or create your own dataset. I will be using BIKED dataset that I already preprocessed. You can download my preprocessed version from dropbox."
},
{
"code": null,
"e": 2709,
"s": 2501,
"text": "# Dowload datasetwget \"https://www.dropbox.com/s/0ybsudabqscstf7/biked_dataset.tar.gz\" -q -O biked_dataset.tar.gz# extract datasettar -zxvf biked_dataset.tar.gz# Delete the tar.gz filerm biked_dataset.tar.gz"
},
{
"code": null,
"e": 2824,
"s": 2709,
"text": "After extracting the content, you will have a folder named BIKED that contains 4510 square images of bike designs."
},
{
"code": null,
"e": 2983,
"s": 2824,
"text": "Note: If you are using your own dataset, create a folder and put all training images inside the folder. Make sure all the images are square and the same size."
},
{
"code": null,
"e": 3004,
"s": 2983,
"text": "3. Preparing Dataset"
},
{
"code": null,
"e": 3180,
"s": 3004,
"text": "As the code needs the dataset to be in .tfrecords format. We first need to convert our dataset to this format. StyleGAN2-ADA has made a script that makes this conversion easy."
},
{
"code": null,
"e": 3305,
"s": 3180,
"text": "# first argument is output and second arg is path to datasetpython dataset_tool.py create_from_images ./datasets/biked biked"
},
{
"code": null,
"e": 3384,
"s": 3305,
"text": "This will create a multi-resolution .tfrecord file in /datasets/biked/ folder."
},
{
"code": null,
"e": 3410,
"s": 3384,
"text": "4. Training StyleGAN2-ADA"
},
{
"code": null,
"e": 3739,
"s": 3410,
"text": "# snap is how often you want to save the model and sample results# res is what image resolution you want to train on# augpipe is augmentation pipes, such as 'blit', 'geom', 'color', 'filter', 'noise', 'cutout' or combination of thesepython train.py --outdir ./results --snap=10 --data=./datasets/biked --augpipe=bgcfnc --res=512"
},
{
"code": null,
"e": 3863,
"s": 3739,
"text": "There are many other arguments that you can modify, feel free to check the train.py code to learn more about the arguments."
},
{
"code": null,
"e": 4179,
"s": 3863,
"text": "Once you run the command, it will start training and periodically save the result and the model file (.pkl) based on the snap arguments that you provided (In this case, every 10kimg). Once you think that the result is good enough or the FID starts to plateau, you can stop training and use the last saved .pkl file."
},
{
"code": null,
"e": 4252,
"s": 4179,
"text": "Once you have the model file you can generate images using this command."
},
{
"code": null,
"e": 4347,
"s": 4252,
"text": "python generate.py --outdir=out --trunc=0.5 --seeds=600-605 --network={path_to_pkl_model_file}"
},
{
"code": null,
"e": 4670,
"s": 4347,
"text": "You can provide a range or a comma-separated value for the seeds. The trunc is the value for the truncation trick. The higher the truncation value the more diverse or extreme the output, but might lower the image quality. The lower the value, the higher the image quality but might be less diverse. The maximum value is 1."
},
{
"code": null,
"e": 4783,
"s": 4670,
"text": "However, if you want to generate interpolation videos or a grid of images. You can refer to my previous article."
},
{
"code": null,
"e": 4806,
"s": 4783,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4846,
"s": 4806,
"text": "5. Transfer Learning or Resume Training"
},
{
"code": null,
"e": 5038,
"s": 4846,
"text": "If your training stopped or crashed for some reason. You can still resume training from the last saved progress. You just need to add — resume argument with the path to the model (.pkl) file."
},
{
"code": null,
"e": 5332,
"s": 5038,
"text": "Additionally, you can also use this argument for transfer learning. Instead of training from scratch, it is usually best to start with one of the pre-trained models, even if the dataset itself not similar. Just replace the .pkl path with one of the pre-trained models provided by StyleGAN-ADA."
},
{
"code": null,
"e": 5420,
"s": 5332,
"text": "In this example, I will resume training from my pre-trained model on the biked dataset."
},
{
"code": null,
"e": 5563,
"s": 5420,
"text": "python train.py --outdir ./results --snap=10 --data=./datasets/biked --augpipe=bgcfnc --res=512 --resume=full-bike-network-snapshot-004096.pkl"
},
{
"code": null,
"e": 5677,
"s": 5563,
"text": "Here is an animation of the training result of 256x256 resolution on the Tesla P100 GPU after training for a day."
},
{
"code": null,
"e": 5734,
"s": 5677,
"text": "If you enjoyed my writings, check out my other articles!"
},
{
"code": null,
"e": 5757,
"s": 5734,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5780,
"s": 5757,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5913,
"s": 5780,
"text": "[1] Regenwetter, L., Curry, B., & Ahmed, F. (2021). BIKED: A Dataset and Machine Learning Benchmarks for Data-Driven Bicycle Design."
},
{
"code": null,
"e": 6050,
"s": 5913,
"text": "[2] Nobari, A. H., Rashad, M. F., & Ahmed, F. (2021). CreativeGAN: Editing Generative Adversarial Networks for Creative Design Synthesis"
}
]
|
Locality of Reference and Cache Operation in Cache Memory - GeeksforGeeks | 21 Aug, 2019
Locality of reference refers to a phenomenon in which a computer program tends to access same set of memory locations for a particular time period. In other words, Locality of Reference refers to the tendency of the computer program to access instructions whose addresses are near one another. The property of locality of reference is mainly shown by loops and subroutine calls in a program.
In case of loops in program control processing unit repeatedly refers to the set of instructions that constitute the loop.In case of subroutine calls, everytime the set of instructions are fetched from memory.References to data items also get localized that means same data item is referenced again and again.
In case of loops in program control processing unit repeatedly refers to the set of instructions that constitute the loop.
In case of subroutine calls, everytime the set of instructions are fetched from memory.
References to data items also get localized that means same data item is referenced again and again.
In the above figure, you can see that the CPU wants to read or fetch the data or instruction. First, it will access the cache memory as it is near to it and provides very fast access. If the required data or instruction is found, it will be fetched. This situation is known as a cache hit. But if the required data or instruction is not found in the cache memory then this situation is known as a cache miss. Now the main memory will be searched for the required data or instruction that was being searched and if found will go through one of the two ways:
First way is that the CPU should fetch the required data or instruction and use it and that’s it but what, when the same data or instruction is required again.CPU again has to access the same main memory location for it and we already know that main memory is the slowest to access.The second way is to store the data or instruction in the cache memory so that if it is needed soon again in the near future it could be fetched in a much faster way.
First way is that the CPU should fetch the required data or instruction and use it and that’s it but what, when the same data or instruction is required again.CPU again has to access the same main memory location for it and we already know that main memory is the slowest to access.
The second way is to store the data or instruction in the cache memory so that if it is needed soon again in the near future it could be fetched in a much faster way.
Cache Operation:It is based on the principle of locality of reference. There are two ways with which data or instruction is fetched from main memory and get stored in cache memory. These two ways are the following:
Temporal Locality –Temporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory so that we can avoid again searching in main memory for the same data.When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future.Spatial Locality –Spatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future. This is slightly different from the temporal locality. Here we are talking about nearly located memory locations while in temporal locality we were talking about the actual memory location that was being fetched.
Temporal Locality –Temporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory so that we can avoid again searching in main memory for the same data.When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future.
When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future.
Spatial Locality –Spatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future. This is slightly different from the temporal locality. Here we are talking about nearly located memory locations while in temporal locality we were talking about the actual memory location that was being fetched.
Cache Performance:The performance of the cache is measured in terms of hit ratio. When CPU refers to memory and find the data or instruction within the Cache Memory, it is known as cache hit. If the desired data or instruction is not found in the cache memory and CPU refers to the main memory to find that data or instruction, it is known as a cache miss.
Hit + Miss = Total CPU Reference
Hit Ratio(h) = Hit / (Hit+Miss)
Average access time of any memory system consists of two levels: Cache and Main Memory. If Tc is time to access cache memory and Tm is the time to access main memory then we can write:
Tavg = Average time to access memory
Tavg = h * Tc + (1-h)*(Tm + Tc)
VaibhavRai3
Technical Scripter 2018
Computer Organization & Architecture
GATE CS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Addressing modes in 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Architecture of 8085 microprocessor
8085 program to add two 8 bit numbers
Computer Organization | Booth's Algorithm
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems | [
{
"code": null,
"e": 24320,
"s": 24292,
"text": "\n21 Aug, 2019"
},
{
"code": null,
"e": 24712,
"s": 24320,
"text": "Locality of reference refers to a phenomenon in which a computer program tends to access same set of memory locations for a particular time period. In other words, Locality of Reference refers to the tendency of the computer program to access instructions whose addresses are near one another. The property of locality of reference is mainly shown by loops and subroutine calls in a program."
},
{
"code": null,
"e": 25022,
"s": 24712,
"text": "In case of loops in program control processing unit repeatedly refers to the set of instructions that constitute the loop.In case of subroutine calls, everytime the set of instructions are fetched from memory.References to data items also get localized that means same data item is referenced again and again."
},
{
"code": null,
"e": 25145,
"s": 25022,
"text": "In case of loops in program control processing unit repeatedly refers to the set of instructions that constitute the loop."
},
{
"code": null,
"e": 25233,
"s": 25145,
"text": "In case of subroutine calls, everytime the set of instructions are fetched from memory."
},
{
"code": null,
"e": 25334,
"s": 25233,
"text": "References to data items also get localized that means same data item is referenced again and again."
},
{
"code": null,
"e": 25891,
"s": 25334,
"text": "In the above figure, you can see that the CPU wants to read or fetch the data or instruction. First, it will access the cache memory as it is near to it and provides very fast access. If the required data or instruction is found, it will be fetched. This situation is known as a cache hit. But if the required data or instruction is not found in the cache memory then this situation is known as a cache miss. Now the main memory will be searched for the required data or instruction that was being searched and if found will go through one of the two ways:"
},
{
"code": null,
"e": 26340,
"s": 25891,
"text": "First way is that the CPU should fetch the required data or instruction and use it and that’s it but what, when the same data or instruction is required again.CPU again has to access the same main memory location for it and we already know that main memory is the slowest to access.The second way is to store the data or instruction in the cache memory so that if it is needed soon again in the near future it could be fetched in a much faster way."
},
{
"code": null,
"e": 26623,
"s": 26340,
"text": "First way is that the CPU should fetch the required data or instruction and use it and that’s it but what, when the same data or instruction is required again.CPU again has to access the same main memory location for it and we already know that main memory is the slowest to access."
},
{
"code": null,
"e": 26790,
"s": 26623,
"text": "The second way is to store the data or instruction in the cache memory so that if it is needed soon again in the near future it could be fetched in a much faster way."
},
{
"code": null,
"e": 27005,
"s": 26790,
"text": "Cache Operation:It is based on the principle of locality of reference. There are two ways with which data or instruction is fetched from main memory and get stored in cache memory. These two ways are the following:"
},
{
"code": null,
"e": 27993,
"s": 27005,
"text": "Temporal Locality –Temporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory so that we can avoid again searching in main memory for the same data.When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future.Spatial Locality –Spatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future. This is slightly different from the temporal locality. Here we are talking about nearly located memory locations while in temporal locality we were talking about the actual memory location that was being fetched."
},
{
"code": null,
"e": 28610,
"s": 27993,
"text": "Temporal Locality –Temporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory so that we can avoid again searching in main memory for the same data.When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future."
},
{
"code": null,
"e": 28980,
"s": 28610,
"text": "When CPU accesses the current main memory location for reading required data or instruction, it also gets stored in the cache memory which is based on the fact that same data or instruction may be needed in near future. This is known as temporal locality. If some data is referenced, then there is a high probability that it will be referenced again in the near future."
},
{
"code": null,
"e": 29352,
"s": 28980,
"text": "Spatial Locality –Spatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in the near future. This is slightly different from the temporal locality. Here we are talking about nearly located memory locations while in temporal locality we were talking about the actual memory location that was being fetched."
},
{
"code": null,
"e": 29709,
"s": 29352,
"text": "Cache Performance:The performance of the cache is measured in terms of hit ratio. When CPU refers to memory and find the data or instruction within the Cache Memory, it is known as cache hit. If the desired data or instruction is not found in the cache memory and CPU refers to the main memory to find that data or instruction, it is known as a cache miss."
},
{
"code": null,
"e": 29776,
"s": 29709,
"text": "Hit + Miss = Total CPU Reference\nHit Ratio(h) = Hit / (Hit+Miss) "
},
{
"code": null,
"e": 29961,
"s": 29776,
"text": "Average access time of any memory system consists of two levels: Cache and Main Memory. If Tc is time to access cache memory and Tm is the time to access main memory then we can write:"
},
{
"code": null,
"e": 30031,
"s": 29961,
"text": "Tavg = Average time to access memory\nTavg = h * Tc + (1-h)*(Tm + Tc) "
},
{
"code": null,
"e": 30043,
"s": 30031,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 30067,
"s": 30043,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30104,
"s": 30067,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 30112,
"s": 30104,
"text": "GATE CS"
},
{
"code": null,
"e": 30131,
"s": 30112,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30229,
"s": 30131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30238,
"s": 30229,
"text": "Comments"
},
{
"code": null,
"e": 30251,
"s": 30238,
"text": "Old Comments"
},
{
"code": null,
"e": 30291,
"s": 30251,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 30386,
"s": 30291,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 30422,
"s": 30386,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 30460,
"s": 30422,
"text": "8085 program to add two 8 bit numbers"
},
{
"code": null,
"e": 30502,
"s": 30460,
"text": "Computer Organization | Booth's Algorithm"
},
{
"code": null,
"e": 30522,
"s": 30502,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 30546,
"s": 30522,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30567,
"s": 30546,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 30594,
"s": 30567,
"text": "Types of Operating Systems"
}
]
|
Home Automation with Alexa. Voice commands with IoT emulated... | by Marcelo Rovai | Towards Data Science | A few years ago, I explored how to use Alexa, an intelligent personal assistant made popular by the Amazon Echo and Echo-Dot, in Home Automation projects:
When IoT Meets AI: Home Automation With Alexa and NodeMCU and
Alexa — NodeMCU: WeMo Emulation Made Simple
Alexa is capable of voice interaction, music playback, making to-do lists, setting alarms, streaming podcasts, playing audiobooks, and providing weather, traffic, and other real-time information. Alexa can also control several smart devices using itself as a home automation hub. We will use on this project, the “Echo Dot”, which allows users to activate the device using a wake-word, such as “Alexa” or “Computer”, as in “Star Trek!.
In the home automation space, Alexa can interact with several different devices like Philips Hue, Belkin Wemo, Sonoff, etc. We emulated WeMo devices on previous projects, using the fauxmoESP library, which seems outdated and not adequately maintained nowadays. Here we will use Espalexa, an easy to use Arduino library compatible with both ESP8266 and ESP32.
The below block diagram shows what will be developed on our project:
The below video shows how the project will look like at the end:
At Arduino IDE Preferences → Additional boards Manager URLs enter with:
https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.json
Next, at Arduino IDE Tools/Boards Manager, Install boards:
In this project, we will use the NodeMCU, but the code could be easily adapted to also work with ESP32. So, let’s also install it:
The ESP8266 NodeMCU Pinout:
Espalexa allows you to set a range of values (e.g., Brightness, Temperature) and optionally a color, additionally to standard on/off control. For example, you can say — — “Alexa, turn the light to 75% “.
Espalexa emulates parts of the SSDP protocol and the Philips hue API, just enough to be discovered and controlled by Alexa.
By default, it’s possible to add up to a total of 10 devices because each device “slot” occupies memory, even if no device is initialized. You can change the maximum number of devices by adding, for example:
#define ESPALEXA_MAXDEVICES 20
before calling the library:
#include <Espalexa.h>
It is recommended to set MAXDEVICES to the exact number of devices you want to add to optimize memory usage.
To install the library, go to Arduino IDE Tools/Manage Libraries, and enter with espalexa:
Our Home Automation project will be created having four smart devices working that can be individually remotely controlled. But suppose that we want to group our devices to be used in our home. What should be done?
For example, suppose that our home has two rooms:
Bed Room
Living Room
Now, suppose that you want to have one lamp and one outlet in each room. So, let’s group our four devices, as shown in the block diagram (at this article introduction):
Bed Room
Light 2
Outlet 1 (Fan)
Living Room
Light1
Outlet 2 (Buzzer)
Ou Home Automation Project will be more or less like this:
For testing purposes, four color LEDs will be used as “IoT devices”. They should be installed as shown in the diagram and listed below:
==> Red LED (Light1) ==> NodeMCU D1 (GPIO5) — Living Room
==> Green LED (Outlet1) ==> NodeMCU D2 (GPIO4) — Living Room
==> Blue LED (Light2) ==> NodeMCU D5 (GPIO14) — Bed Room
==> Yellow LED (Outlet2) ==> NodeMCU D6 (GPIO12) — Bed Room
The LEDs red and green will simulate the devices installed on “Living Room,” and LEDs blue and yellow will simulate the ones installed on “Bed Room.”
First, we must call the libraries:
#include <ESP8266WiFi.h>#include <Espalexa.h>
Following for NodeMCU pins definitions to be connected to devices (at test phase will be LEDs and at final project, Relays inputs):
#define RelayPin1 5 //D1#define RelayPin2 4 //D2#define RelayPin3 14 //D5#define RelayPin4 12 //D6
Once we have 4 devices, at least 4 direct callback functions should be defined:
void device1Changed(uint8_t brightness);void device2Changed(uint8_t brightness);void device3Changed(uint8_t brightness);void device4Changed(uint8_t brightness);
The brightness parameter contains the new device state (0:off, 255:on, 1–254:dimmed) that will be sent by Alexa when that callback function is called.
But the callback function can be any function to be executed under Alexa command, so we will define here three additional special functions to be called that will handle multiple IoT devices:
void devFunc1Changed(uint8_t brightness);void devFunc2Changed(uint8_t brightness);void devFunc3Changed(uint8_t brightness);
The above callback functions will be associated with:
All Home Devices (Light1, Light2, Outlet1, and Outlet2)
Living Room (Light1 and Outlet1)
Bed Room (Light2 and Outlet2)
So, Alexa will in fact handle seven “IoT devices”. For each one of them, we must define a unique name to be called by Alexa:
// device namesString Device_1_Name = "Red light";String Device_2_Name = "Green light";String Device_3_Name = "Blue light";String Device_4_Name = "Yellow light";// device_function namesString Dev_Func_1_Name = "Living Room";String Dev_Func_2_Name = "Bed Room";String Dev_Func_3_Name = "All Home Devices";
During testing phase, we will call the LEDs by “{its color} Light”. On our final project we can changed those variables by its final name (“Light 1”, “Outlet2”, etc).
The last but not least, we should declare the variables to be used by espalexa:
Espalexa espalexa;
and for communication:
boolean connectWifi();boolean wifiConnected = false;const char* ssid = "YOUR SSID HERE";const char* password = "YOUR PASSWORD HERE";
On Setup phase, you should besides the usual pin and serial bald-rate definitions and communication start procedures, have each one of the IoT devices with its name properly associated and espalexa started:
// Define your devices here.espalexa.addDevice(Device_1_Name, device1Changed);espalexa.addDevice(Device_2_Name, device2Changed);espalexa.addDevice(Device_3_Name, device3Changed);espalexa.addDevice(Device_4_Name, device4Changed);// Define your devices functions here.espalexa.addDevice(Dev_Func_1_Name, devFunc1Changed);espalexa.addDevice(Dev_Func_2_Name, devFunc2Changed);espalexa.addDevice(Dev_Func_3_Name, devFunc3Changed);espalexa.begin();
The loop function should be very simple:
void loop(){ espalexa.loop(); delay(1);}
The last procedure will be creating of callback functions, or better, what must be done when Alexa sent a command.
The below callback function could be adapted for all four IoT devices:
void deviceNChanged(uint8_t brightness){ //Control the device if (brightness == 255) { digitalWrite(RelayPinN, HIGH); Serial.println("DeviceN ON"); } else { digitalWrite(RelayPinN, LOW); Serial.println("DeviceN OFF"); }}
Changing “N” on the above code by 1, 2, 3, and 4 will have the four direct callback functions. Remember that brightness parameter sent by Alexa, contains the new device state that will be:
0 ==> OFF;
255 ==> ON
1 to 254 ==> “dimmed light”.
We can expand the above simple ON-OFF function for a special function where a light intensity can be controlled. We will do this for the device1 (the Red LED):
void device1Changed(uint8_t brightness){ //Control the device if (brightness == 255) { digitalWrite(RelayPin1, HIGH); Serial.println("Device1 ON"); } else if (brightness == 0) { digitalWrite(RelayPin1, LOW); Serial.println("Device1 OFF"); } else { int brigh_perc = (brightness/255.)*100; analogWrite(RelayPin1, brightness); Serial.print("Device1 Brightness: "); Serial.print(brigh_perc); Serial.println("%"); }}
Remember that the NodeMCU has PWM outputs that can be used with Arduino analogWrite() function. If an ESP32 is used, the PWM function should be created once the analogWrite() is not available.
The complete code can be downloaded from my GitHub: Alexa_NodeMCU_Home_Automation
Do not forget to change the dummy wifi credentials with your own.
Once you compile the code on Arduino IDE and upload it to the NodeMCU, you can see the messages exchanged on the Serial monitor. Once the NodeMCU is connected to your wifi, a similar message (with your network data) should appear:
We consider that you already have an Alexa adequately installed on the same network where your NodeMcu is connected.
Now, let’s ask Alexa to find your devices. There are two methods to do it:
Using the Alexa App in your Smartphone
Asking Alexa to do it directly using voice command, like: “Alexa, discovery devices”.
After 45 seconds, you should receive Alexa confirmation that seven devices were found. You can see than on the App “Light tab” as below:
Once Alexa has discovered your devices, you can give her voice commands, as shown below:
The below screenshot shows the Serial monitor response.
Instead of LEDs and resistors, the Outputs GPIOs should be connected to the 4-Channel Relay model as below:
Do not power the Relay-Module directly from the NodeMcu 5V output pin. Use an external Power supply for that instead. A 1A Power Supply should be enough. Confirm with the Relay-Module manufacturer if another version is used. Do not forget to connect the GNDs all together.
In principle, the same code developed for testing can be used, BUT you must confirm the Relay-Module’s logic. For example, in the above module, you should keep the inputs “Open” or HIGH, changing to LOW to activate the Relay output. So, the code must be changed accordantly.
During setup() phase, define GPIOs outputs as HIGH
On CallBack functions change HIGH for LOW and vice-versa
You can confirm that relays are working properly by both, the sound of output relay closing and from a red led in the module.
Once everything is correctly working is the time for complete installation of our “smart devices”, which are two fixed “Lamps” and 2 “general Outlets”, let’s rename them appropriately:
Light One
Light Two
Outlet One
Outlet Two
// device namesString Device_1_Name = "Light One"; String Device_2_Name = "Light Two";String Device_3_Name = "Outlet One";String Device_4_Name = "Outlet Two";
As shown on the video at the start of this tutorial, to complete our project, connect some devices to be controlled by relays. In my case, I use two LEDs as lamps and attach a fan on outlet 1 and a buzzer on outlet 2 (to simulate a device like a radio, for example). The below diagram shows the appliances installed.
Note that you can install real AC Lamps and appliances to be controlled using Alexa once the relays can handle them.
Starting from the concept of emulating simple IoT devices, as WeMo or Philips Hue, we also used Alexa to “trigger” more complex functions, “the Device Functions”. On those functions, multiple outputs were used as a group of the devices split by rooms.
In my tutorial, Computer, Firing All Weapons, some of Star Trek Enterprise weapons, as Photon Torpedos and Phasers, were simulated using such functions.
This is a powerful tool to be explored in the IoT field, where a simple voice command can trigger more complex processes using microcontrollers, as can be observed on below video (Here "Computer" wake-word was used instead "Alexa"):
As always, I hope this project can help others find their way in the exciting world of electronics and IoT!
Please visit my GitHub for updated files: Alexa_NodeMCU_Home_Automation
For more projects, please visit my blog: MJRoBot.org
Saludos from the south of the world!
See you at my next article! | [
{
"code": null,
"e": 326,
"s": 171,
"text": "A few years ago, I explored how to use Alexa, an intelligent personal assistant made popular by the Amazon Echo and Echo-Dot, in Home Automation projects:"
},
{
"code": null,
"e": 388,
"s": 326,
"text": "When IoT Meets AI: Home Automation With Alexa and NodeMCU and"
},
{
"code": null,
"e": 432,
"s": 388,
"text": "Alexa — NodeMCU: WeMo Emulation Made Simple"
},
{
"code": null,
"e": 868,
"s": 432,
"text": "Alexa is capable of voice interaction, music playback, making to-do lists, setting alarms, streaming podcasts, playing audiobooks, and providing weather, traffic, and other real-time information. Alexa can also control several smart devices using itself as a home automation hub. We will use on this project, the “Echo Dot”, which allows users to activate the device using a wake-word, such as “Alexa” or “Computer”, as in “Star Trek!."
},
{
"code": null,
"e": 1227,
"s": 868,
"text": "In the home automation space, Alexa can interact with several different devices like Philips Hue, Belkin Wemo, Sonoff, etc. We emulated WeMo devices on previous projects, using the fauxmoESP library, which seems outdated and not adequately maintained nowadays. Here we will use Espalexa, an easy to use Arduino library compatible with both ESP8266 and ESP32."
},
{
"code": null,
"e": 1296,
"s": 1227,
"text": "The below block diagram shows what will be developed on our project:"
},
{
"code": null,
"e": 1361,
"s": 1296,
"text": "The below video shows how the project will look like at the end:"
},
{
"code": null,
"e": 1433,
"s": 1361,
"text": "At Arduino IDE Preferences → Additional boards Manager URLs enter with:"
},
{
"code": null,
"e": 1551,
"s": 1433,
"text": "https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.json"
},
{
"code": null,
"e": 1610,
"s": 1551,
"text": "Next, at Arduino IDE Tools/Boards Manager, Install boards:"
},
{
"code": null,
"e": 1741,
"s": 1610,
"text": "In this project, we will use the NodeMCU, but the code could be easily adapted to also work with ESP32. So, let’s also install it:"
},
{
"code": null,
"e": 1769,
"s": 1741,
"text": "The ESP8266 NodeMCU Pinout:"
},
{
"code": null,
"e": 1973,
"s": 1769,
"text": "Espalexa allows you to set a range of values (e.g., Brightness, Temperature) and optionally a color, additionally to standard on/off control. For example, you can say — — “Alexa, turn the light to 75% “."
},
{
"code": null,
"e": 2097,
"s": 1973,
"text": "Espalexa emulates parts of the SSDP protocol and the Philips hue API, just enough to be discovered and controlled by Alexa."
},
{
"code": null,
"e": 2305,
"s": 2097,
"text": "By default, it’s possible to add up to a total of 10 devices because each device “slot” occupies memory, even if no device is initialized. You can change the maximum number of devices by adding, for example:"
},
{
"code": null,
"e": 2336,
"s": 2305,
"text": "#define ESPALEXA_MAXDEVICES 20"
},
{
"code": null,
"e": 2364,
"s": 2336,
"text": "before calling the library:"
},
{
"code": null,
"e": 2386,
"s": 2364,
"text": "#include <Espalexa.h>"
},
{
"code": null,
"e": 2495,
"s": 2386,
"text": "It is recommended to set MAXDEVICES to the exact number of devices you want to add to optimize memory usage."
},
{
"code": null,
"e": 2586,
"s": 2495,
"text": "To install the library, go to Arduino IDE Tools/Manage Libraries, and enter with espalexa:"
},
{
"code": null,
"e": 2801,
"s": 2586,
"text": "Our Home Automation project will be created having four smart devices working that can be individually remotely controlled. But suppose that we want to group our devices to be used in our home. What should be done?"
},
{
"code": null,
"e": 2851,
"s": 2801,
"text": "For example, suppose that our home has two rooms:"
},
{
"code": null,
"e": 2860,
"s": 2851,
"text": "Bed Room"
},
{
"code": null,
"e": 2872,
"s": 2860,
"text": "Living Room"
},
{
"code": null,
"e": 3041,
"s": 2872,
"text": "Now, suppose that you want to have one lamp and one outlet in each room. So, let’s group our four devices, as shown in the block diagram (at this article introduction):"
},
{
"code": null,
"e": 3050,
"s": 3041,
"text": "Bed Room"
},
{
"code": null,
"e": 3058,
"s": 3050,
"text": "Light 2"
},
{
"code": null,
"e": 3073,
"s": 3058,
"text": "Outlet 1 (Fan)"
},
{
"code": null,
"e": 3085,
"s": 3073,
"text": "Living Room"
},
{
"code": null,
"e": 3092,
"s": 3085,
"text": "Light1"
},
{
"code": null,
"e": 3110,
"s": 3092,
"text": "Outlet 2 (Buzzer)"
},
{
"code": null,
"e": 3169,
"s": 3110,
"text": "Ou Home Automation Project will be more or less like this:"
},
{
"code": null,
"e": 3305,
"s": 3169,
"text": "For testing purposes, four color LEDs will be used as “IoT devices”. They should be installed as shown in the diagram and listed below:"
},
{
"code": null,
"e": 3363,
"s": 3305,
"text": "==> Red LED (Light1) ==> NodeMCU D1 (GPIO5) — Living Room"
},
{
"code": null,
"e": 3424,
"s": 3363,
"text": "==> Green LED (Outlet1) ==> NodeMCU D2 (GPIO4) — Living Room"
},
{
"code": null,
"e": 3481,
"s": 3424,
"text": "==> Blue LED (Light2) ==> NodeMCU D5 (GPIO14) — Bed Room"
},
{
"code": null,
"e": 3541,
"s": 3481,
"text": "==> Yellow LED (Outlet2) ==> NodeMCU D6 (GPIO12) — Bed Room"
},
{
"code": null,
"e": 3691,
"s": 3541,
"text": "The LEDs red and green will simulate the devices installed on “Living Room,” and LEDs blue and yellow will simulate the ones installed on “Bed Room.”"
},
{
"code": null,
"e": 3726,
"s": 3691,
"text": "First, we must call the libraries:"
},
{
"code": null,
"e": 3772,
"s": 3726,
"text": "#include <ESP8266WiFi.h>#include <Espalexa.h>"
},
{
"code": null,
"e": 3904,
"s": 3772,
"text": "Following for NodeMCU pins definitions to be connected to devices (at test phase will be LEDs and at final project, Relays inputs):"
},
{
"code": null,
"e": 4005,
"s": 3904,
"text": "#define RelayPin1 5 //D1#define RelayPin2 4 //D2#define RelayPin3 14 //D5#define RelayPin4 12 //D6"
},
{
"code": null,
"e": 4085,
"s": 4005,
"text": "Once we have 4 devices, at least 4 direct callback functions should be defined:"
},
{
"code": null,
"e": 4246,
"s": 4085,
"text": "void device1Changed(uint8_t brightness);void device2Changed(uint8_t brightness);void device3Changed(uint8_t brightness);void device4Changed(uint8_t brightness);"
},
{
"code": null,
"e": 4397,
"s": 4246,
"text": "The brightness parameter contains the new device state (0:off, 255:on, 1–254:dimmed) that will be sent by Alexa when that callback function is called."
},
{
"code": null,
"e": 4589,
"s": 4397,
"text": "But the callback function can be any function to be executed under Alexa command, so we will define here three additional special functions to be called that will handle multiple IoT devices:"
},
{
"code": null,
"e": 4713,
"s": 4589,
"text": "void devFunc1Changed(uint8_t brightness);void devFunc2Changed(uint8_t brightness);void devFunc3Changed(uint8_t brightness);"
},
{
"code": null,
"e": 4767,
"s": 4713,
"text": "The above callback functions will be associated with:"
},
{
"code": null,
"e": 4823,
"s": 4767,
"text": "All Home Devices (Light1, Light2, Outlet1, and Outlet2)"
},
{
"code": null,
"e": 4856,
"s": 4823,
"text": "Living Room (Light1 and Outlet1)"
},
{
"code": null,
"e": 4886,
"s": 4856,
"text": "Bed Room (Light2 and Outlet2)"
},
{
"code": null,
"e": 5011,
"s": 4886,
"text": "So, Alexa will in fact handle seven “IoT devices”. For each one of them, we must define a unique name to be called by Alexa:"
},
{
"code": null,
"e": 5316,
"s": 5011,
"text": "// device namesString Device_1_Name = \"Red light\";String Device_2_Name = \"Green light\";String Device_3_Name = \"Blue light\";String Device_4_Name = \"Yellow light\";// device_function namesString Dev_Func_1_Name = \"Living Room\";String Dev_Func_2_Name = \"Bed Room\";String Dev_Func_3_Name = \"All Home Devices\";"
},
{
"code": null,
"e": 5483,
"s": 5316,
"text": "During testing phase, we will call the LEDs by “{its color} Light”. On our final project we can changed those variables by its final name (“Light 1”, “Outlet2”, etc)."
},
{
"code": null,
"e": 5563,
"s": 5483,
"text": "The last but not least, we should declare the variables to be used by espalexa:"
},
{
"code": null,
"e": 5582,
"s": 5563,
"text": "Espalexa espalexa;"
},
{
"code": null,
"e": 5605,
"s": 5582,
"text": "and for communication:"
},
{
"code": null,
"e": 5738,
"s": 5605,
"text": "boolean connectWifi();boolean wifiConnected = false;const char* ssid = \"YOUR SSID HERE\";const char* password = \"YOUR PASSWORD HERE\";"
},
{
"code": null,
"e": 5945,
"s": 5738,
"text": "On Setup phase, you should besides the usual pin and serial bald-rate definitions and communication start procedures, have each one of the IoT devices with its name properly associated and espalexa started:"
},
{
"code": null,
"e": 6388,
"s": 5945,
"text": "// Define your devices here.espalexa.addDevice(Device_1_Name, device1Changed);espalexa.addDevice(Device_2_Name, device2Changed);espalexa.addDevice(Device_3_Name, device3Changed);espalexa.addDevice(Device_4_Name, device4Changed);// Define your devices functions here.espalexa.addDevice(Dev_Func_1_Name, devFunc1Changed);espalexa.addDevice(Dev_Func_2_Name, devFunc2Changed);espalexa.addDevice(Dev_Func_3_Name, devFunc3Changed);espalexa.begin();"
},
{
"code": null,
"e": 6429,
"s": 6388,
"text": "The loop function should be very simple:"
},
{
"code": null,
"e": 6472,
"s": 6429,
"text": "void loop(){ espalexa.loop(); delay(1);}"
},
{
"code": null,
"e": 6587,
"s": 6472,
"text": "The last procedure will be creating of callback functions, or better, what must be done when Alexa sent a command."
},
{
"code": null,
"e": 6658,
"s": 6587,
"text": "The below callback function could be adapted for all four IoT devices:"
},
{
"code": null,
"e": 6907,
"s": 6658,
"text": "void deviceNChanged(uint8_t brightness){ //Control the device if (brightness == 255) { digitalWrite(RelayPinN, HIGH); Serial.println(\"DeviceN ON\"); } else { digitalWrite(RelayPinN, LOW); Serial.println(\"DeviceN OFF\"); }}"
},
{
"code": null,
"e": 7096,
"s": 6907,
"text": "Changing “N” on the above code by 1, 2, 3, and 4 will have the four direct callback functions. Remember that brightness parameter sent by Alexa, contains the new device state that will be:"
},
{
"code": null,
"e": 7107,
"s": 7096,
"text": "0 ==> OFF;"
},
{
"code": null,
"e": 7118,
"s": 7107,
"text": "255 ==> ON"
},
{
"code": null,
"e": 7147,
"s": 7118,
"text": "1 to 254 ==> “dimmed light”."
},
{
"code": null,
"e": 7307,
"s": 7147,
"text": "We can expand the above simple ON-OFF function for a special function where a light intensity can be controlled. We will do this for the device1 (the Red LED):"
},
{
"code": null,
"e": 7756,
"s": 7307,
"text": "void device1Changed(uint8_t brightness){ //Control the device if (brightness == 255) { digitalWrite(RelayPin1, HIGH); Serial.println(\"Device1 ON\"); } else if (brightness == 0) { digitalWrite(RelayPin1, LOW); Serial.println(\"Device1 OFF\"); } else { int brigh_perc = (brightness/255.)*100; analogWrite(RelayPin1, brightness); Serial.print(\"Device1 Brightness: \"); Serial.print(brigh_perc); Serial.println(\"%\"); }}"
},
{
"code": null,
"e": 7949,
"s": 7756,
"text": "Remember that the NodeMCU has PWM outputs that can be used with Arduino analogWrite() function. If an ESP32 is used, the PWM function should be created once the analogWrite() is not available."
},
{
"code": null,
"e": 8031,
"s": 7949,
"text": "The complete code can be downloaded from my GitHub: Alexa_NodeMCU_Home_Automation"
},
{
"code": null,
"e": 8097,
"s": 8031,
"text": "Do not forget to change the dummy wifi credentials with your own."
},
{
"code": null,
"e": 8328,
"s": 8097,
"text": "Once you compile the code on Arduino IDE and upload it to the NodeMCU, you can see the messages exchanged on the Serial monitor. Once the NodeMCU is connected to your wifi, a similar message (with your network data) should appear:"
},
{
"code": null,
"e": 8445,
"s": 8328,
"text": "We consider that you already have an Alexa adequately installed on the same network where your NodeMcu is connected."
},
{
"code": null,
"e": 8520,
"s": 8445,
"text": "Now, let’s ask Alexa to find your devices. There are two methods to do it:"
},
{
"code": null,
"e": 8559,
"s": 8520,
"text": "Using the Alexa App in your Smartphone"
},
{
"code": null,
"e": 8645,
"s": 8559,
"text": "Asking Alexa to do it directly using voice command, like: “Alexa, discovery devices”."
},
{
"code": null,
"e": 8782,
"s": 8645,
"text": "After 45 seconds, you should receive Alexa confirmation that seven devices were found. You can see than on the App “Light tab” as below:"
},
{
"code": null,
"e": 8871,
"s": 8782,
"text": "Once Alexa has discovered your devices, you can give her voice commands, as shown below:"
},
{
"code": null,
"e": 8927,
"s": 8871,
"text": "The below screenshot shows the Serial monitor response."
},
{
"code": null,
"e": 9035,
"s": 8927,
"text": "Instead of LEDs and resistors, the Outputs GPIOs should be connected to the 4-Channel Relay model as below:"
},
{
"code": null,
"e": 9308,
"s": 9035,
"text": "Do not power the Relay-Module directly from the NodeMcu 5V output pin. Use an external Power supply for that instead. A 1A Power Supply should be enough. Confirm with the Relay-Module manufacturer if another version is used. Do not forget to connect the GNDs all together."
},
{
"code": null,
"e": 9583,
"s": 9308,
"text": "In principle, the same code developed for testing can be used, BUT you must confirm the Relay-Module’s logic. For example, in the above module, you should keep the inputs “Open” or HIGH, changing to LOW to activate the Relay output. So, the code must be changed accordantly."
},
{
"code": null,
"e": 9634,
"s": 9583,
"text": "During setup() phase, define GPIOs outputs as HIGH"
},
{
"code": null,
"e": 9691,
"s": 9634,
"text": "On CallBack functions change HIGH for LOW and vice-versa"
},
{
"code": null,
"e": 9817,
"s": 9691,
"text": "You can confirm that relays are working properly by both, the sound of output relay closing and from a red led in the module."
},
{
"code": null,
"e": 10002,
"s": 9817,
"text": "Once everything is correctly working is the time for complete installation of our “smart devices”, which are two fixed “Lamps” and 2 “general Outlets”, let’s rename them appropriately:"
},
{
"code": null,
"e": 10012,
"s": 10002,
"text": "Light One"
},
{
"code": null,
"e": 10022,
"s": 10012,
"text": "Light Two"
},
{
"code": null,
"e": 10033,
"s": 10022,
"text": "Outlet One"
},
{
"code": null,
"e": 10044,
"s": 10033,
"text": "Outlet Two"
},
{
"code": null,
"e": 10203,
"s": 10044,
"text": "// device namesString Device_1_Name = \"Light One\"; String Device_2_Name = \"Light Two\";String Device_3_Name = \"Outlet One\";String Device_4_Name = \"Outlet Two\";"
},
{
"code": null,
"e": 10520,
"s": 10203,
"text": "As shown on the video at the start of this tutorial, to complete our project, connect some devices to be controlled by relays. In my case, I use two LEDs as lamps and attach a fan on outlet 1 and a buzzer on outlet 2 (to simulate a device like a radio, for example). The below diagram shows the appliances installed."
},
{
"code": null,
"e": 10637,
"s": 10520,
"text": "Note that you can install real AC Lamps and appliances to be controlled using Alexa once the relays can handle them."
},
{
"code": null,
"e": 10889,
"s": 10637,
"text": "Starting from the concept of emulating simple IoT devices, as WeMo or Philips Hue, we also used Alexa to “trigger” more complex functions, “the Device Functions”. On those functions, multiple outputs were used as a group of the devices split by rooms."
},
{
"code": null,
"e": 11042,
"s": 10889,
"text": "In my tutorial, Computer, Firing All Weapons, some of Star Trek Enterprise weapons, as Photon Torpedos and Phasers, were simulated using such functions."
},
{
"code": null,
"e": 11275,
"s": 11042,
"text": "This is a powerful tool to be explored in the IoT field, where a simple voice command can trigger more complex processes using microcontrollers, as can be observed on below video (Here \"Computer\" wake-word was used instead \"Alexa\"):"
},
{
"code": null,
"e": 11383,
"s": 11275,
"text": "As always, I hope this project can help others find their way in the exciting world of electronics and IoT!"
},
{
"code": null,
"e": 11455,
"s": 11383,
"text": "Please visit my GitHub for updated files: Alexa_NodeMCU_Home_Automation"
},
{
"code": null,
"e": 11508,
"s": 11455,
"text": "For more projects, please visit my blog: MJRoBot.org"
},
{
"code": null,
"e": 11545,
"s": 11508,
"text": "Saludos from the south of the world!"
}
]
|
How to convert empty values to NA in an R data frame? | When our data has empty values then it is difficult to perform the analysis, we might to convert those empty values to NA so that we can understand the number of values that are not available. This can be done by using single square brackets.
Consider the below data frame that has some empty values −
> x1<-c(rep(c(1,2,3),times=5),"","","",2,1)
> x2<-rep(c(2,4,"",4,""),each=4)
> x3<-rep(c(5,4,2,""),times=c(2,5,3,10))
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 2
10 1 2
11 2
12 3
13 1 4
14 2 4
15 3 4
16 4
17
18
19 2
20 1
Converting empty values to NA −
> df[df == ""]<-NA
> df
x1 x2 x3
1 1 2 5
2 2 2 5
3 3 2 4
4 1 2 4
5 2 4 4
6 3 4 4
7 1 4 4
8 2 4 2
9 3 <NA> 2
10 1 <NA> 2
11 2 <NA> <NA>
12 3 <NA> <NA>
13 1 4 <NA>
14 2 4 <NA>
15 3 4 <NA>
16 <NA> 4 <NA>
17 <NA> <NA> <NA>
18 <NA> <NA> <NA>
19 2 <NA> <NA>
20 1 <NA> <NA> | [
{
"code": null,
"e": 1305,
"s": 1062,
"text": "When our data has empty values then it is difficult to perform the analysis, we might to convert those empty values to NA so that we can understand the number of values that are not available. This can be done by using single square brackets."
},
{
"code": null,
"e": 1364,
"s": 1305,
"text": "Consider the below data frame that has some empty values −"
},
{
"code": null,
"e": 1652,
"s": 1364,
"text": "> x1<-c(rep(c(1,2,3),times=5),\"\",\"\",\"\",2,1)\n> x2<-rep(c(2,4,\"\",4,\"\"),each=4)\n> x3<-rep(c(5,4,2,\"\"),times=c(2,5,3,10))\n> df<-data.frame(x1,x2,x3)\n> df\nx1 x2 x3\n1 1 2 5\n2 2 2 5\n3 3 2 4\n4 1 2 4\n5 2 4 4\n6 3 4 4\n7 1 4 4\n8 2 4 2\n9 3 2\n10 1 2\n11 2\n12 3\n13 1 4\n14 2 4\n15 3 4\n16 4\n17\n18\n19 2\n20 1"
},
{
"code": null,
"e": 1684,
"s": 1652,
"text": "Converting empty values to NA −"
},
{
"code": null,
"e": 1951,
"s": 1684,
"text": "> df[df == \"\"]<-NA\n> df\nx1 x2 x3\n1 1 2 5\n2 2 2 5\n3 3 2 4\n4 1 2 4\n5 2 4 4\n6 3 4 4\n7 1 4 4\n8 2 4 2\n9 3 <NA> 2\n10 1 <NA> 2\n11 2 <NA> <NA>\n12 3 <NA> <NA>\n13 1 4 <NA>\n14 2 4 <NA>\n15 3 4 <NA>\n16 <NA> 4 <NA>\n17 <NA> <NA> <NA>\n18 <NA> <NA> <NA>\n19 2 <NA> <NA>\n20 1 <NA> <NA>"
}
]
|
Binary Tree (Array implementation) - GeeksforGeeks | 27 Dec, 2021
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation. Do refer in order to understand how to construct binary tree from given parent array representation.
Ways to represent:
Trees can be represented in two ways as listed below:
Dynamic Node Representation (Linked Representation).Array Representation (Sequential Representation).
Dynamic Node Representation (Linked Representation).
Array Representation (Sequential Representation).
Now, we are going to talk about the sequential representation of the trees. In order to represent a tree using an array, the numbering of nodes can start either from 0–(n-1) or 1– n, consider the below illustration as follows:
Illustration:
A(0)
/ \
B(1) C(2)
/ \ \
D(3) E(4) F(6)
OR,
A(1)
/ \
B(2) C(3)
/ \ \
D(4) E(5) F(7)
Procedure:
Note: father, left_son and right_son are the values of indices of the array.
Case 1: (0—n-1)
if (say)father=p;
then left_son=(2*p)+1;
and right_son=(2*p)+2;
Case 2: 1—n
if (say)father=p;
then left_son=(2*p);
and right_son=(2*p)+1;
Implementation:
Examples
C++
Java
C#
Python3
// C++ implementation of tree using array// numbering starting from 0 to n-1.#include<bits/stdc++.h>using namespace std;char tree[10];int root(char key) { if (tree[0] != '\0') cout << "Tree already had root"; else tree[0] = key; return 0;} int set_left(char key, int parent) { if (tree[parent] == '\0') cout << "\nCan't set child at" << (parent * 2) + 1 << " , no parent found"; else tree[(parent * 2) + 1] = key; return 0;} int set_right(char key, int parent) { if (tree[parent] == '\0') cout << "\nCan't set child at" << (parent * 2) + 2 << " , no parent found"; else tree[(parent * 2) + 2] = key; return 0;} int print_tree() { cout << "\n"; for (int i = 0; i < 10; i++) { if (tree[i] != '\0') cout << tree[i]; else cout << "-"; } return 0;} // Driver Codeint main() { root('A'); //insert_left('B',0); set_right('C', 0); set_left('D', 1); set_right('E', 1); set_right('F', 2); print_tree(); return 0;}
// JAVA implementation of tree using array// numbering starting from 0 to n-1. // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper class (Node class)class Tree { // Main driver method public static void main(String[] args) { // Creating object of class 2 inside main() method Array_imp obj = new Array_imp(); // Setting root node obj.Root("A"); // obj.set_Left("B", 0); obj.set_Right("C", 0); obj.set_Left("D", 1); obj.set_Right("E", 1); obj.set_Left("F", 2); obj.print_Tree(); }} // Class 2// Helper classclass Array_imp { // Member variables of this class static int root = 0; static String[] str = new String[10]; // Method 1 // Creating root node public void Root(String key) { str[0] = key; } // Method 2 // Creating left son of root public void set_Left(String key, int root) { int t = (root * 2) + 1; if (str[root] == null) { System.out.printf( "Can't set child at %d, no parent found\n", t); } else { str[t] = key; } } // Method 3 // Creating right son of root public void set_Right(String key, int root) { int t = (root * 2) + 2; if (str[root] == null) { System.out.printf( "Can't set child at %d, no parent found\n", t); } else { str[t] = key; } } // Method 4 // To print our tree public void print_Tree() { // Iterating using for loop for (int i = 0; i < 10; i++) { if (str[i] != null) System.out.print(str[i]); else System.out.print("-"); } }}
// C# implementation of tree using array// numbering starting from 0 to n-1.using System; public class Tree { public static void Main(String[] args) { Array_imp obj = new Array_imp(); obj.Root("A"); // obj.set_Left("B", 0); obj.set_Right("C", 0); obj.set_Left("D", 1); obj.set_Right("E", 1); obj.set_Left("F", 2); obj.print_Tree(); }} class Array_imp { static int root = 0; static String[] str = new String[10]; /*create root*/ public void Root(String key) { str[0] = key; } /*create left son of root*/ public void set_Left(String key, int root) { int t = (root * 2) + 1; if (str[root] == null) { Console.Write("Can't set child at {0}, no parent found\n", t); } else { str[t] = key; } } /*create right son of root*/ public void set_Right(String key, int root) { int t = (root * 2) + 2; if (str[root] == null) { Console.Write("Can't set child at {0}, no parent found\n", t); } else { str[t] = key; } } public void print_Tree() { for (int i = 0; i < 10; i++) { if (str[i] != null) Console.Write(str[i]); else Console.Write("-"); } }} // This code contributed by Rajput-Ji
# Python3 implementation of tree using array# numbering starting from 0 to n-1.tree = [None] * 10 def root(key): if tree[0] != None: print("Tree already had root") else: tree[0] = key def set_left(key, parent): if tree[parent] == None: print("Can't set child at", (parent * 2) + 1, ", no parent found") else: tree[(parent * 2) + 1] = key def set_right(key, parent): if tree[parent] == None: print("Can't set child at", (parent * 2) + 2, ", no parent found") else: tree[(parent * 2) + 2] = key def print_tree(): for i in range(10): if tree[i] != None: print(tree[i], end="") else: print("-", end="") print() # Driver Coderoot('A')set_right('C', 0)set_left('D', 1)set_right('E', 1)set_right('F', 2)print_tree() # This code is contributed by Gaurav Kumar Tailor
Can't set child at3 , no parent found
Can't set child at4 , no parent found
A-C---F---
Sachin Jain 1
diegoolalde
Rajput-Ji
gaurav_kumar_raghav
gauravtailorthoi
hitesh sharma 3
msr20comp
simmytarika5
germanshephered48
Binary Tree
Java-Array-Programs
Arrays
Java
Technical Scripter
Tree
Arrays
Java
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Program for array rotation
Largest Sum Contiguous Subarray
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 35846,
"s": 35818,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 36299,
"s": 35846,
"text": "Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation. Do refer in order to understand how to construct binary tree from given parent array representation."
},
{
"code": null,
"e": 36319,
"s": 36299,
"text": "Ways to represent: "
},
{
"code": null,
"e": 36373,
"s": 36319,
"text": "Trees can be represented in two ways as listed below:"
},
{
"code": null,
"e": 36475,
"s": 36373,
"text": "Dynamic Node Representation (Linked Representation).Array Representation (Sequential Representation)."
},
{
"code": null,
"e": 36528,
"s": 36475,
"text": "Dynamic Node Representation (Linked Representation)."
},
{
"code": null,
"e": 36578,
"s": 36528,
"text": "Array Representation (Sequential Representation)."
},
{
"code": null,
"e": 36806,
"s": 36578,
"text": "Now, we are going to talk about the sequential representation of the trees. In order to represent a tree using an array, the numbering of nodes can start either from 0–(n-1) or 1– n, consider the below illustration as follows:"
},
{
"code": null,
"e": 36820,
"s": 36806,
"text": "Illustration:"
},
{
"code": null,
"e": 36982,
"s": 36820,
"text": " A(0) \n / \\\n B(1) C(2) \n / \\ \\\n D(3) E(4) F(6) \nOR,\n A(1) \n / \\\n B(2) C(3) \n / \\ \\\n D(4) E(5) F(7) "
},
{
"code": null,
"e": 36993,
"s": 36982,
"text": "Procedure:"
},
{
"code": null,
"e": 37070,
"s": 36993,
"text": "Note: father, left_son and right_son are the values of indices of the array."
},
{
"code": null,
"e": 37088,
"s": 37070,
"text": " Case 1: (0—n-1) "
},
{
"code": null,
"e": 37154,
"s": 37088,
"text": "if (say)father=p; \nthen left_son=(2*p)+1; \nand right_son=(2*p)+2;"
},
{
"code": null,
"e": 37166,
"s": 37154,
"text": "Case 2: 1—n"
},
{
"code": null,
"e": 37231,
"s": 37166,
"text": "if (say)father=p; \nthen left_son=(2*p); \nand right_son=(2*p)+1; "
},
{
"code": null,
"e": 37247,
"s": 37231,
"text": "Implementation:"
},
{
"code": null,
"e": 37257,
"s": 37247,
"text": "Examples "
},
{
"code": null,
"e": 37261,
"s": 37257,
"text": "C++"
},
{
"code": null,
"e": 37266,
"s": 37261,
"text": "Java"
},
{
"code": null,
"e": 37269,
"s": 37266,
"text": "C#"
},
{
"code": null,
"e": 37277,
"s": 37269,
"text": "Python3"
},
{
"code": "// C++ implementation of tree using array// numbering starting from 0 to n-1.#include<bits/stdc++.h>using namespace std;char tree[10];int root(char key) { if (tree[0] != '\\0') cout << \"Tree already had root\"; else tree[0] = key; return 0;} int set_left(char key, int parent) { if (tree[parent] == '\\0') cout << \"\\nCan't set child at\" << (parent * 2) + 1 << \" , no parent found\"; else tree[(parent * 2) + 1] = key; return 0;} int set_right(char key, int parent) { if (tree[parent] == '\\0') cout << \"\\nCan't set child at\" << (parent * 2) + 2 << \" , no parent found\"; else tree[(parent * 2) + 2] = key; return 0;} int print_tree() { cout << \"\\n\"; for (int i = 0; i < 10; i++) { if (tree[i] != '\\0') cout << tree[i]; else cout << \"-\"; } return 0;} // Driver Codeint main() { root('A'); //insert_left('B',0); set_right('C', 0); set_left('D', 1); set_right('E', 1); set_right('F', 2); print_tree(); return 0;}",
"e": 38248,
"s": 37277,
"text": null
},
{
"code": "// JAVA implementation of tree using array// numbering starting from 0 to n-1. // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper class (Node class)class Tree { // Main driver method public static void main(String[] args) { // Creating object of class 2 inside main() method Array_imp obj = new Array_imp(); // Setting root node obj.Root(\"A\"); // obj.set_Left(\"B\", 0); obj.set_Right(\"C\", 0); obj.set_Left(\"D\", 1); obj.set_Right(\"E\", 1); obj.set_Left(\"F\", 2); obj.print_Tree(); }} // Class 2// Helper classclass Array_imp { // Member variables of this class static int root = 0; static String[] str = new String[10]; // Method 1 // Creating root node public void Root(String key) { str[0] = key; } // Method 2 // Creating left son of root public void set_Left(String key, int root) { int t = (root * 2) + 1; if (str[root] == null) { System.out.printf( \"Can't set child at %d, no parent found\\n\", t); } else { str[t] = key; } } // Method 3 // Creating right son of root public void set_Right(String key, int root) { int t = (root * 2) + 2; if (str[root] == null) { System.out.printf( \"Can't set child at %d, no parent found\\n\", t); } else { str[t] = key; } } // Method 4 // To print our tree public void print_Tree() { // Iterating using for loop for (int i = 0; i < 10; i++) { if (str[i] != null) System.out.print(str[i]); else System.out.print(\"-\"); } }}",
"e": 40061,
"s": 38248,
"text": null
},
{
"code": "// C# implementation of tree using array// numbering starting from 0 to n-1.using System; public class Tree { public static void Main(String[] args) { Array_imp obj = new Array_imp(); obj.Root(\"A\"); // obj.set_Left(\"B\", 0); obj.set_Right(\"C\", 0); obj.set_Left(\"D\", 1); obj.set_Right(\"E\", 1); obj.set_Left(\"F\", 2); obj.print_Tree(); }} class Array_imp { static int root = 0; static String[] str = new String[10]; /*create root*/ public void Root(String key) { str[0] = key; } /*create left son of root*/ public void set_Left(String key, int root) { int t = (root * 2) + 1; if (str[root] == null) { Console.Write(\"Can't set child at {0}, no parent found\\n\", t); } else { str[t] = key; } } /*create right son of root*/ public void set_Right(String key, int root) { int t = (root * 2) + 2; if (str[root] == null) { Console.Write(\"Can't set child at {0}, no parent found\\n\", t); } else { str[t] = key; } } public void print_Tree() { for (int i = 0; i < 10; i++) { if (str[i] != null) Console.Write(str[i]); else Console.Write(\"-\"); } }} // This code contributed by Rajput-Ji",
"e": 41440,
"s": 40061,
"text": null
},
{
"code": "# Python3 implementation of tree using array# numbering starting from 0 to n-1.tree = [None] * 10 def root(key): if tree[0] != None: print(\"Tree already had root\") else: tree[0] = key def set_left(key, parent): if tree[parent] == None: print(\"Can't set child at\", (parent * 2) + 1, \", no parent found\") else: tree[(parent * 2) + 1] = key def set_right(key, parent): if tree[parent] == None: print(\"Can't set child at\", (parent * 2) + 2, \", no parent found\") else: tree[(parent * 2) + 2] = key def print_tree(): for i in range(10): if tree[i] != None: print(tree[i], end=\"\") else: print(\"-\", end=\"\") print() # Driver Coderoot('A')set_right('C', 0)set_left('D', 1)set_right('E', 1)set_right('F', 2)print_tree() # This code is contributed by Gaurav Kumar Tailor",
"e": 42306,
"s": 41440,
"text": null
},
{
"code": null,
"e": 42393,
"s": 42306,
"text": "Can't set child at3 , no parent found\nCan't set child at4 , no parent found\nA-C---F---"
},
{
"code": null,
"e": 42407,
"s": 42393,
"text": "Sachin Jain 1"
},
{
"code": null,
"e": 42419,
"s": 42407,
"text": "diegoolalde"
},
{
"code": null,
"e": 42429,
"s": 42419,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42449,
"s": 42429,
"text": "gaurav_kumar_raghav"
},
{
"code": null,
"e": 42466,
"s": 42449,
"text": "gauravtailorthoi"
},
{
"code": null,
"e": 42482,
"s": 42466,
"text": "hitesh sharma 3"
},
{
"code": null,
"e": 42492,
"s": 42482,
"text": "msr20comp"
},
{
"code": null,
"e": 42505,
"s": 42492,
"text": "simmytarika5"
},
{
"code": null,
"e": 42523,
"s": 42505,
"text": "germanshephered48"
},
{
"code": null,
"e": 42535,
"s": 42523,
"text": "Binary Tree"
},
{
"code": null,
"e": 42555,
"s": 42535,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 42562,
"s": 42555,
"text": "Arrays"
},
{
"code": null,
"e": 42567,
"s": 42562,
"text": "Java"
},
{
"code": null,
"e": 42586,
"s": 42567,
"text": "Technical Scripter"
},
{
"code": null,
"e": 42591,
"s": 42586,
"text": "Tree"
},
{
"code": null,
"e": 42598,
"s": 42591,
"text": "Arrays"
},
{
"code": null,
"e": 42603,
"s": 42598,
"text": "Java"
},
{
"code": null,
"e": 42608,
"s": 42603,
"text": "Tree"
},
{
"code": null,
"e": 42706,
"s": 42608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42721,
"s": 42706,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42737,
"s": 42721,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 42785,
"s": 42737,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 42812,
"s": 42785,
"text": "Program for array rotation"
},
{
"code": null,
"e": 42844,
"s": 42812,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 42859,
"s": 42844,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42903,
"s": 42859,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 42925,
"s": 42903,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 42961,
"s": 42925,
"text": "Arrays.sort() in Java with examples"
}
]
|
GWT - Event Handling | GWT provides a event handler model similar to Java AWT or SWING User Interface frameworks.
A listener interface defines one or more methods that the widget calls to announce an event. GWT provides a list of interfaces corresponding to various possible events.
A listener interface defines one or more methods that the widget calls to announce an event. GWT provides a list of interfaces corresponding to various possible events.
A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events.
A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events.
For example, the Button class publishes click events so you will have to write a class to implement ClickHandler to handle click event.
All GWT event handlers have been extended from EventHandler interface and each handler has only a single method with a single argument. This argument is always an object of associated event type. Each event object have a number of methods to manipulate the passed event object. For example for click event you will have to write your handler as follows −
/**
* create a custom click handler which will call
* onClick method when button is clicked.
*/
public class MyClickHandler implements ClickHandler {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello World!");
}
}
Now any class wishing to receive click events will call addClickHandler() to register an event handler as follows −
/**
* create button and attach click handler
*/
Button button = new Button("Click Me!");
button.addClickHandler(new MyClickHandler());
Each widget supporting an event type will have a method of the form HandlerRegistration addFooHandler(FooEvent) where Foo is the actual event like Click, Error, KeyPress etc.
Following is the list of important GWT event handlers and associated events and handler registration methods −
void on Before Selection (Before Selection Event<I> event);
Called when BeforeSelectionEvent is fired.
void on Blur(Blur Event event);
Called when Blur Event is fired.
void on Change(ChangeEvent event);
Called when a change event is fired.
void on Click(ClickEvent event);
Called when a native click event is fired.
void on Close(CloseEvent<T> event);
Called when CloseEvent is fired.
void on Context Menu(Context Menu Event event);
Called when a native context menu event is fired.
void on Double Click(Double Click Event event);
Called when a Double Click Event is fired.
void on Error(Error Event event);
Called when Error Event is fired.
void on Focus(Focus Event event);
Called when Focus Event is fired.
void on Submit Complete(Form Panel.Submit Complete Event event);
Fired when a form has been submitted successfully.
void on Submit(Form Panel.Submit Event event);
Fired when the form is submitted.
void on Key Down(Key Down Event event);
Called when KeyDownEvent is fired.
void on KeyPress(KeyPressEvent event);
Called when KeyPressEvent is fired.
void on KeyUp(KeyUpEvent event);
Called when KeyUpEvent is fired.
void on Load(LoadEvent event);
Called when LoadEvent is fired.
void on MouseDown(MouseDownEvent event);
Called when MouseDown is fired.
void on MouseMove(MouseMoveEvent event);
Called when MouseMoveEvent is fired.
void on MouseOut(MouseOutEvent event);
Called when MouseOutEvent is fired.
void on MouseOver(MouseOverEvent event);
Called when MouseOverEvent is fired.
void on MouseUp(MouseUpEvent event);
Called when MouseUpEvent is fired.
void on MouseWheel(MouseWheelEvent event);
Called when MouseWheelEvent is fired.
void on Resize(ResizeEvent event);
Fired when the widget is resized.
void on Scroll(ScrollEvent event);
Called when ScrollEvent is fired.
void on Selection(SelectionEvent<I> event);
Called when SelectionEvent is fired.
void on ValueChange(ValueChangeEvent<I> event);
Called when ValueChangeEvent is fired.
void on WindowClosing(Window.ClosingEvent event);
Fired just before the browser window closes or navigates to a different site.
void on WindowScroll(Window.ScrollEvent event);
Fired when the browser window is scrolled.
As mentioned earlier, each handler has a single method with a single argument which holds the event object, for example void onClick(ClickEvent event) or void onKeyDown(KeyDownEvent event). The event objects like ClickEvent and KeyDownEvent has few common methods which are listed below −
protected void dispatch(ClickHandler handler) This method Should only be called by HandlerManager
DomEvent.Type <FooHandler> getAssociatedType() This method returns the type used to register Foo event.
static DomEvent.Type<FooHandler> getType() This method gets the event type associated with Foo events.
public java.lang.Object getSource() This method returns the source that last fired this event.
protected final boolean isLive() This method returns whether the event is live.
protected void kill() This method kills the event
This example will take you through simple steps to show usage of a Click Event and KeyDown Event handling in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
Following is the content of the modified HTML host file war/HelloWorld.html.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>Event Handling Demonstration</h1>
<div id = "gwtContainer"></div>
</body>
</html>
Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Event Handling in GWT.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
/**
* create textbox and attach key down handler
*/
TextBox textBox = new TextBox();
textBox.addKeyDownHandler(new MyKeyDownHandler());
/*
* create button and attach click handler
*/
Button button = new Button("Click Me!");
button.addClickHandler(new MyClickHandler());
VerticalPanel panel = new VerticalPanel();
panel.setSpacing(10);
panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
panel.setSize("300", "100");
panel.add(textBox);
panel.add(button);
DecoratorPanel decoratorPanel = new DecoratorPanel();
decoratorPanel.add(panel);
RootPanel.get("gwtContainer").add(decoratorPanel);
}
/**
* create a custom click handler which will call
* onClick method when button is clicked.
*/
private class MyClickHandler implements ClickHandler {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello World!");
}
}
/**
* create a custom key down handler which will call
* onKeyDown method when a key is down in textbox.
*/
private class MyKeyDownHandler implements KeyDownHandler {
@Override
public void onKeyDown(KeyDownEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
Window.alert(((TextBox)event.getSource()).getValue());
}
}
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2114,
"s": 2023,
"text": "GWT provides a event handler model similar to Java AWT or SWING User Interface frameworks."
},
{
"code": null,
"e": 2283,
"s": 2114,
"text": "A listener interface defines one or more methods that the widget calls to announce an event. GWT provides a list of interfaces corresponding to various possible events."
},
{
"code": null,
"e": 2452,
"s": 2283,
"text": "A listener interface defines one or more methods that the widget calls to announce an event. GWT provides a list of interfaces corresponding to various possible events."
},
{
"code": null,
"e": 2636,
"s": 2452,
"text": "A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events."
},
{
"code": null,
"e": 2820,
"s": 2636,
"text": "A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events."
},
{
"code": null,
"e": 2956,
"s": 2820,
"text": "For example, the Button class publishes click events so you will have to write a class to implement ClickHandler to handle click event."
},
{
"code": null,
"e": 3312,
"s": 2956,
"text": "All GWT event handlers have been extended from EventHandler interface and each handler has only a single method with a single argument. This argument is always an object of associated event type. Each event object have a number of methods to manipulate the passed event object. For example for click event you will have to write your handler as follows −"
},
{
"code": null,
"e": 3565,
"s": 3312,
"text": "/**\n * create a custom click handler which will call \n * onClick method when button is clicked.\n */\npublic class MyClickHandler implements ClickHandler {\n @Override\n public void onClick(ClickEvent event) {\n Window.alert(\"Hello World!\");\n }\n}"
},
{
"code": null,
"e": 3682,
"s": 3565,
"text": "Now any class wishing to receive click events will call addClickHandler() to register an event handler as follows −"
},
{
"code": null,
"e": 3819,
"s": 3682,
"text": "/**\n * create button and attach click handler\n */\nButton button = new Button(\"Click Me!\");\nbutton.addClickHandler(new MyClickHandler());"
},
{
"code": null,
"e": 3994,
"s": 3819,
"text": "Each widget supporting an event type will have a method of the form HandlerRegistration addFooHandler(FooEvent) where Foo is the actual event like Click, Error, KeyPress etc."
},
{
"code": null,
"e": 4105,
"s": 3994,
"text": "Following is the list of important GWT event handlers and associated events and handler registration methods −"
},
{
"code": null,
"e": 4165,
"s": 4105,
"text": "void on Before Selection (Before Selection Event<I> event);"
},
{
"code": null,
"e": 4208,
"s": 4165,
"text": "Called when BeforeSelectionEvent is fired."
},
{
"code": null,
"e": 4240,
"s": 4208,
"text": "void on Blur(Blur Event event);"
},
{
"code": null,
"e": 4273,
"s": 4240,
"text": "Called when Blur Event is fired."
},
{
"code": null,
"e": 4308,
"s": 4273,
"text": "void on Change(ChangeEvent event);"
},
{
"code": null,
"e": 4345,
"s": 4308,
"text": "Called when a change event is fired."
},
{
"code": null,
"e": 4378,
"s": 4345,
"text": "void on Click(ClickEvent event);"
},
{
"code": null,
"e": 4421,
"s": 4378,
"text": "Called when a native click event is fired."
},
{
"code": null,
"e": 4457,
"s": 4421,
"text": "void on Close(CloseEvent<T> event);"
},
{
"code": null,
"e": 4490,
"s": 4457,
"text": "Called when CloseEvent is fired."
},
{
"code": null,
"e": 4538,
"s": 4490,
"text": "void on Context Menu(Context Menu Event event);"
},
{
"code": null,
"e": 4588,
"s": 4538,
"text": "Called when a native context menu event is fired."
},
{
"code": null,
"e": 4636,
"s": 4588,
"text": "void on Double Click(Double Click Event event);"
},
{
"code": null,
"e": 4679,
"s": 4636,
"text": "Called when a Double Click Event is fired."
},
{
"code": null,
"e": 4713,
"s": 4679,
"text": "void on Error(Error Event event);"
},
{
"code": null,
"e": 4747,
"s": 4713,
"text": "Called when Error Event is fired."
},
{
"code": null,
"e": 4781,
"s": 4747,
"text": "void on Focus(Focus Event event);"
},
{
"code": null,
"e": 4815,
"s": 4781,
"text": "Called when Focus Event is fired."
},
{
"code": null,
"e": 4880,
"s": 4815,
"text": "void on Submit Complete(Form Panel.Submit Complete Event event);"
},
{
"code": null,
"e": 4931,
"s": 4880,
"text": "Fired when a form has been submitted successfully."
},
{
"code": null,
"e": 4978,
"s": 4931,
"text": "void on Submit(Form Panel.Submit Event event);"
},
{
"code": null,
"e": 5012,
"s": 4978,
"text": "Fired when the form is submitted."
},
{
"code": null,
"e": 5052,
"s": 5012,
"text": "void on Key Down(Key Down Event event);"
},
{
"code": null,
"e": 5087,
"s": 5052,
"text": "Called when KeyDownEvent is fired."
},
{
"code": null,
"e": 5126,
"s": 5087,
"text": "void on KeyPress(KeyPressEvent event);"
},
{
"code": null,
"e": 5162,
"s": 5126,
"text": "Called when KeyPressEvent is fired."
},
{
"code": null,
"e": 5195,
"s": 5162,
"text": "void on KeyUp(KeyUpEvent event);"
},
{
"code": null,
"e": 5228,
"s": 5195,
"text": "Called when KeyUpEvent is fired."
},
{
"code": null,
"e": 5259,
"s": 5228,
"text": "void on Load(LoadEvent event);"
},
{
"code": null,
"e": 5291,
"s": 5259,
"text": "Called when LoadEvent is fired."
},
{
"code": null,
"e": 5332,
"s": 5291,
"text": "void on MouseDown(MouseDownEvent event);"
},
{
"code": null,
"e": 5364,
"s": 5332,
"text": "Called when MouseDown is fired."
},
{
"code": null,
"e": 5405,
"s": 5364,
"text": "void on MouseMove(MouseMoveEvent event);"
},
{
"code": null,
"e": 5442,
"s": 5405,
"text": "Called when MouseMoveEvent is fired."
},
{
"code": null,
"e": 5481,
"s": 5442,
"text": "void on MouseOut(MouseOutEvent event);"
},
{
"code": null,
"e": 5517,
"s": 5481,
"text": "Called when MouseOutEvent is fired."
},
{
"code": null,
"e": 5558,
"s": 5517,
"text": "void on MouseOver(MouseOverEvent event);"
},
{
"code": null,
"e": 5595,
"s": 5558,
"text": "Called when MouseOverEvent is fired."
},
{
"code": null,
"e": 5632,
"s": 5595,
"text": "void on MouseUp(MouseUpEvent event);"
},
{
"code": null,
"e": 5667,
"s": 5632,
"text": "Called when MouseUpEvent is fired."
},
{
"code": null,
"e": 5710,
"s": 5667,
"text": "void on MouseWheel(MouseWheelEvent event);"
},
{
"code": null,
"e": 5748,
"s": 5710,
"text": "Called when MouseWheelEvent is fired."
},
{
"code": null,
"e": 5783,
"s": 5748,
"text": "void on Resize(ResizeEvent event);"
},
{
"code": null,
"e": 5817,
"s": 5783,
"text": "Fired when the widget is resized."
},
{
"code": null,
"e": 5852,
"s": 5817,
"text": "void on Scroll(ScrollEvent event);"
},
{
"code": null,
"e": 5886,
"s": 5852,
"text": "Called when ScrollEvent is fired."
},
{
"code": null,
"e": 5930,
"s": 5886,
"text": "void on Selection(SelectionEvent<I> event);"
},
{
"code": null,
"e": 5967,
"s": 5930,
"text": "Called when SelectionEvent is fired."
},
{
"code": null,
"e": 6015,
"s": 5967,
"text": "void on ValueChange(ValueChangeEvent<I> event);"
},
{
"code": null,
"e": 6054,
"s": 6015,
"text": "Called when ValueChangeEvent is fired."
},
{
"code": null,
"e": 6104,
"s": 6054,
"text": "void on WindowClosing(Window.ClosingEvent event);"
},
{
"code": null,
"e": 6182,
"s": 6104,
"text": "Fired just before the browser window closes or navigates to a different site."
},
{
"code": null,
"e": 6230,
"s": 6182,
"text": "void on WindowScroll(Window.ScrollEvent event);"
},
{
"code": null,
"e": 6273,
"s": 6230,
"text": "Fired when the browser window is scrolled."
},
{
"code": null,
"e": 6562,
"s": 6273,
"text": "As mentioned earlier, each handler has a single method with a single argument which holds the event object, for example void onClick(ClickEvent event) or void onKeyDown(KeyDownEvent event). The event objects like ClickEvent and KeyDownEvent has few common methods which are listed below −"
},
{
"code": null,
"e": 6660,
"s": 6562,
"text": "protected void dispatch(ClickHandler handler) This method Should only be called by HandlerManager"
},
{
"code": null,
"e": 6764,
"s": 6660,
"text": "DomEvent.Type <FooHandler>\tgetAssociatedType() This method returns the type used to register Foo event."
},
{
"code": null,
"e": 6867,
"s": 6764,
"text": "static DomEvent.Type<FooHandler>\tgetType() This method gets the event type associated with Foo events."
},
{
"code": null,
"e": 6963,
"s": 6867,
"text": "public java.lang.Object getSource() This method returns the source that last fired this event."
},
{
"code": null,
"e": 7043,
"s": 6963,
"text": "protected final boolean isLive() This method returns whether the event is live."
},
{
"code": null,
"e": 7093,
"s": 7043,
"text": "protected void kill() This method kills the event"
},
{
"code": null,
"e": 7314,
"s": 7093,
"text": "This example will take you through simple steps to show usage of a Click Event and KeyDown Event handling in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −"
},
{
"code": null,
"e": 7416,
"s": 7314,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 8025,
"s": 7416,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 8103,
"s": 8025,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 8289,
"s": 8103,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}"
},
{
"code": null,
"e": 8366,
"s": 8289,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html."
},
{
"code": null,
"e": 8692,
"s": 8366,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Event Handling Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 8827,
"s": 8692,
"text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Event Handling in GWT."
},
{
"code": null,
"e": 11020,
"s": 8827,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.event.dom.client.KeyCodes;\nimport com.google.gwt.event.dom.client.KeyDownEvent;\nimport com.google.gwt.event.dom.client.KeyDownHandler;\nimport com.google.gwt.user.client.Window;\nimport com.google.gwt.user.client.ui.Button;\nimport com.google.gwt.user.client.ui.DecoratorPanel;\nimport com.google.gwt.user.client.ui.HasHorizontalAlignment;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.TextBox;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n /**\n * create textbox and attach key down handler\n */\n TextBox textBox = new TextBox(); \n textBox.addKeyDownHandler(new MyKeyDownHandler());\n\n /*\n * create button and attach click handler\n */\n Button button = new Button(\"Click Me!\");\n button.addClickHandler(new MyClickHandler());\n\n VerticalPanel panel = new VerticalPanel();\n panel.setSpacing(10);\n panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);\n panel.setSize(\"300\", \"100\");\n panel.add(textBox);\n panel.add(button);\n\n DecoratorPanel decoratorPanel = new DecoratorPanel();\n decoratorPanel.add(panel);\n RootPanel.get(\"gwtContainer\").add(decoratorPanel);\n }\n\n /** \n * create a custom click handler which will call \n * onClick method when button is clicked.\n */\n private class MyClickHandler implements ClickHandler {\n @Override\n public void onClick(ClickEvent event) {\n Window.alert(\"Hello World!\");\n }\n }\n\n /**\n * create a custom key down handler which will call \n * onKeyDown method when a key is down in textbox.\n */\n private class MyKeyDownHandler implements KeyDownHandler {\n @Override\n public void onKeyDown(KeyDownEvent event) {\n if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){\n Window.alert(((TextBox)event.getSource()).getValue());\n }\n }\n }\n}"
},
{
"code": null,
"e": 11254,
"s": 11020,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −"
},
{
"code": null,
"e": 11261,
"s": 11254,
"text": " Print"
},
{
"code": null,
"e": 11272,
"s": 11261,
"text": " Add Notes"
}
]
|
Building Surveillance System using USB Camera and Wireless-Connected Raspberry Pi | by Ahmed Gad | Towards Data Science | This tutorial discusses building a surveillance system using a USB camera plugged into Raspberry Pi (RPi) which is connected a PC using its wireless interface. PyGame is used for accessing the camera and capturing images which are stored inside the SD card of RPi. A background model is created for the scene to discover the changes from the default state. A simple circuit, connected to the GPIO pins, lights a led as an indication of such states.
The tutorial has the following steps:
Connecting RPi to a PC using the wireless interface.Connecting a USB camera to RPi.Capturing images using PyGame.Building the background model.Detecting changes to the background model.Building a simple circuit that lights a led when a change occurs.
Connecting RPi to a PC using the wireless interface.
Connecting a USB camera to RPi.
Capturing images using PyGame.
Building the background model.
Detecting changes to the background model.
Building a simple circuit that lights a led when a change occurs.
The tutorial assumes that the reader has a PC connected to a wireless network and RPi connected to a switch using the Ethernet interface. For doing such work, please read the tutorial titled ”Building an Image Classifier Running on Raspberry Pi” which is available at this link:
https://www.linkedin.com/pulse/building-image-classifier-running-raspberry-pi-ahmed-gad
You should be able to know the IP address of the devices using a software such as “Advanced IP Scanner” and familiar with establishing the SSH connection using the MobaXterm software. After that, then we can start discussing each of the above steps.
In a previous tutorial “Building an Image Classifier Running on Raspberry Pi”, we built a network with three devices connected which are RPi, a switch, and a PC. RPI was connected to the switch using the Ethernet interface but the PC is connected to the switch using the wireless interface. In this tutorial, we will modify such network by using the wireless interface of the RPi to connect to the switch. This makes the network completely connected wirelessly and avoids the restrictions of the wires.
The wireless interface of RPi needs configuration before being able to use it. For such reason, we will still use the connection established using the Ethernet interface for configuring the wireless interface. Using DHCP in the switch, the RPi Ethernet interface will be given an IPv4 address. Such an address can then be used for establishing a secure shell (SSH) connection. You can refer to the previous tutorial for more details about establishing the connection.
Inside the SSH session created using MobaXterm, we can start configuring the wireless interface using either terminal commands or using the GUI of the Raspbian OS. Both ways are simple.
Using terminal commands, we will start by scanning the available wireless networks to find their service set identifiers (SSIDs). This is done using the following command:
pi@raspberrypi:~ $ sudo iwlist wlan0 scan
The first few lines of the output of this command are given in the following figure. The SSID of the target wireless network is “TEData_864A”. Note that you do not have to use a switch for connecting the PC to the RPi. Using a smartphone, we can create an access point for connecting them.
After knowing the SSID of the target network, we can use it for configuring the wireless interface. Such a configuration exists inside a file which can be accessed using the following command:
pi@raspberrypi:~ $ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
The file will be opened inside the terminal. Using the down arrow, go back to the end of the file to write the network configuration. This is by writing the SSID and the password of the network as follows:
network={ssid=”TEData_864A”psk=”YOUR_NETWOK_PASSWORD”}
After that, press CTRL+X to exit the file followed by Y to save the changes. For my case, I configured 2 networks and thus the file content has two configured networks according to the next figure.
You might need to change the status of the wireless interface from up to down them up again to apply such configurations. This is done using these 2 commands:
pi@raspberry:~ $ sudo ifdown wlan0pi@raspberry:~ $ sudo ifup wlan0
To check whether the wireless interface is configured correctly, enter the “ifconfig” command to retrieve the configuration of the interface.
pi@raspberry:~ $ ifconfig
According to the output of this command, the wireless interface is given an IPv4 address of 192.168.1.8. This is how to configure the wireless connection using terminal commands.
We can do the same using the GUI of the OS which can be accessed using the startlxde terminal command. After the GUI opens, there will be an icon for the network connections located inside the right part of the OS bar. Clicking on it will open a menu of the available wireless networks according to the next figure. Clicking any of the items will open a window that allows you to enter the password. By entering the password for the network with SSID “TEData_864A” and entering the “ifconfig” command, the result will be identical to that shown in the previous figure.
At this point, we have both the PC and the RPi connected wirelessly to the switch. The current network is illustrated in the following figure. We can now remove the Ethernet connection and just use the wireless one between RPi and the switch.
RPi has its own camera module that can be used. Rather than buying this module, which might be costly to many, we can just use a USB camera which is might be available everywhere at less cost. The configuration of such a camera is very simple. Just connect the USB camera to one of the USB ports of the RPi. After doing that, we can check whether the camera works well or not by capturing images using the “fswebcam” package. At first, we need to install that package using the following command:
pi@raspberry:~ $ sudo apt-get install fswebcam
After that, we can use it to capture an image. A very basic way to do that is as follows:
pi@raspberry:~ $ sudo fswebcam test_image.jpg
This accesses the camera, captures an image, and saves it to the SD card in the current directory with the name “test_image.jpg”. The output after executing the command is given in the following figure.
Here is the captured image:
The “fswebcam” package is useful for quickly testing whether the camera is working well or not. After making sure it is functioning well, we can start building a Python script that accesses the camera to capture images continuously using the PyGame library. The following code uses PyGame for capturing a single image, opens a window for displaying that image, and finally save such image.
import pygame import pygame.camera # Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera. width = 320 height = 240 # Initializing PyGame and the camera. pygame.init() pygame.camera.init() # Specifying the camera to be used for capturing images. If there is a single camera, then it have the index 0. cam = pygame.camera.Camera("/dev/video0",(width,height)) # Preparing a resizable window of the specified size for displaying the captured images. window = pygame.display.set_mode((width,height),pygame.RESIZABLE) # Starting the camera for capturing images. cam.start() # Capturing an image. image = cam.get_image() # Stopping the camera. cam.stop() # Displaying the image on the window starting from the top-left corner. window.blit(image,(0,0)) # Refreshing the window. pygame.display.update() # Saving the captured image. pygame.image.save(window,'PyGame_image.jpg')
Assume that the above code is saved in a Python file named “im_cap.py”. To execute such code, we can issue the following command from the terminal:
pi@raspberry:~ $ python3 im_cam.py
Here is the window displayed after executing such file.
We can modify the previous code to capture more than one image. For example, we can use a for loop to capture a number of previously specified images. We can also use a while loop that is not limited to a number of images. Here is the modified code that captures 2,000 images using a for loop.
import pygameimport pygame.camera# Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera.width = 320height = 240# Initializing PyGame and the camera.pygame.init()pygame.camera.init()# Specifying the camera to be used for capturing images. If there is a single camera, then it has the index 0.cam = pygame.camera.Camera("/dev/video0", (width, height))# Preparing a resizable window of the specified size for displaying the captured images.window = pygame.display.set_mode((width, height), pygame.RESIZABLE)# Starting the camera for capturing images.cam.start()for im_num in range(0, 2000): print("Image : ", im_num) # Capturing an image. image = cam.get_image() # Displaying the image on the window starting from the top-left corner. window.blit(image, (0, 0)) # Refreshing the window. pygame.display.update() # Saving the captured image. pygame.image.save(window, './pygame_images/image_' + str(im_num) + '.jpg')# Stopping the camera.cam.stop()
Here are 8 captured images. Note that the camera position is changed a bit.
Up to this point, we successfully built a simple surveillance system in which a camera captures images which are saved in the SD card of RPi. We can extend that to automatically detect changes to the scene. This is done by building a background model for the scene. Any change to such a model will indicate a change. For example, if someone is passing through the scene will cause a change to the background.
The background model can be simply created by averaging multiple captured images to the scene background without any object in them. Because we are interested in the color information, the images will be converted into binary. Here is the Python code used to build the background model.
import skimage.ioimport osimport numpydir_files = os.listdir('./pygame_images/')bg_image = skimage.io.imread(fname=dir_files[0], as_grey=True)for k in range(1, len(dir_files)): fname = dir_files[k] im = skimage.io.imread(fname=fname, as_grey=True) bg_image = bg_image + imbg_image = bg_image/(len(dir_files))bg_image_bin = bg_image > 0.5skimage.io.imsave(fname='bg_model.jpg', arr=bg_image)skimage.io.imsave(fname='bg_model_bin.jpg', arr=bg_image_bin*255)
Here is the background model in both gray and binary after averaging 500 images.
After building the background model, we can test a new image to check if there is a change to the background or not. This is done simply by converting the new image into binary. Then the number of white pixels is compared in both images. If the number exceeds a given threshold, this indicates a change from the background. The threshold changes from scene to scene. Here is the code used for testing a new image.
bg_num_ones = numpy.sum(bg_image_bin)test = skimage.io.imread(fname="./pygame_images/image_800.jpg", as_grey=True)test_bin = test > 0.5test_num_ones = numpy.sum(test_bin)print("Num 1s in BG :", bg_num_ones)print("Num 1s in Test :", test_num_ones)if(abs(test_num_ones-bg_num_ones) < 5000): print("Change.")
Here is a test image in both color, gray, and binary in which there is a change from the background due to the appearance of an object (person) in the scene.
As an indication of a change to the background model, we can build a simple circuit in which a led lights when a change occurs. This circuit will be connected to the GPIO (General Purpose Input Output) bins of the RPi. The circuit needs the following components:
One breadboard.
One led.
One resistor (more than or equal to 100 ohms). I use a 178.8 ohms resistor.
Two male/male jumper wires.
Two male/female jumper wires.
It is recommended to test the circuit before connecting it to the GPIO pins. This is because if the resistor value was not selected properly, this might lead to not only burning the led but also damaging the GPIO pins. To do the test, we need a battery for supplying the breadboard by power. Here is the circuit after connecting all components correctly.
After that, we can remove the battery and connect the breadboard the GPIO pins of RPi. Based on the breadboard numbering of the GPIO pins, the ground is connected to bin number 20 and the high voltage is connected to the output bin number 22. The following figure illustrates the connections between the breadboard and the RPi. The RPi is also connected to both the charger and the USB camera.
The output GPIO bin is controlled using the Python script given below. Its default state is LOW meaning the led is turned off. When there is a change to the background, the state will be changed to HIGH meaning the led is turned on. The led remains on for 0.1 seconds then its state returns back to off. When another input image is different from the background, the led returns back to on for another 0.1 seconds.
import time import RPi.GPIO import skimage.io import numpy import os import pygame.camera import pygame #####GPIO##### # Initializing the GPIO pins. The numbering using is board. RPi.GPIO.setmode(RPi.GPIO.BOARD) # Configuring the GPIO bin number 22 to be an output bin. RPi.GPIO.setup(22, RPi.GPIO.OUT) #####PyGame##### # Initializing PyGame and the camera. pygame.init() pygame.camera.init() # Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera. width = 320 height = 240 # Preparing a resizable window of the specified size for displaying the captured images. window = pygame.display.set_mode((width, height), pygame.RESIZABLE) # Specifying the camera source and the image dimensions. cam = pygame.camera.Camera("/dev/video0",(width,height)) cam.start() #####Background Model##### # Reading the background model. bg_image = skimage.io.imread(fname='bg_model_bin.jpg', as_grey=True) bg_image_bin = bg_image > 0.5 bg_num_ones = numpy.sum(bg_image_bin) im_dir = '/home/pi/pygame_images/' for im_num in range(0, 2000): print("Image : ", im_num) im = cam.get_image() # Displaying the image on the window starting from the top-left corner. window.blit(im, (0, 0)) # Refreshing the window. pygame.display.update() pygame.image.save(window, im_dir+'image'+str(im_num)+'.jpg') im = pygame.surfarray.array3d(window) test_bin = im > 0.5 test_num_ones = numpy.sum(test_bin) # Checking if there is a change in the test image. if (abs(test_num_ones - bg_num_ones) < 5000): print("Change.") try: RPi.GPIO.output(22, RPi.GPIO.HIGH) time.sleep(0.1) RPi.GPIO.output(22, RPi.GPIO.LOW) except KeyboardInterrupt: # CTRL+C print("Keyboard Interrupt.") except: print("Error occurred.") # Stopping the camera. cam.stop() # cleanup all GPIO pins. print("Clean Up GPIO.") RPi.GPIO.cleanup()
The following figure is shown one input image which is different from the background image due to the existence of a person. As a result, the led will be turned on for 0.1 seconds.
The following video (https://youtu.be/WOUG-vjg3A4) shows the led state for multiple frames captured using the camera. The led is turned on when the input image is different from the background model according to the used threshold.
Ahmed Fawzy Gad, “Building an Image Classifier Running on Raspberry Pi”, September 2018, https://www.linkedin.com/pulse/building-image-classifier-running-raspberry-pi-ahmed-gad | [
{
"code": null,
"e": 620,
"s": 171,
"text": "This tutorial discusses building a surveillance system using a USB camera plugged into Raspberry Pi (RPi) which is connected a PC using its wireless interface. PyGame is used for accessing the camera and capturing images which are stored inside the SD card of RPi. A background model is created for the scene to discover the changes from the default state. A simple circuit, connected to the GPIO pins, lights a led as an indication of such states."
},
{
"code": null,
"e": 658,
"s": 620,
"text": "The tutorial has the following steps:"
},
{
"code": null,
"e": 909,
"s": 658,
"text": "Connecting RPi to a PC using the wireless interface.Connecting a USB camera to RPi.Capturing images using PyGame.Building the background model.Detecting changes to the background model.Building a simple circuit that lights a led when a change occurs."
},
{
"code": null,
"e": 962,
"s": 909,
"text": "Connecting RPi to a PC using the wireless interface."
},
{
"code": null,
"e": 994,
"s": 962,
"text": "Connecting a USB camera to RPi."
},
{
"code": null,
"e": 1025,
"s": 994,
"text": "Capturing images using PyGame."
},
{
"code": null,
"e": 1056,
"s": 1025,
"text": "Building the background model."
},
{
"code": null,
"e": 1099,
"s": 1056,
"text": "Detecting changes to the background model."
},
{
"code": null,
"e": 1165,
"s": 1099,
"text": "Building a simple circuit that lights a led when a change occurs."
},
{
"code": null,
"e": 1444,
"s": 1165,
"text": "The tutorial assumes that the reader has a PC connected to a wireless network and RPi connected to a switch using the Ethernet interface. For doing such work, please read the tutorial titled ”Building an Image Classifier Running on Raspberry Pi” which is available at this link:"
},
{
"code": null,
"e": 1532,
"s": 1444,
"text": "https://www.linkedin.com/pulse/building-image-classifier-running-raspberry-pi-ahmed-gad"
},
{
"code": null,
"e": 1782,
"s": 1532,
"text": "You should be able to know the IP address of the devices using a software such as “Advanced IP Scanner” and familiar with establishing the SSH connection using the MobaXterm software. After that, then we can start discussing each of the above steps."
},
{
"code": null,
"e": 2285,
"s": 1782,
"text": "In a previous tutorial “Building an Image Classifier Running on Raspberry Pi”, we built a network with three devices connected which are RPi, a switch, and a PC. RPI was connected to the switch using the Ethernet interface but the PC is connected to the switch using the wireless interface. In this tutorial, we will modify such network by using the wireless interface of the RPi to connect to the switch. This makes the network completely connected wirelessly and avoids the restrictions of the wires."
},
{
"code": null,
"e": 2753,
"s": 2285,
"text": "The wireless interface of RPi needs configuration before being able to use it. For such reason, we will still use the connection established using the Ethernet interface for configuring the wireless interface. Using DHCP in the switch, the RPi Ethernet interface will be given an IPv4 address. Such an address can then be used for establishing a secure shell (SSH) connection. You can refer to the previous tutorial for more details about establishing the connection."
},
{
"code": null,
"e": 2939,
"s": 2753,
"text": "Inside the SSH session created using MobaXterm, we can start configuring the wireless interface using either terminal commands or using the GUI of the Raspbian OS. Both ways are simple."
},
{
"code": null,
"e": 3111,
"s": 2939,
"text": "Using terminal commands, we will start by scanning the available wireless networks to find their service set identifiers (SSIDs). This is done using the following command:"
},
{
"code": null,
"e": 3153,
"s": 3111,
"text": "pi@raspberrypi:~ $ sudo iwlist wlan0 scan"
},
{
"code": null,
"e": 3443,
"s": 3153,
"text": "The first few lines of the output of this command are given in the following figure. The SSID of the target wireless network is “TEData_864A”. Note that you do not have to use a switch for connecting the PC to the RPi. Using a smartphone, we can create an access point for connecting them."
},
{
"code": null,
"e": 3636,
"s": 3443,
"text": "After knowing the SSID of the target network, we can use it for configuring the wireless interface. Such a configuration exists inside a file which can be accessed using the following command:"
},
{
"code": null,
"e": 3705,
"s": 3636,
"text": "pi@raspberrypi:~ $ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf"
},
{
"code": null,
"e": 3911,
"s": 3705,
"text": "The file will be opened inside the terminal. Using the down arrow, go back to the end of the file to write the network configuration. This is by writing the SSID and the password of the network as follows:"
},
{
"code": null,
"e": 3966,
"s": 3911,
"text": "network={ssid=”TEData_864A”psk=”YOUR_NETWOK_PASSWORD”}"
},
{
"code": null,
"e": 4164,
"s": 3966,
"text": "After that, press CTRL+X to exit the file followed by Y to save the changes. For my case, I configured 2 networks and thus the file content has two configured networks according to the next figure."
},
{
"code": null,
"e": 4323,
"s": 4164,
"text": "You might need to change the status of the wireless interface from up to down them up again to apply such configurations. This is done using these 2 commands:"
},
{
"code": null,
"e": 4390,
"s": 4323,
"text": "pi@raspberry:~ $ sudo ifdown wlan0pi@raspberry:~ $ sudo ifup wlan0"
},
{
"code": null,
"e": 4532,
"s": 4390,
"text": "To check whether the wireless interface is configured correctly, enter the “ifconfig” command to retrieve the configuration of the interface."
},
{
"code": null,
"e": 4558,
"s": 4532,
"text": "pi@raspberry:~ $ ifconfig"
},
{
"code": null,
"e": 4737,
"s": 4558,
"text": "According to the output of this command, the wireless interface is given an IPv4 address of 192.168.1.8. This is how to configure the wireless connection using terminal commands."
},
{
"code": null,
"e": 5306,
"s": 4737,
"text": "We can do the same using the GUI of the OS which can be accessed using the startlxde terminal command. After the GUI opens, there will be an icon for the network connections located inside the right part of the OS bar. Clicking on it will open a menu of the available wireless networks according to the next figure. Clicking any of the items will open a window that allows you to enter the password. By entering the password for the network with SSID “TEData_864A” and entering the “ifconfig” command, the result will be identical to that shown in the previous figure."
},
{
"code": null,
"e": 5549,
"s": 5306,
"text": "At this point, we have both the PC and the RPi connected wirelessly to the switch. The current network is illustrated in the following figure. We can now remove the Ethernet connection and just use the wireless one between RPi and the switch."
},
{
"code": null,
"e": 6046,
"s": 5549,
"text": "RPi has its own camera module that can be used. Rather than buying this module, which might be costly to many, we can just use a USB camera which is might be available everywhere at less cost. The configuration of such a camera is very simple. Just connect the USB camera to one of the USB ports of the RPi. After doing that, we can check whether the camera works well or not by capturing images using the “fswebcam” package. At first, we need to install that package using the following command:"
},
{
"code": null,
"e": 6093,
"s": 6046,
"text": "pi@raspberry:~ $ sudo apt-get install fswebcam"
},
{
"code": null,
"e": 6183,
"s": 6093,
"text": "After that, we can use it to capture an image. A very basic way to do that is as follows:"
},
{
"code": null,
"e": 6229,
"s": 6183,
"text": "pi@raspberry:~ $ sudo fswebcam test_image.jpg"
},
{
"code": null,
"e": 6432,
"s": 6229,
"text": "This accesses the camera, captures an image, and saves it to the SD card in the current directory with the name “test_image.jpg”. The output after executing the command is given in the following figure."
},
{
"code": null,
"e": 6460,
"s": 6432,
"text": "Here is the captured image:"
},
{
"code": null,
"e": 6850,
"s": 6460,
"text": "The “fswebcam” package is useful for quickly testing whether the camera is working well or not. After making sure it is functioning well, we can start building a Python script that accesses the camera to capture images continuously using the PyGame library. The following code uses PyGame for capturing a single image, opens a window for displaying that image, and finally save such image."
},
{
"code": null,
"e": 7786,
"s": 6850,
"text": "import pygame import pygame.camera # Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera. width = 320 height = 240 # Initializing PyGame and the camera. pygame.init() pygame.camera.init() # Specifying the camera to be used for capturing images. If there is a single camera, then it have the index 0. cam = pygame.camera.Camera(\"/dev/video0\",(width,height)) # Preparing a resizable window of the specified size for displaying the captured images. window = pygame.display.set_mode((width,height),pygame.RESIZABLE) # Starting the camera for capturing images. cam.start() # Capturing an image. image = cam.get_image() # Stopping the camera. cam.stop() # Displaying the image on the window starting from the top-left corner. window.blit(image,(0,0)) # Refreshing the window. pygame.display.update() # Saving the captured image. pygame.image.save(window,'PyGame_image.jpg')"
},
{
"code": null,
"e": 7934,
"s": 7786,
"text": "Assume that the above code is saved in a Python file named “im_cap.py”. To execute such code, we can issue the following command from the terminal:"
},
{
"code": null,
"e": 7969,
"s": 7934,
"text": "pi@raspberry:~ $ python3 im_cam.py"
},
{
"code": null,
"e": 8025,
"s": 7969,
"text": "Here is the window displayed after executing such file."
},
{
"code": null,
"e": 8319,
"s": 8025,
"text": "We can modify the previous code to capture more than one image. For example, we can use a for loop to capture a number of previously specified images. We can also use a while loop that is not limited to a number of images. Here is the modified code that captures 2,000 images using a for loop."
},
{
"code": null,
"e": 9347,
"s": 8319,
"text": "import pygameimport pygame.camera# Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera.width = 320height = 240# Initializing PyGame and the camera.pygame.init()pygame.camera.init()# Specifying the camera to be used for capturing images. If there is a single camera, then it has the index 0.cam = pygame.camera.Camera(\"/dev/video0\", (width, height))# Preparing a resizable window of the specified size for displaying the captured images.window = pygame.display.set_mode((width, height), pygame.RESIZABLE)# Starting the camera for capturing images.cam.start()for im_num in range(0, 2000): print(\"Image : \", im_num) # Capturing an image. image = cam.get_image() # Displaying the image on the window starting from the top-left corner. window.blit(image, (0, 0)) # Refreshing the window. pygame.display.update() # Saving the captured image. pygame.image.save(window, './pygame_images/image_' + str(im_num) + '.jpg')# Stopping the camera.cam.stop()"
},
{
"code": null,
"e": 9423,
"s": 9347,
"text": "Here are 8 captured images. Note that the camera position is changed a bit."
},
{
"code": null,
"e": 9832,
"s": 9423,
"text": "Up to this point, we successfully built a simple surveillance system in which a camera captures images which are saved in the SD card of RPi. We can extend that to automatically detect changes to the scene. This is done by building a background model for the scene. Any change to such a model will indicate a change. For example, if someone is passing through the scene will cause a change to the background."
},
{
"code": null,
"e": 10119,
"s": 9832,
"text": "The background model can be simply created by averaging multiple captured images to the scene background without any object in them. Because we are interested in the color information, the images will be converted into binary. Here is the Python code used to build the background model."
},
{
"code": null,
"e": 10584,
"s": 10119,
"text": "import skimage.ioimport osimport numpydir_files = os.listdir('./pygame_images/')bg_image = skimage.io.imread(fname=dir_files[0], as_grey=True)for k in range(1, len(dir_files)): fname = dir_files[k] im = skimage.io.imread(fname=fname, as_grey=True) bg_image = bg_image + imbg_image = bg_image/(len(dir_files))bg_image_bin = bg_image > 0.5skimage.io.imsave(fname='bg_model.jpg', arr=bg_image)skimage.io.imsave(fname='bg_model_bin.jpg', arr=bg_image_bin*255)"
},
{
"code": null,
"e": 10665,
"s": 10584,
"text": "Here is the background model in both gray and binary after averaging 500 images."
},
{
"code": null,
"e": 11079,
"s": 10665,
"text": "After building the background model, we can test a new image to check if there is a change to the background or not. This is done simply by converting the new image into binary. Then the number of white pixels is compared in both images. If the number exceeds a given threshold, this indicates a change from the background. The threshold changes from scene to scene. Here is the code used for testing a new image."
},
{
"code": null,
"e": 11415,
"s": 11079,
"text": "bg_num_ones = numpy.sum(bg_image_bin)test = skimage.io.imread(fname=\"./pygame_images/image_800.jpg\", as_grey=True)test_bin = test > 0.5test_num_ones = numpy.sum(test_bin)print(\"Num 1s in BG :\", bg_num_ones)print(\"Num 1s in Test :\", test_num_ones)if(abs(test_num_ones-bg_num_ones) < 5000): print(\"Change.\")"
},
{
"code": null,
"e": 11573,
"s": 11415,
"text": "Here is a test image in both color, gray, and binary in which there is a change from the background due to the appearance of an object (person) in the scene."
},
{
"code": null,
"e": 11836,
"s": 11573,
"text": "As an indication of a change to the background model, we can build a simple circuit in which a led lights when a change occurs. This circuit will be connected to the GPIO (General Purpose Input Output) bins of the RPi. The circuit needs the following components:"
},
{
"code": null,
"e": 11852,
"s": 11836,
"text": "One breadboard."
},
{
"code": null,
"e": 11861,
"s": 11852,
"text": "One led."
},
{
"code": null,
"e": 11937,
"s": 11861,
"text": "One resistor (more than or equal to 100 ohms). I use a 178.8 ohms resistor."
},
{
"code": null,
"e": 11965,
"s": 11937,
"text": "Two male/male jumper wires."
},
{
"code": null,
"e": 11995,
"s": 11965,
"text": "Two male/female jumper wires."
},
{
"code": null,
"e": 12350,
"s": 11995,
"text": "It is recommended to test the circuit before connecting it to the GPIO pins. This is because if the resistor value was not selected properly, this might lead to not only burning the led but also damaging the GPIO pins. To do the test, we need a battery for supplying the breadboard by power. Here is the circuit after connecting all components correctly."
},
{
"code": null,
"e": 12744,
"s": 12350,
"text": "After that, we can remove the battery and connect the breadboard the GPIO pins of RPi. Based on the breadboard numbering of the GPIO pins, the ground is connected to bin number 20 and the high voltage is connected to the output bin number 22. The following figure illustrates the connections between the breadboard and the RPi. The RPi is also connected to both the charger and the USB camera."
},
{
"code": null,
"e": 13159,
"s": 12744,
"text": "The output GPIO bin is controlled using the Python script given below. Its default state is LOW meaning the led is turned off. When there is a change to the background, the state will be changed to HIGH meaning the led is turned on. The led remains on for 0.1 seconds then its state returns back to off. When another input image is different from the background, the led returns back to on for another 0.1 seconds."
},
{
"code": null,
"e": 15142,
"s": 13159,
"text": "import time import RPi.GPIO import skimage.io import numpy import os import pygame.camera import pygame #####GPIO##### # Initializing the GPIO pins. The numbering using is board. RPi.GPIO.setmode(RPi.GPIO.BOARD) # Configuring the GPIO bin number 22 to be an output bin. RPi.GPIO.setup(22, RPi.GPIO.OUT) #####PyGame##### # Initializing PyGame and the camera. pygame.init() pygame.camera.init() # Captured image dimensions. It should be less than or equal to the maximum dimensions acceptable by the camera. width = 320 height = 240 # Preparing a resizable window of the specified size for displaying the captured images. window = pygame.display.set_mode((width, height), pygame.RESIZABLE) # Specifying the camera source and the image dimensions. cam = pygame.camera.Camera(\"/dev/video0\",(width,height)) cam.start() #####Background Model##### # Reading the background model. bg_image = skimage.io.imread(fname='bg_model_bin.jpg', as_grey=True) bg_image_bin = bg_image > 0.5 bg_num_ones = numpy.sum(bg_image_bin) im_dir = '/home/pi/pygame_images/' for im_num in range(0, 2000): print(\"Image : \", im_num) im = cam.get_image() # Displaying the image on the window starting from the top-left corner. window.blit(im, (0, 0)) # Refreshing the window. pygame.display.update() pygame.image.save(window, im_dir+'image'+str(im_num)+'.jpg') im = pygame.surfarray.array3d(window) test_bin = im > 0.5 test_num_ones = numpy.sum(test_bin) # Checking if there is a change in the test image. if (abs(test_num_ones - bg_num_ones) < 5000): print(\"Change.\") try: RPi.GPIO.output(22, RPi.GPIO.HIGH) time.sleep(0.1) RPi.GPIO.output(22, RPi.GPIO.LOW) except KeyboardInterrupt: # CTRL+C print(\"Keyboard Interrupt.\") except: print(\"Error occurred.\") # Stopping the camera. cam.stop() # cleanup all GPIO pins. print(\"Clean Up GPIO.\") RPi.GPIO.cleanup()"
},
{
"code": null,
"e": 15323,
"s": 15142,
"text": "The following figure is shown one input image which is different from the background image due to the existence of a person. As a result, the led will be turned on for 0.1 seconds."
},
{
"code": null,
"e": 15555,
"s": 15323,
"text": "The following video (https://youtu.be/WOUG-vjg3A4) shows the led state for multiple frames captured using the camera. The led is turned on when the input image is different from the background model according to the used threshold."
}
]
|
How to Remove Spaces from String in Python | Python Regex | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to remove spaces from String in Python.
We have different solutions to fulfil this requirement in python. Let’s see one by one.
Python rstrip() function is used to remove the spaces at the right side of a string.
str = ' hello python string '
str = str.rstrip()
print(str)
Output:
hello python string
Python lstrip() function is used to remove the spaces at the left side of a string.
str = ' hello python string '
str = str.lstrip()
print(str)
Output:
hello python string
Python strip() function is used to remove the spaces at both sides of a string.
str = ' hello python string '
str = str.strip()
print(str)
Output:
hello python string
replace() function used to replace all the matching contents with the given content. Here I am going to replace all the white spaces with empty so that I can remove all white areas from the string.
str = ' hello python string '
str= sentence.replace(" ", "")
print(str)
Output:
hellopythonstring
join() function is used to join the array of strings.
str = ' hello python string '
str = " ".join(str.split())
print(str)
Output:
hello python string
import re
# Reg Expression
# Removing Begining of a String
str = ' hello python '
str = re.sub(r"^\s+", "", str, flags=re.UNICODE)
print("removed spaces at left side :",str)
# Ending of a string
str = ' hello python '
str = re.sub(r"\s+$", "", str, flags=re.UNICODE)
print("removed spaces at right side :",str)
# Removing Begining and Ending
str = ' hello python '
str = re.sub("^\s+|\s+$", "", str, flags=re.UNICODE)
print("removed spaces at both sides :",str)
# Removing all spaces
str = ' hello python '
pattern = re.compile(r'\s+')
str = re.sub(pattern, '', str)
print(str)
Output:
removed spaces at left side : hello python
removed spaces at right side : hello python
removed spaces at both sides : hello python
removed all spaces: hellopython
Done!
Python Regular Exp guide
Python How to read string input from the keyboard
Happy Learning 🙂
Python How to read input from keyboard
Python Set Data Structure in Depth
Python raw_input read input from keyboard
Python TypeCasting for Different Types
Python List Data Structure In Depth
JQuery Remove Elements Example
Python – How to remove key from dictionary ?
Python – How to remove duplicate elements from List
Python – Print different vowels present in a String
Python String to int Conversion Example
PHP Comments , White Spaces and Case Sensitivity
How to merge two lists in Python
How to Read CSV File in Python
How to get the size of a Directory in Python ?
Python – Find the biggest of 2 given numbers
Python How to read input from keyboard
Python Set Data Structure in Depth
Python raw_input read input from keyboard
Python TypeCasting for Different Types
Python List Data Structure In Depth
JQuery Remove Elements Example
Python – How to remove key from dictionary ?
Python – How to remove duplicate elements from List
Python – Print different vowels present in a String
Python String to int Conversion Example
PHP Comments , White Spaces and Case Sensitivity
How to merge two lists in Python
How to Read CSV File in Python
How to get the size of a Directory in Python ?
Python – Find the biggest of 2 given numbers
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 472,
"s": 398,
"text": "In this tutorial, we will see how to remove spaces from String in Python."
},
{
"code": null,
"e": 560,
"s": 472,
"text": "We have different solutions to fulfil this requirement in python. Let’s see one by one."
},
{
"code": null,
"e": 645,
"s": 560,
"text": "Python rstrip() function is used to remove the spaces at the right side of a string."
},
{
"code": null,
"e": 710,
"s": 645,
"text": "str = ' hello python string '\nstr = str.rstrip()\nprint(str)\n"
},
{
"code": null,
"e": 718,
"s": 710,
"text": "Output:"
},
{
"code": null,
"e": 739,
"s": 718,
"text": "hello python string"
},
{
"code": null,
"e": 823,
"s": 739,
"text": "Python lstrip() function is used to remove the spaces at the left side of a string."
},
{
"code": null,
"e": 889,
"s": 823,
"text": "str = ' hello python string '\nstr = str.lstrip()\nprint(str)"
},
{
"code": null,
"e": 897,
"s": 889,
"text": "Output:"
},
{
"code": null,
"e": 917,
"s": 897,
"text": "hello python string"
},
{
"code": null,
"e": 997,
"s": 917,
"text": "Python strip() function is used to remove the spaces at both sides of a string."
},
{
"code": null,
"e": 1064,
"s": 997,
"text": "str = ' hello python string '\nstr = str.strip()\nprint(str)"
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Output:"
},
{
"code": null,
"e": 1092,
"s": 1072,
"text": "hello python string"
},
{
"code": null,
"e": 1290,
"s": 1092,
"text": "replace() function used to replace all the matching contents with the given content. Here I am going to replace all the white spaces with empty so that I can remove all white areas from the string."
},
{
"code": null,
"e": 1366,
"s": 1290,
"text": "str = ' hello python string '\nstr= sentence.replace(\" \", \"\")\nprint(str)"
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1392,
"s": 1374,
"text": "hellopythonstring"
},
{
"code": null,
"e": 1446,
"s": 1392,
"text": "join() function is used to join the array of strings."
},
{
"code": null,
"e": 1519,
"s": 1446,
"text": "str = ' hello python string '\nstr = \" \".join(str.split())\nprint(str)"
},
{
"code": null,
"e": 1527,
"s": 1519,
"text": "Output:"
},
{
"code": null,
"e": 1547,
"s": 1527,
"text": "hello python string"
},
{
"code": null,
"e": 2150,
"s": 1547,
"text": "import re\n\n# Reg Expression\n# Removing Begining of a String\nstr = ' hello python '\nstr = re.sub(r\"^\\s+\", \"\", str, flags=re.UNICODE)\nprint(\"removed spaces at left side :\",str)\n\n# Ending of a string\nstr = ' hello python '\nstr = re.sub(r\"\\s+$\", \"\", str, flags=re.UNICODE)\nprint(\"removed spaces at right side :\",str)\n\n# Removing Begining and Ending\nstr = ' hello python '\nstr = re.sub(\"^\\s+|\\s+$\", \"\", str, flags=re.UNICODE)\nprint(\"removed spaces at both sides :\",str)\n\n# Removing all spaces\nstr = ' hello python '\npattern = re.compile(r'\\s+')\nstr = re.sub(pattern, '', str)\nprint(str)"
},
{
"code": null,
"e": 2158,
"s": 2150,
"text": "Output:"
},
{
"code": null,
"e": 2331,
"s": 2158,
"text": "removed spaces at left side : hello python \nremoved spaces at right side : hello python\nremoved spaces at both sides : hello python\nremoved all spaces: hellopython"
},
{
"code": null,
"e": 2337,
"s": 2331,
"text": "Done!"
},
{
"code": null,
"e": 2362,
"s": 2337,
"text": "Python Regular Exp guide"
},
{
"code": null,
"e": 2412,
"s": 2362,
"text": "Python How to read string input from the keyboard"
},
{
"code": null,
"e": 2429,
"s": 2412,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3047,
"s": 2429,
"text": "\nPython How to read input from keyboard\nPython Set Data Structure in Depth\nPython raw_input read input from keyboard\nPython TypeCasting for Different Types\nPython List Data Structure In Depth\nJQuery Remove Elements Example\nPython – How to remove key from dictionary ?\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython String to int Conversion Example\nPHP Comments , White Spaces and Case Sensitivity\nHow to merge two lists in Python\nHow to Read CSV File in Python\nHow to get the size of a Directory in Python ?\nPython – Find the biggest of 2 given numbers\n"
},
{
"code": null,
"e": 3086,
"s": 3047,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 3121,
"s": 3086,
"text": "Python Set Data Structure in Depth"
},
{
"code": null,
"e": 3163,
"s": 3121,
"text": "Python raw_input read input from keyboard"
},
{
"code": null,
"e": 3202,
"s": 3163,
"text": "Python TypeCasting for Different Types"
},
{
"code": null,
"e": 3238,
"s": 3202,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 3269,
"s": 3238,
"text": "JQuery Remove Elements Example"
},
{
"code": null,
"e": 3314,
"s": 3269,
"text": "Python – How to remove key from dictionary ?"
},
{
"code": null,
"e": 3366,
"s": 3314,
"text": "Python – How to remove duplicate elements from List"
},
{
"code": null,
"e": 3418,
"s": 3366,
"text": "Python – Print different vowels present in a String"
},
{
"code": null,
"e": 3458,
"s": 3418,
"text": "Python String to int Conversion Example"
},
{
"code": null,
"e": 3507,
"s": 3458,
"text": "PHP Comments , White Spaces and Case Sensitivity"
},
{
"code": null,
"e": 3540,
"s": 3507,
"text": "How to merge two lists in Python"
},
{
"code": null,
"e": 3571,
"s": 3540,
"text": "How to Read CSV File in Python"
},
{
"code": null,
"e": 3618,
"s": 3571,
"text": "How to get the size of a Directory in Python ?"
},
{
"code": null,
"e": 3663,
"s": 3618,
"text": "Python – Find the biggest of 2 given numbers"
},
{
"code": null,
"e": 3669,
"s": 3667,
"text": "Δ"
},
{
"code": null,
"e": 3692,
"s": 3669,
"text": " Python – Introduction"
},
{
"code": null,
"e": 3711,
"s": 3692,
"text": " Python – Features"
},
{
"code": null,
"e": 3740,
"s": 3711,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 3767,
"s": 3740,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 3791,
"s": 3767,
"text": " Python – Number System"
},
{
"code": null,
"e": 3813,
"s": 3791,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 3833,
"s": 3813,
"text": " Python – Operators"
},
{
"code": null,
"e": 3860,
"s": 3833,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 3893,
"s": 3860,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 3912,
"s": 3893,
"text": " Python – Keywords"
},
{
"code": null,
"e": 3933,
"s": 3912,
"text": " Python – Data Types"
},
{
"code": null,
"e": 3962,
"s": 3933,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 3992,
"s": 3962,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 4015,
"s": 3992,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 4039,
"s": 4015,
"text": " Python – String to Int"
},
{
"code": null,
"e": 4072,
"s": 4039,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 4095,
"s": 4072,
"text": " Python – if statement"
},
{
"code": null,
"e": 4124,
"s": 4095,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 4150,
"s": 4124,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 4185,
"s": 4150,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 4205,
"s": 4185,
"text": " Python – raw_input"
},
{
"code": null,
"e": 4229,
"s": 4205,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 4258,
"s": 4229,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 4281,
"s": 4258,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 4311,
"s": 4281,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 4336,
"s": 4311,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 4366,
"s": 4336,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 4396,
"s": 4366,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 4419,
"s": 4396,
"text": " Python – Constructors"
},
{
"code": null,
"e": 4450,
"s": 4419,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 4472,
"s": 4450,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 4493,
"s": 4472,
"text": " Python – Decorators"
},
{
"code": null,
"e": 4529,
"s": 4493,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 4559,
"s": 4529,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 4593,
"s": 4559,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 4619,
"s": 4593,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 4657,
"s": 4619,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 4685,
"s": 4657,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 4709,
"s": 4685,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 4735,
"s": 4709,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 4767,
"s": 4735,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 4793,
"s": 4767,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 4821,
"s": 4793,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 4852,
"s": 4821,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 4883,
"s": 4852,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 4916,
"s": 4883,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 4951,
"s": 4916,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 4988,
"s": 4951,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 5026,
"s": 4988,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 5052,
"s": 5026,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 5077,
"s": 5052,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 5117,
"s": 5077,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 5152,
"s": 5117,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 5187,
"s": 5152,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 5216,
"s": 5187,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 5242,
"s": 5216,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 5268,
"s": 5242,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 5300,
"s": 5268,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 5328,
"s": 5300,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 5368,
"s": 5328,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 5402,
"s": 5368,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 5427,
"s": 5402,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 5448,
"s": 5427,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 5479,
"s": 5448,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 5516,
"s": 5479,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 5553,
"s": 5516,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 5575,
"s": 5553,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 5613,
"s": 5575,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 5636,
"s": 5613,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 5674,
"s": 5636,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 5705,
"s": 5674,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 5743,
"s": 5705,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 5783,
"s": 5743,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 5830,
"s": 5783,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 5862,
"s": 5830,
"text": " Howto – Sort dictionary by key"
}
]
|
Redeclaration of global variable in C - GeeksforGeeks | 28 May, 2017
Consider the below two programs:
// Program 1int main(){ int x; int x = 5; printf("%d", x); return 0; }
Output in C:
redeclaration of ‘x’ with no linkage
// Program 2int x;int x = 5; int main(){ printf("%d", x); return 0; }
Output in C:
5
In C, the first program fails in compilation, but second program works fine. In C++, both programs fail in compilation.
C allows a global variable to be declared again when first declaration doesn’t initialize the variable.
The below program fails in both C also as the global variable is initialized in first declaration itself.
int x = 5;int x = 10; int main(){ printf("%d", x); return 0;}
Output:
error: redefinition of ‘x’
This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Variable Declaration and Scope
cpp-storage-classes
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
Enumeration (or enum) in C
std::string class in C++
Exception Handling in C++ | [
{
"code": null,
"e": 24029,
"s": 24001,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 24062,
"s": 24029,
"text": "Consider the below two programs:"
},
{
"code": "// Program 1int main(){ int x; int x = 5; printf(\"%d\", x); return 0; }",
"e": 24141,
"s": 24062,
"text": null
},
{
"code": null,
"e": 24154,
"s": 24141,
"text": "Output in C:"
},
{
"code": null,
"e": 24191,
"s": 24154,
"text": "redeclaration of ‘x’ with no linkage"
},
{
"code": "// Program 2int x;int x = 5; int main(){ printf(\"%d\", x); return 0; }",
"e": 24266,
"s": 24191,
"text": null
},
{
"code": null,
"e": 24279,
"s": 24266,
"text": "Output in C:"
},
{
"code": null,
"e": 24281,
"s": 24279,
"text": "5"
},
{
"code": null,
"e": 24401,
"s": 24281,
"text": "In C, the first program fails in compilation, but second program works fine. In C++, both programs fail in compilation."
},
{
"code": null,
"e": 24505,
"s": 24401,
"text": "C allows a global variable to be declared again when first declaration doesn’t initialize the variable."
},
{
"code": null,
"e": 24611,
"s": 24505,
"text": "The below program fails in both C also as the global variable is initialized in first declaration itself."
},
{
"code": "int x = 5;int x = 10; int main(){ printf(\"%d\", x); return 0;}",
"e": 24678,
"s": 24611,
"text": null
},
{
"code": null,
"e": 24686,
"s": 24678,
"text": "Output:"
},
{
"code": null,
"e": 24714,
"s": 24686,
"text": " error: redefinition of ‘x’"
},
{
"code": null,
"e": 24879,
"s": 24714,
"text": "This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 24912,
"s": 24879,
"text": "C-Variable Declaration and Scope"
},
{
"code": null,
"e": 24932,
"s": 24912,
"text": "cpp-storage-classes"
},
{
"code": null,
"e": 24943,
"s": 24932,
"text": "C Language"
},
{
"code": null,
"e": 25041,
"s": 24943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25050,
"s": 25041,
"text": "Comments"
},
{
"code": null,
"e": 25063,
"s": 25050,
"text": "Old Comments"
},
{
"code": null,
"e": 25075,
"s": 25063,
"text": "fork() in C"
},
{
"code": null,
"e": 25107,
"s": 25075,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25124,
"s": 25107,
"text": "Substring in C++"
},
{
"code": null,
"e": 25146,
"s": 25124,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25193,
"s": 25146,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 25231,
"s": 25193,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25247,
"s": 25231,
"text": "Structures in C"
},
{
"code": null,
"e": 25274,
"s": 25247,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 25299,
"s": 25274,
"text": "std::string class in C++"
}
]
|
Java Examples - Retrieve Table Contents | How to retrieve contents of a table using JDBC connection?
Following example uses getString, getInt & executeQuery methods to fetch & display the contents of the table.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
} catch(SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
}
The above code sample will produce the following result. The result may vary.
id name job
1 alok trainee
2 ravi trainee
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2127,
"s": 2068,
"text": "How to retrieve contents of a table using JDBC connection?"
},
{
"code": null,
"e": 2237,
"s": 2127,
"text": "Following example uses getString, getInt & executeQuery methods to fetch & display the contents of the table."
},
{
"code": null,
"e": 3168,
"s": 2237,
"text": "import java.sql.*;\n\npublic class jdbcResultSet {\n public static void main(String[] args) {\n try {\n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n } catch(ClassNotFoundException e) {\n System.out.println(\"Class not found \"+ e);\n }\n try {\n Connection con = DriverManager.getConnection(\n \"jdbc:derby://localhost:1527/testDb\",\"username\", \"password\");\n \n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"SELECT * FROM employee\");\n System.out.println(\"id name job\");\n \n while (rs.next()) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n String job = rs.getString(\"job\");\n System.out.println(id+\" \"+name+\" \"+job);\n }\n } catch(SQLException e) {\n System.out.println(\"SQL exception occured\" + e);\n }\n }\n}"
},
{
"code": null,
"e": 3246,
"s": 3168,
"text": "The above code sample will produce the following result. The result may vary."
},
{
"code": null,
"e": 3300,
"s": 3246,
"text": "id name job\n1 alok trainee\n2 ravi trainee\n"
},
{
"code": null,
"e": 3307,
"s": 3300,
"text": " Print"
},
{
"code": null,
"e": 3318,
"s": 3307,
"text": " Add Notes"
}
]
|
Predicting the Price of the Beyond Meat Stock Using Random Forest in Python | by Sadrach Pierre, Ph.D. | Towards Data Science | In this post we will predict the price of the Beyond Meat stock using random forest. Beyond Meat is a producer of plant-based meat substitutes and was founded by Ethan Brown in Los Angeles in 2009.
First thing we can do is import the necessary libraries. We will be using the yahoo finance API, seaborn, matplotlib, pandas, numpy, and sklearn:
import yfinance as yfimport seaborn as snsimport numpy as npimport pandas as pd from sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt
If you don’t have the python wrapper for the yahoo finance API installed you can type the following in a command line:
pip install yfinance
We can pull the last five months of ‘BYND’ stock data from Yahoo finance and print the first five rows. We will pull data from May 5, 2019 to November 2, 2019:
data = yf.Ticker('BYND')df = data.history(period="max", start="2019-05-01", end="2019-11-02")print(df.head())
We can plot the open prices using seaborn. We also use matpltlib to modify the seaborn plot. In order to plot the time series we need to convert the date strings into datetime objects:
sns.set()df[‘timestamp’] = df.indexdf[‘timestamp’] = pd.to_datetime(df[‘timestamp’])sns.lineplot(df[‘timestamp’], df['Open'])plt.ylabel("Open Price")
Next thing we can do is calculate the daily returns using the open and close daily prices and plot the results:
df[‘returns’] = (df[‘Close’]-df[‘Open’])/df[‘Open’]sns.lineplot(df[‘timestamp’], df['returns'])plt.ylabel("Returns")
Next we define a variable that specifies how far out we want to predict. Let’s predict 3 days out. We also create a new prediction column which is the target variable shifted up by the 3 days. Here our target variable will be the closing price :
forecast_out = 3df[‘prediction’] = df[[‘Close’]].shift(-forecast_out)X = np.array(df['Close']).reshape(-1,1)X = X[:-forecast_out]y = np.array(df['prediction'])y = y[:-forecast_out]
Next we split our data for training and testing, define a random forest object and train our model:
reg = RandomForestRegressor(n_estimators = 300, max_depth =300, random_state = 42)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 7)reg.fit(X_train, y_train)print("Performance (R^2): ", reg.score(X_test, y_test))
Our model has R2 = 0.84, which isn’t too bad. Thank you for reading and happy machine learning! The code from this post is available on GitHub. | [
{
"code": null,
"e": 369,
"s": 171,
"text": "In this post we will predict the price of the Beyond Meat stock using random forest. Beyond Meat is a producer of plant-based meat substitutes and was founded by Ethan Brown in Los Angeles in 2009."
},
{
"code": null,
"e": 515,
"s": 369,
"text": "First thing we can do is import the necessary libraries. We will be using the yahoo finance API, seaborn, matplotlib, pandas, numpy, and sklearn:"
},
{
"code": null,
"e": 729,
"s": 515,
"text": "import yfinance as yfimport seaborn as snsimport numpy as npimport pandas as pd from sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 848,
"s": 729,
"text": "If you don’t have the python wrapper for the yahoo finance API installed you can type the following in a command line:"
},
{
"code": null,
"e": 869,
"s": 848,
"text": "pip install yfinance"
},
{
"code": null,
"e": 1029,
"s": 869,
"text": "We can pull the last five months of ‘BYND’ stock data from Yahoo finance and print the first five rows. We will pull data from May 5, 2019 to November 2, 2019:"
},
{
"code": null,
"e": 1140,
"s": 1029,
"text": "data = yf.Ticker('BYND')df = data.history(period=\"max\", start=\"2019-05-01\", end=\"2019-11-02\")print(df.head())"
},
{
"code": null,
"e": 1325,
"s": 1140,
"text": "We can plot the open prices using seaborn. We also use matpltlib to modify the seaborn plot. In order to plot the time series we need to convert the date strings into datetime objects:"
},
{
"code": null,
"e": 1475,
"s": 1325,
"text": "sns.set()df[‘timestamp’] = df.indexdf[‘timestamp’] = pd.to_datetime(df[‘timestamp’])sns.lineplot(df[‘timestamp’], df['Open'])plt.ylabel(\"Open Price\")"
},
{
"code": null,
"e": 1587,
"s": 1475,
"text": "Next thing we can do is calculate the daily returns using the open and close daily prices and plot the results:"
},
{
"code": null,
"e": 1704,
"s": 1587,
"text": "df[‘returns’] = (df[‘Close’]-df[‘Open’])/df[‘Open’]sns.lineplot(df[‘timestamp’], df['returns'])plt.ylabel(\"Returns\")"
},
{
"code": null,
"e": 1950,
"s": 1704,
"text": "Next we define a variable that specifies how far out we want to predict. Let’s predict 3 days out. We also create a new prediction column which is the target variable shifted up by the 3 days. Here our target variable will be the closing price :"
},
{
"code": null,
"e": 2131,
"s": 1950,
"text": "forecast_out = 3df[‘prediction’] = df[[‘Close’]].shift(-forecast_out)X = np.array(df['Close']).reshape(-1,1)X = X[:-forecast_out]y = np.array(df['prediction'])y = y[:-forecast_out]"
},
{
"code": null,
"e": 2231,
"s": 2131,
"text": "Next we split our data for training and testing, define a random forest object and train our model:"
},
{
"code": null,
"e": 2484,
"s": 2231,
"text": "reg = RandomForestRegressor(n_estimators = 300, max_depth =300, random_state = 42)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 7)reg.fit(X_train, y_train)print(\"Performance (R^2): \", reg.score(X_test, y_test))"
}
]
|
Python | Scipy integrate.quadrature() method - GeeksforGeeks | 23 Jan, 2020
With the help of scipy.integrate.quadrature() method, we can get the computation of definite integral using fixed tolerance gaussian quadrature by using scipy.integrate.quadrature() method.
Syntax : scipy.integrate.quadrature(func, a, b)
Return : Return gaussian quadrature approximation to integral.
Example #1 :In this example we can see that by using scipy.integrate.quadrature() method, we are able to get the gaussian quadrature approximation to integral function from limit a to b by using this method.
# import scipy.integrate.from scipy import integrate gfg = lambda x: x**8 + x**4 # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 1.8) print(geek)
Output :
25.81905715199999
Example #2 :
# import scipy.integrate.from scipy import integrate gfg = lambda x: x**2 + 2 * x + 4 # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 4.0) print(geek)
Output :
53.33333333333333
Python-scipy
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 ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python | [
{
"code": null,
"e": 24746,
"s": 24718,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 24936,
"s": 24746,
"text": "With the help of scipy.integrate.quadrature() method, we can get the computation of definite integral using fixed tolerance gaussian quadrature by using scipy.integrate.quadrature() method."
},
{
"code": null,
"e": 24984,
"s": 24936,
"text": "Syntax : scipy.integrate.quadrature(func, a, b)"
},
{
"code": null,
"e": 25047,
"s": 24984,
"text": "Return : Return gaussian quadrature approximation to integral."
},
{
"code": null,
"e": 25255,
"s": 25047,
"text": "Example #1 :In this example we can see that by using scipy.integrate.quadrature() method, we are able to get the gaussian quadrature approximation to integral function from limit a to b by using this method."
},
{
"code": "# import scipy.integrate.from scipy import integrate gfg = lambda x: x**8 + x**4 # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 1.8) print(geek)",
"e": 25437,
"s": 25255,
"text": null
},
{
"code": null,
"e": 25446,
"s": 25437,
"text": "Output :"
},
{
"code": null,
"e": 25464,
"s": 25446,
"text": "25.81905715199999"
},
{
"code": null,
"e": 25477,
"s": 25464,
"text": "Example #2 :"
},
{
"code": "# import scipy.integrate.from scipy import integrate gfg = lambda x: x**2 + 2 * x + 4 # using scipy.integrate.quadrature() methodgeek = integrate.quadrature(gfg, 0.0, 4.0) print(geek)",
"e": 25664,
"s": 25477,
"text": null
},
{
"code": null,
"e": 25673,
"s": 25664,
"text": "Output :"
},
{
"code": null,
"e": 25691,
"s": 25673,
"text": "53.33333333333333"
},
{
"code": null,
"e": 25704,
"s": 25691,
"text": "Python-scipy"
},
{
"code": null,
"e": 25711,
"s": 25704,
"text": "Python"
},
{
"code": null,
"e": 25809,
"s": 25711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25818,
"s": 25809,
"text": "Comments"
},
{
"code": null,
"e": 25831,
"s": 25818,
"text": "Old Comments"
},
{
"code": null,
"e": 25849,
"s": 25831,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25881,
"s": 25849,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25916,
"s": 25881,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25938,
"s": 25916,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25968,
"s": 25938,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26010,
"s": 25968,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26047,
"s": 26010,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26073,
"s": 26047,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26117,
"s": 26073,
"text": "Reading and Writing to text files in Python"
}
]
|
CNN-LSTM: Predicting Daily Hotel Cancellations | by Michael Grogan | Towards Data Science | An LSTM (long-short term memory network) is a type of recurrent neural network that allows for the accounting of sequential dependencies in a time series.
Given that correlations exist between observations in a given time series (a phenomenon known as autocorrelation), a standard neural network would treat all observations as independent, which is erroneous and would generate misleading results.
A convolutional neural network is one that applies a process known as convolution in determining the relationships between two functions. e.g. given two functions f and g, the convolution integal expresses how the shape of one function is modified by the other. Such networks are traditionally used for image classification, and do not account for sequential dependencies in the way that a recurrent neural network is able to do.
However, the main advantage of CNNs that make them suited to forecasting time series is that of dilated convolutions - or the ability to use filters to compute dilations between each cell. That is to say, the size of the space between each cell, which in turn allows the neural network to better understand the relationships between the different observations in the time series.
For this reason, LSTM and CNN layers are often combined when forecasting a time series. This allows for the LSTM layer to account for sequential dependencies in the time series, while the CNN layer further informs this process through the use of dilated convolutions.
With that being said, standalone CNNs are increasingly being used for time series forecasting, and the combination of several Conv1D layers can actually produce quite impressive results — rivalling that of a model which uses both CNN and LSTM layers.
How is this possible? Let’s find out!
The below example was designed using a CNN template from the Intro to TensorFlow for Deep Learning course from Udacity — this particular topic is found in Lesson 8: Time Series Forecasting by Aurélien Géron.
The below analysis is based on data from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets.
Imagine this scenario. A hotel is having difficulty in forecasting hotel booking cancellations on a day-to-day basis. This is leading to difficulty in forecasting revenues and also in the efficient allocation of hotel rooms.
The hotel would like to solve this problem by building a time series model that can forecast the fluctuations in daily hotel cancellations with reasonably high accuracy.
Here is a time series plot of the fluctuations in daily hotel cancellation bookings:
The neural network is structured as follows:
Here are the important model parameters that must be accounted for.
The kernel size is set to 3, meaning that each output is calculated based on the previous three time steps.
Here is a rough illustration:
Setting the correct kernel size is a matter of experimentation, as a low kernel size risks poor model performance, while a high kernel size risks overfitting.
As can be seen from the diagram, three input time steps are taken and used to generate a separate output.
In this instance, causal padding is used in order to ensure that the output sequence has the same length as the input sequence. In other words, this ensures that the network “pads” time steps from the left side of the series in order to ensure that future values on the right side of the series are not being used in generating the forecast — this will quite obviously lead to false results and we will end up overestimating the accuracy of our model.
The stride length is set to one, which means that the filter slides forward by one time step at a time when forecasting future values.
However, this could be set higher. For instance, setting the stride length to two would mean that the output sequence would be approximately half the length of the input sequence.
A long stride length would mean that the model might potentially discard valuable data in generating the forecast, but increasing the stride length can be useful when it comes to capturing longer-term trends and smoothing out noise in the series.
Here is the model configuration:
model = keras.models.Sequential([ keras.layers.Conv1D(filters=32, kernel_size=3, strides=1, padding="causal", activation="relu", input_shape=[None, 1]), keras.layers.LSTM(32, return_sequences=True), keras.layers.Dense(1), keras.layers.Lambda(lambda x: x * 200)])lr_schedule = keras.callbacks.LearningRateScheduler( lambda epoch: 1e-8 * 10**(epoch / 20))optimizer = keras.optimizers.SGD(lr=1e-8, momentum=0.9)model.compile(loss=keras.losses.Huber(), optimizer=optimizer, metrics=["mae"])
Firstly, let’s make forecasts using the above model on different window sizes.
It is important that the window size is large enough to account for the volatility across time steps.
Suppose we start with a window size of 5.
The training loss is as follows:
plt.semilogx(history.history["lr"], history.history["loss"])plt.axis([1e-8, 1e-4, 0, 30])
Here is a visual of the forecasts versus actual daily cancellation values:
rnn_forecast = model_forecast(model, series[:, np.newaxis], window_size)rnn_forecast = rnn_forecast[split_time - window_size:-1, -1, 0]plt.figure(figsize=(10, 6))plot_series(time_valid, x_valid)plot_series(time_valid, rnn_forecast)
The mean absolute error is calculated:
>>> keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()9.113908
With a mean of 19.89 across the validation set, the model accuracy is reasonable. However, we do see from the diagram above that the model falls short in terms of forecasting more extreme values.
What if the window size was increased to 30?
The mean absolute error decreases slightly:
>>> keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()7.377962
As mentioned, the stride length can be set higher if we wish to smooth out the forecast — with the caveat that such a forecast (the output sequence) will have less data points than that of the input sequence.
Unlike an LSTM, a CNN is not recurrent, which means that it does not retain memory of previous time series patterns. Instead, it can only train based on the data that is inputted by the model at a particular time step.
However, by stacking several Conv1D layers together, it is in fact possible for a convolutional neural network to effectively learn long-term dependencies in the time series.
This can be done using a WaveNet architecture. Essentially, this means that the model defines every layer as a 1D convolutional layer with a stride length of 1 and a kernel size of 2. The second convolutional layer uses a dilation rate of 2, which means that every second input timestep in the series is skipped. The third layer uses a dilation rate of 4, the fourth layer uses a dilation rate of 8, and so on.
The reason for this is that it allows the lower layers to learn short-term patterns in the time series, while the higher layers learn longer-term patterns.
The WaveNet model is defined as follows:
model = keras.models.Sequential()model.add(keras.layers.InputLayer(input_shape=[None, 1]))for dilation_rate in (1, 2, 4, 8, 16, 32): model.add( keras.layers.Conv1D(filters=32, kernel_size=2, strides=1, dilation_rate=dilation_rate, padding="causal", activation="relu") )model.add(keras.layers.Conv1D(filters=1, kernel_size=1))optimizer = keras.optimizers.Adam(lr=3e-4)model.compile(loss=keras.losses.Huber(), optimizer=optimizer, metrics=["mae"])model_checkpoint = keras.callbacks.ModelCheckpoint( "my_checkpoint.h6", save_best_only=True)early_stopping = keras.callbacks.EarlyStopping(patience=50)history = model.fit(train_set, epochs=500, validation_data=valid_set, callbacks=[early_stopping, model_checkpoint])
A window size of 64 is used in training the model. In this instance, we are using a larger window size than was used with the CNN-LSTM model, in order to ensure that the CNN model picks up longer-term dependencies.
Note that early stopping is used when training the neural network. The purpose of this is to ensure that the neural network halts training at the point where further training would result in overfitting. Determining this manually is quite an arbitrary process, so early stopping can greatly assist with this.
Let’s now generate forecasts using the standalone CNN model that we just built.
cnn_forecast = model_forecast(model, series[..., np.newaxis], window_size)cnn_forecast = cnn_forecast[split_time - window_size:-1, -1, 0]
Here is a plot of the forecasted vs. actual data.
The mean absolute error came in slightly higher at 7.49.
Note that for both models, the Huber loss was used as the loss function. This type of loss tends to be more robust to outliers, in that it is quadratic for smaller errors and linear for larger ones.
This type of loss is suitable for this scenario, as we can see that some outliers are present in the data. Using MSE (mean squared error) would overly inflate the forecast error yielded by the model, whereas MAE on its own would likely underestimate the size of the error by not taking such outliers into account. The use of a Huber loss function allows for a happy medium.
>>> keras.metrics.mean_absolute_error(x_valid, cnn_forecast).numpy()7.490844
Even with a slightly higher MAE, the CNN model has performed quite well in forecasting daily hotel cancellations, without having to be combined with an LSTM layer in order to learn long-term dependencies.
Of course, any model comes with limitations and the CNN is no exception.
Given that the model is making one-step predictions, this means that all observations up to time t in the relevant window is required to predict the value at time t+1. In this regard, a one-step CNN cannot be used to make long-range forecasts. While a multi-step CNN can be used for this purpose, it is debatable as to whether such a model will outperform an ARIMA model, for instance.
Additionally, a CNN (or any neural network model) requires a lot of data to train effectively. While many time series models come with pre-built parameters to model a range of time series, the CNN is learning entirely from scratch. In this regard, a researcher may spend a lot of time configuring a CNN model and end up with either lower accuracy relative to other standard time series models, or just a marginal gain in accuracy that does not justify the extra training time and data resources required.
In this particular example, the model was trained using 80% of the data as training data and then prediction accuracy was screened against 20% of the validation data. However, a true test of whether a model is effective involves comparing the prediction accuracy against test data, or data that is completely unseen by the model. This has not been done here, as this article has covered the model training component only.
However, neural networks are quite prone to overfitting — whereby the model performs well on data it has seen before — while performing poorly in predicting unseen data.
In this example, we have seen:
The similarities and differences between CNNs and LSTMs in forecasting time series
How dilated convolutions assist CNNs in forecasting time series
Modification of kernel size, padding and strides in forecasting a time series with CNN
Use of a WaveNet architecture to conduct a time series forecast using stand-alone CNN layers
In particular, we saw how a CNN can produce similarly strong results compared to a CNN-LSTM model through the use of dilation.
Many thanks for your time, and any questions, suggestions or feedback are greatly appreciated.
As mentioned, this topic is also covered in the Intro to TensorFlow for Deep Learning course from Udacity course — I highly recommend the chapter on Time Series Forecasting for further detail on this topic. Usual disclaimers apply — this is only a personal recommendation and I have no affiliation with the authors of this course in any way.
You can also find the full Jupyter Notebook that I used for running this example on hotel cancellations here.
The original Jupyter Notebook (Copyright 2018, The TensorFlow Authors) can also be found here.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. The findings and interpretations are those of the author and are not endorsed by or affiliated with any third-parties mentioned in this article. | [
{
"code": null,
"e": 327,
"s": 172,
"text": "An LSTM (long-short term memory network) is a type of recurrent neural network that allows for the accounting of sequential dependencies in a time series."
},
{
"code": null,
"e": 571,
"s": 327,
"text": "Given that correlations exist between observations in a given time series (a phenomenon known as autocorrelation), a standard neural network would treat all observations as independent, which is erroneous and would generate misleading results."
},
{
"code": null,
"e": 1001,
"s": 571,
"text": "A convolutional neural network is one that applies a process known as convolution in determining the relationships between two functions. e.g. given two functions f and g, the convolution integal expresses how the shape of one function is modified by the other. Such networks are traditionally used for image classification, and do not account for sequential dependencies in the way that a recurrent neural network is able to do."
},
{
"code": null,
"e": 1381,
"s": 1001,
"text": "However, the main advantage of CNNs that make them suited to forecasting time series is that of dilated convolutions - or the ability to use filters to compute dilations between each cell. That is to say, the size of the space between each cell, which in turn allows the neural network to better understand the relationships between the different observations in the time series."
},
{
"code": null,
"e": 1649,
"s": 1381,
"text": "For this reason, LSTM and CNN layers are often combined when forecasting a time series. This allows for the LSTM layer to account for sequential dependencies in the time series, while the CNN layer further informs this process through the use of dilated convolutions."
},
{
"code": null,
"e": 1900,
"s": 1649,
"text": "With that being said, standalone CNNs are increasingly being used for time series forecasting, and the combination of several Conv1D layers can actually produce quite impressive results — rivalling that of a model which uses both CNN and LSTM layers."
},
{
"code": null,
"e": 1938,
"s": 1900,
"text": "How is this possible? Let’s find out!"
},
{
"code": null,
"e": 2148,
"s": 1938,
"text": "The below example was designed using a CNN template from the Intro to TensorFlow for Deep Learning course from Udacity — this particular topic is found in Lesson 8: Time Series Forecasting by Aurélien Géron."
},
{
"code": null,
"e": 2255,
"s": 2148,
"text": "The below analysis is based on data from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets."
},
{
"code": null,
"e": 2480,
"s": 2255,
"text": "Imagine this scenario. A hotel is having difficulty in forecasting hotel booking cancellations on a day-to-day basis. This is leading to difficulty in forecasting revenues and also in the efficient allocation of hotel rooms."
},
{
"code": null,
"e": 2650,
"s": 2480,
"text": "The hotel would like to solve this problem by building a time series model that can forecast the fluctuations in daily hotel cancellations with reasonably high accuracy."
},
{
"code": null,
"e": 2735,
"s": 2650,
"text": "Here is a time series plot of the fluctuations in daily hotel cancellation bookings:"
},
{
"code": null,
"e": 2780,
"s": 2735,
"text": "The neural network is structured as follows:"
},
{
"code": null,
"e": 2848,
"s": 2780,
"text": "Here are the important model parameters that must be accounted for."
},
{
"code": null,
"e": 2956,
"s": 2848,
"text": "The kernel size is set to 3, meaning that each output is calculated based on the previous three time steps."
},
{
"code": null,
"e": 2986,
"s": 2956,
"text": "Here is a rough illustration:"
},
{
"code": null,
"e": 3145,
"s": 2986,
"text": "Setting the correct kernel size is a matter of experimentation, as a low kernel size risks poor model performance, while a high kernel size risks overfitting."
},
{
"code": null,
"e": 3251,
"s": 3145,
"text": "As can be seen from the diagram, three input time steps are taken and used to generate a separate output."
},
{
"code": null,
"e": 3703,
"s": 3251,
"text": "In this instance, causal padding is used in order to ensure that the output sequence has the same length as the input sequence. In other words, this ensures that the network “pads” time steps from the left side of the series in order to ensure that future values on the right side of the series are not being used in generating the forecast — this will quite obviously lead to false results and we will end up overestimating the accuracy of our model."
},
{
"code": null,
"e": 3838,
"s": 3703,
"text": "The stride length is set to one, which means that the filter slides forward by one time step at a time when forecasting future values."
},
{
"code": null,
"e": 4018,
"s": 3838,
"text": "However, this could be set higher. For instance, setting the stride length to two would mean that the output sequence would be approximately half the length of the input sequence."
},
{
"code": null,
"e": 4265,
"s": 4018,
"text": "A long stride length would mean that the model might potentially discard valuable data in generating the forecast, but increasing the stride length can be useful when it comes to capturing longer-term trends and smoothing out noise in the series."
},
{
"code": null,
"e": 4298,
"s": 4265,
"text": "Here is the model configuration:"
},
{
"code": null,
"e": 4881,
"s": 4298,
"text": "model = keras.models.Sequential([ keras.layers.Conv1D(filters=32, kernel_size=3, strides=1, padding=\"causal\", activation=\"relu\", input_shape=[None, 1]), keras.layers.LSTM(32, return_sequences=True), keras.layers.Dense(1), keras.layers.Lambda(lambda x: x * 200)])lr_schedule = keras.callbacks.LearningRateScheduler( lambda epoch: 1e-8 * 10**(epoch / 20))optimizer = keras.optimizers.SGD(lr=1e-8, momentum=0.9)model.compile(loss=keras.losses.Huber(), optimizer=optimizer, metrics=[\"mae\"])"
},
{
"code": null,
"e": 4960,
"s": 4881,
"text": "Firstly, let’s make forecasts using the above model on different window sizes."
},
{
"code": null,
"e": 5062,
"s": 4960,
"text": "It is important that the window size is large enough to account for the volatility across time steps."
},
{
"code": null,
"e": 5104,
"s": 5062,
"text": "Suppose we start with a window size of 5."
},
{
"code": null,
"e": 5137,
"s": 5104,
"text": "The training loss is as follows:"
},
{
"code": null,
"e": 5227,
"s": 5137,
"text": "plt.semilogx(history.history[\"lr\"], history.history[\"loss\"])plt.axis([1e-8, 1e-4, 0, 30])"
},
{
"code": null,
"e": 5302,
"s": 5227,
"text": "Here is a visual of the forecasts versus actual daily cancellation values:"
},
{
"code": null,
"e": 5535,
"s": 5302,
"text": "rnn_forecast = model_forecast(model, series[:, np.newaxis], window_size)rnn_forecast = rnn_forecast[split_time - window_size:-1, -1, 0]plt.figure(figsize=(10, 6))plot_series(time_valid, x_valid)plot_series(time_valid, rnn_forecast)"
},
{
"code": null,
"e": 5574,
"s": 5535,
"text": "The mean absolute error is calculated:"
},
{
"code": null,
"e": 5651,
"s": 5574,
"text": ">>> keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()9.113908"
},
{
"code": null,
"e": 5847,
"s": 5651,
"text": "With a mean of 19.89 across the validation set, the model accuracy is reasonable. However, we do see from the diagram above that the model falls short in terms of forecasting more extreme values."
},
{
"code": null,
"e": 5892,
"s": 5847,
"text": "What if the window size was increased to 30?"
},
{
"code": null,
"e": 5936,
"s": 5892,
"text": "The mean absolute error decreases slightly:"
},
{
"code": null,
"e": 6013,
"s": 5936,
"text": ">>> keras.metrics.mean_absolute_error(x_valid, rnn_forecast).numpy()7.377962"
},
{
"code": null,
"e": 6222,
"s": 6013,
"text": "As mentioned, the stride length can be set higher if we wish to smooth out the forecast — with the caveat that such a forecast (the output sequence) will have less data points than that of the input sequence."
},
{
"code": null,
"e": 6441,
"s": 6222,
"text": "Unlike an LSTM, a CNN is not recurrent, which means that it does not retain memory of previous time series patterns. Instead, it can only train based on the data that is inputted by the model at a particular time step."
},
{
"code": null,
"e": 6616,
"s": 6441,
"text": "However, by stacking several Conv1D layers together, it is in fact possible for a convolutional neural network to effectively learn long-term dependencies in the time series."
},
{
"code": null,
"e": 7027,
"s": 6616,
"text": "This can be done using a WaveNet architecture. Essentially, this means that the model defines every layer as a 1D convolutional layer with a stride length of 1 and a kernel size of 2. The second convolutional layer uses a dilation rate of 2, which means that every second input timestep in the series is skipped. The third layer uses a dilation rate of 4, the fourth layer uses a dilation rate of 8, and so on."
},
{
"code": null,
"e": 7183,
"s": 7027,
"text": "The reason for this is that it allows the lower layers to learn short-term patterns in the time series, while the higher layers learn longer-term patterns."
},
{
"code": null,
"e": 7224,
"s": 7183,
"text": "The WaveNet model is defined as follows:"
},
{
"code": null,
"e": 8139,
"s": 7224,
"text": "model = keras.models.Sequential()model.add(keras.layers.InputLayer(input_shape=[None, 1]))for dilation_rate in (1, 2, 4, 8, 16, 32): model.add( keras.layers.Conv1D(filters=32, kernel_size=2, strides=1, dilation_rate=dilation_rate, padding=\"causal\", activation=\"relu\") )model.add(keras.layers.Conv1D(filters=1, kernel_size=1))optimizer = keras.optimizers.Adam(lr=3e-4)model.compile(loss=keras.losses.Huber(), optimizer=optimizer, metrics=[\"mae\"])model_checkpoint = keras.callbacks.ModelCheckpoint( \"my_checkpoint.h6\", save_best_only=True)early_stopping = keras.callbacks.EarlyStopping(patience=50)history = model.fit(train_set, epochs=500, validation_data=valid_set, callbacks=[early_stopping, model_checkpoint])"
},
{
"code": null,
"e": 8354,
"s": 8139,
"text": "A window size of 64 is used in training the model. In this instance, we are using a larger window size than was used with the CNN-LSTM model, in order to ensure that the CNN model picks up longer-term dependencies."
},
{
"code": null,
"e": 8663,
"s": 8354,
"text": "Note that early stopping is used when training the neural network. The purpose of this is to ensure that the neural network halts training at the point where further training would result in overfitting. Determining this manually is quite an arbitrary process, so early stopping can greatly assist with this."
},
{
"code": null,
"e": 8743,
"s": 8663,
"text": "Let’s now generate forecasts using the standalone CNN model that we just built."
},
{
"code": null,
"e": 8881,
"s": 8743,
"text": "cnn_forecast = model_forecast(model, series[..., np.newaxis], window_size)cnn_forecast = cnn_forecast[split_time - window_size:-1, -1, 0]"
},
{
"code": null,
"e": 8931,
"s": 8881,
"text": "Here is a plot of the forecasted vs. actual data."
},
{
"code": null,
"e": 8988,
"s": 8931,
"text": "The mean absolute error came in slightly higher at 7.49."
},
{
"code": null,
"e": 9187,
"s": 8988,
"text": "Note that for both models, the Huber loss was used as the loss function. This type of loss tends to be more robust to outliers, in that it is quadratic for smaller errors and linear for larger ones."
},
{
"code": null,
"e": 9561,
"s": 9187,
"text": "This type of loss is suitable for this scenario, as we can see that some outliers are present in the data. Using MSE (mean squared error) would overly inflate the forecast error yielded by the model, whereas MAE on its own would likely underestimate the size of the error by not taking such outliers into account. The use of a Huber loss function allows for a happy medium."
},
{
"code": null,
"e": 9638,
"s": 9561,
"text": ">>> keras.metrics.mean_absolute_error(x_valid, cnn_forecast).numpy()7.490844"
},
{
"code": null,
"e": 9843,
"s": 9638,
"text": "Even with a slightly higher MAE, the CNN model has performed quite well in forecasting daily hotel cancellations, without having to be combined with an LSTM layer in order to learn long-term dependencies."
},
{
"code": null,
"e": 9916,
"s": 9843,
"text": "Of course, any model comes with limitations and the CNN is no exception."
},
{
"code": null,
"e": 10302,
"s": 9916,
"text": "Given that the model is making one-step predictions, this means that all observations up to time t in the relevant window is required to predict the value at time t+1. In this regard, a one-step CNN cannot be used to make long-range forecasts. While a multi-step CNN can be used for this purpose, it is debatable as to whether such a model will outperform an ARIMA model, for instance."
},
{
"code": null,
"e": 10807,
"s": 10302,
"text": "Additionally, a CNN (or any neural network model) requires a lot of data to train effectively. While many time series models come with pre-built parameters to model a range of time series, the CNN is learning entirely from scratch. In this regard, a researcher may spend a lot of time configuring a CNN model and end up with either lower accuracy relative to other standard time series models, or just a marginal gain in accuracy that does not justify the extra training time and data resources required."
},
{
"code": null,
"e": 11229,
"s": 10807,
"text": "In this particular example, the model was trained using 80% of the data as training data and then prediction accuracy was screened against 20% of the validation data. However, a true test of whether a model is effective involves comparing the prediction accuracy against test data, or data that is completely unseen by the model. This has not been done here, as this article has covered the model training component only."
},
{
"code": null,
"e": 11399,
"s": 11229,
"text": "However, neural networks are quite prone to overfitting — whereby the model performs well on data it has seen before — while performing poorly in predicting unseen data."
},
{
"code": null,
"e": 11430,
"s": 11399,
"text": "In this example, we have seen:"
},
{
"code": null,
"e": 11513,
"s": 11430,
"text": "The similarities and differences between CNNs and LSTMs in forecasting time series"
},
{
"code": null,
"e": 11577,
"s": 11513,
"text": "How dilated convolutions assist CNNs in forecasting time series"
},
{
"code": null,
"e": 11664,
"s": 11577,
"text": "Modification of kernel size, padding and strides in forecasting a time series with CNN"
},
{
"code": null,
"e": 11757,
"s": 11664,
"text": "Use of a WaveNet architecture to conduct a time series forecast using stand-alone CNN layers"
},
{
"code": null,
"e": 11884,
"s": 11757,
"text": "In particular, we saw how a CNN can produce similarly strong results compared to a CNN-LSTM model through the use of dilation."
},
{
"code": null,
"e": 11979,
"s": 11884,
"text": "Many thanks for your time, and any questions, suggestions or feedback are greatly appreciated."
},
{
"code": null,
"e": 12321,
"s": 11979,
"text": "As mentioned, this topic is also covered in the Intro to TensorFlow for Deep Learning course from Udacity course — I highly recommend the chapter on Time Series Forecasting for further detail on this topic. Usual disclaimers apply — this is only a personal recommendation and I have no affiliation with the authors of this course in any way."
},
{
"code": null,
"e": 12431,
"s": 12321,
"text": "You can also find the full Jupyter Notebook that I used for running this example on hotel cancellations here."
},
{
"code": null,
"e": 12526,
"s": 12431,
"text": "The original Jupyter Notebook (Copyright 2018, The TensorFlow Authors) can also be found here."
}
]
|
Laravel - Guest User Gates | The Guest User Gates feature is an add-on to the latest 5.7 version released in September 2018. This feature is used to initiate the authorization process for specific users.
In Laravel 5.6, there was a procedure where it used to return false for unauthenticated users. In Laravel 5.7, we can allow guests to go authorization checks by using the specific nullable type hint within the specified controller as given below −
<?php
Gate::define('view-post', function (?User $user) {
// Guests
});
By using a nullable type hint the $user variable will be null when a guest user is passed to the gate. You can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization. If you don’t use a nullable type hint, guests will automatically get the 403 response for Laravel 5.7, which is displayed below −
The difference between 403 and 404 error is that 404 is displayed when user tries to access the unknown resource or URL and 403 error as mentioned in the snapshot above is displayed if unauthorized user accesses the website.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2647,
"s": 2472,
"text": "The Guest User Gates feature is an add-on to the latest 5.7 version released in September 2018. This feature is used to initiate the authorization process for specific users."
},
{
"code": null,
"e": 2895,
"s": 2647,
"text": "In Laravel 5.6, there was a procedure where it used to return false for unauthenticated users. In Laravel 5.7, we can allow guests to go authorization checks by using the specific nullable type hint within the specified controller as given below −"
},
{
"code": null,
"e": 2970,
"s": 2895,
"text": "<?php\nGate::define('view-post', function (?User $user) {\n // Guests\n});\n"
},
{
"code": null,
"e": 3346,
"s": 2970,
"text": "By using a nullable type hint the $user variable will be null when a guest user is passed to the gate. You can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization. If you don’t use a nullable type hint, guests will automatically get the 403 response for Laravel 5.7, which is displayed below −"
},
{
"code": null,
"e": 3571,
"s": 3346,
"text": "The difference between 403 and 404 error is that 404 is displayed when user tries to access the unknown resource or URL and 403 error as mentioned in the snapshot above is displayed if unauthorized user accesses the website."
},
{
"code": null,
"e": 3604,
"s": 3571,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3624,
"s": 3604,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 3659,
"s": 3624,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3673,
"s": 3659,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3707,
"s": 3673,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3727,
"s": 3707,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 3760,
"s": 3727,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3780,
"s": 3760,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3815,
"s": 3780,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3838,
"s": 3815,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 3873,
"s": 3838,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3893,
"s": 3873,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 3900,
"s": 3893,
"text": " Print"
},
{
"code": null,
"e": 3911,
"s": 3900,
"text": " Add Notes"
}
]
|
How to Create Multi-Category Charts in Excel? - GeeksforGeeks | 24 May, 2021
The multi-category chart is used when we handle data sets that have the main category followed by a subcategory. For example: “Fruits” is a main category and bananas, apples, grapes are subcategories under fruits. These charts help to infer data when we deal with dynamic categories of data sets. By using a single chart we can analyze various subcategories of data.
In this article, we will see how to create a multi-category chart in Excel using a suitable example shown below :
Example: Consider the employees from our organization working in various departments. The main categories under departments are “Marketing”, “Sales”, “IT”. Now under every department, there are multiple employees which is a subcategory.
Now, we would like to create a Multi-Category chart having the age details of employees from multiple departments. Consider the table shown below :
Employee Details Table
Step 1: Insert the data into the cells in Excel. Now select all the data by dragging and then go to “Insert” and select “Insert Column or Bar Chart”. A pop-down menu having 2-D and 3-D bars will occur and select “vertical bar” from it.
Select the cell -> Insert -> Chart Groups -> 2-D Column
Bar Chart Insertion
Multi-Category Chart
An important thing to note is that sometimes few subcategory data may be missing in the chart after insertion. It is not an error and just by increasing the size of the chart the data will be shown.
The Multi-category chart is ready. Now we can perform various modifications to it to make the chart more insightful by adding titles, changing the width and gap, assigning different colors to different sub-categories.
Step 2: For formatting, select the chart and use the “+” button beside it to add Title, Data labels, Axes Titles, and others or right-click and then select Format option.
Adding Title: Check the “Chart Title” box from the Chart Elements pop down and add a suitable title.
Adding data labels: Check the “Data Labels” from the Chart Elements pop down.
Data Labels
Assigning a color to bars: Select the individual bar and add colors as shown below:
Gap Width: Assign a suitable gap width as per requirements. Select all the bars, right-click on it and select “Format Data Series.”
Gap width
Formatting Axis: Select the chart and then click on the “+” button and under “Axes” select “More Options”. Another way is to select the axis in the chart and then right-click and click on “Format Axis”.
Axis Formation
Changing the chart style: Click on the Chart Styles beside the chart and select a suitable chart style.
Final Multi-Category Chart
Changing the Chart Type: Suppose now we want the above chart in the form of horizontal bars.
Select chart -> Right Click -> Change Chart Type
Finally, Click on OK.
Final Horizontal Multi-Category chart
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Get Length of Array in Excel VBA?
Introduction to Excel Spreadsheet
Macros in Excel
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Extract the Last Word From a Cell in Excel?
How to Easily Calculate the Dot Product in Excel? | [
{
"code": null,
"e": 25070,
"s": 25042,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25438,
"s": 25070,
"text": "The multi-category chart is used when we handle data sets that have the main category followed by a subcategory. For example: “Fruits” is a main category and bananas, apples, grapes are subcategories under fruits. These charts help to infer data when we deal with dynamic categories of data sets. By using a single chart we can analyze various subcategories of data. "
},
{
"code": null,
"e": 25552,
"s": 25438,
"text": "In this article, we will see how to create a multi-category chart in Excel using a suitable example shown below :"
},
{
"code": null,
"e": 25790,
"s": 25552,
"text": "Example: Consider the employees from our organization working in various departments. The main categories under departments are “Marketing”, “Sales”, “IT”. Now under every department, there are multiple employees which is a subcategory. "
},
{
"code": null,
"e": 25938,
"s": 25790,
"text": "Now, we would like to create a Multi-Category chart having the age details of employees from multiple departments. Consider the table shown below :"
},
{
"code": null,
"e": 25961,
"s": 25938,
"text": "Employee Details Table"
},
{
"code": null,
"e": 26197,
"s": 25961,
"text": "Step 1: Insert the data into the cells in Excel. Now select all the data by dragging and then go to “Insert” and select “Insert Column or Bar Chart”. A pop-down menu having 2-D and 3-D bars will occur and select “vertical bar” from it."
},
{
"code": null,
"e": 26253,
"s": 26197,
"text": "Select the cell -> Insert -> Chart Groups -> 2-D Column"
},
{
"code": null,
"e": 26273,
"s": 26253,
"text": "Bar Chart Insertion"
},
{
"code": null,
"e": 26294,
"s": 26273,
"text": "Multi-Category Chart"
},
{
"code": null,
"e": 26493,
"s": 26294,
"text": "An important thing to note is that sometimes few subcategory data may be missing in the chart after insertion. It is not an error and just by increasing the size of the chart the data will be shown."
},
{
"code": null,
"e": 26711,
"s": 26493,
"text": "The Multi-category chart is ready. Now we can perform various modifications to it to make the chart more insightful by adding titles, changing the width and gap, assigning different colors to different sub-categories."
},
{
"code": null,
"e": 26882,
"s": 26711,
"text": "Step 2: For formatting, select the chart and use the “+” button beside it to add Title, Data labels, Axes Titles, and others or right-click and then select Format option."
},
{
"code": null,
"e": 26983,
"s": 26882,
"text": "Adding Title: Check the “Chart Title” box from the Chart Elements pop down and add a suitable title."
},
{
"code": null,
"e": 27061,
"s": 26983,
"text": "Adding data labels: Check the “Data Labels” from the Chart Elements pop down."
},
{
"code": null,
"e": 27073,
"s": 27061,
"text": "Data Labels"
},
{
"code": null,
"e": 27157,
"s": 27073,
"text": "Assigning a color to bars: Select the individual bar and add colors as shown below:"
},
{
"code": null,
"e": 27290,
"s": 27157,
"text": "Gap Width: Assign a suitable gap width as per requirements. Select all the bars, right-click on it and select “Format Data Series.”"
},
{
"code": null,
"e": 27300,
"s": 27290,
"text": "Gap width"
},
{
"code": null,
"e": 27503,
"s": 27300,
"text": "Formatting Axis: Select the chart and then click on the “+” button and under “Axes” select “More Options”. Another way is to select the axis in the chart and then right-click and click on “Format Axis”."
},
{
"code": null,
"e": 27518,
"s": 27503,
"text": "Axis Formation"
},
{
"code": null,
"e": 27622,
"s": 27518,
"text": "Changing the chart style: Click on the Chart Styles beside the chart and select a suitable chart style."
},
{
"code": null,
"e": 27649,
"s": 27622,
"text": "Final Multi-Category Chart"
},
{
"code": null,
"e": 27742,
"s": 27649,
"text": "Changing the Chart Type: Suppose now we want the above chart in the form of horizontal bars."
},
{
"code": null,
"e": 27791,
"s": 27742,
"text": "Select chart -> Right Click -> Change Chart Type"
},
{
"code": null,
"e": 27813,
"s": 27791,
"text": "Finally, Click on OK."
},
{
"code": null,
"e": 27851,
"s": 27813,
"text": "Final Horizontal Multi-Category chart"
},
{
"code": null,
"e": 27858,
"s": 27851,
"text": "Picked"
},
{
"code": null,
"e": 27864,
"s": 27858,
"text": "Excel"
},
{
"code": null,
"e": 27962,
"s": 27864,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27990,
"s": 27962,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 28045,
"s": 27990,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 28103,
"s": 28045,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 28144,
"s": 28103,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 28178,
"s": 28144,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 28194,
"s": 28178,
"text": "Macros in Excel"
},
{
"code": null,
"e": 28250,
"s": 28194,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
},
{
"code": null,
"e": 28314,
"s": 28250,
"text": "How to Sum Values Based on Criteria in Another Column in Excel?"
},
{
"code": null,
"e": 28365,
"s": 28314,
"text": "How to Extract the Last Word From a Cell in Excel?"
}
]
|
Image recognition with Machine Learning on Python, Convolutional Neural Network | by Jonathan Leban | Towards Data Science | This article follows the article I wrote on image processing. After making the data available for image recognition task, it is time to create an algorithm that will perform the task. Among many techniques used to recognize images as multilayer perceptron model, Convolution Neural Network (CNN) appears as a very efficient one. In this article, we will see how to build a CNN and how to apply it on a dataset of images.
When we start building an image recognition model for the first time, it’s usually a good idea to train and evaluate it on a relatively simple dataset.
One of the simplest tasks we can perform is handwritten digit recognition. Given an image of a handwritten digit (i.e., 0, 1, ..., 9), we want our model to be able to correctly classify its numeric value. Though this task seems relatively simple, it is actually used fairly often in real life, such as automatically extracting credit card numbers from a picture. The dataset we will use for digit recognition is the MNIST dataset, which is the dataset used for machine learning-based digit recognition.
The MNIST (Modified National Institute of Standards and Technology) database contains 60,000 training examples and 10,000 testing examples. The database contains grayscale handwritten digits that were resized to fit in a 20x20 pixel box, which was then centered in a 28x28 image (padded with whitespace). The MNIST database is accessible via Python.
In this article, I will show you how to code your Convolutional Neural Network using keras, TensorFlow’s high-level API. I am using tensorflow 2.0 in this article.
Since each grayscale image has dimensions 28x28, there are 784 pixels per image. Therefore, each input image corresponds to a tensor of 784 normalized floating point values between 0.0 and 1.0. The label for an image is a one-hot tensor with 10 classes (each class represents a digit). In terms of our code, we have img_rows = 28, img_cols = 28 and num_classes = 10. Thus the input has shape (number_examples, img_rows, img_cols) hence 60000x28x28. Another important element to set up is the random seed as we want to keep the start point when a computer generates a random number sequence.
We also import the MNIST dataset.
import tensorflow as tf # tensorflow 2.0from keras.datasets import mnistimport numpy as npseed=0np.random.seed(seed) # fix random seedtf.random.set_seed(seed)# input image dimensionsnum_classes = 10 # 10 digitsimg_rows, img_cols = 28, 28 # number of pixels # the data, shuffled and split between train and test sets(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
As mentioned in the previous section, inputs have shape (number_examples, img_rows, img_cols). However, in order to use the data with our convolutional neural network, we need to get it into NHWC format.
NHWC format has a shape with four dimensions:
Number of image data samples (batch size)Height of each imageWidth of each imageChannels per image
Number of image data samples (batch size)
Height of each image
Width of each image
Channels per image
The height and width of each image from the dataset is img_rows and img_cols, while the number of channels is 1 (since the images are grayscale).
Also, each pixel contains a greyscale value quantified by an integer between 0 and 255. So, the database is normalized to have floating point values between 0.0 and 1.0. In this case, 0.0 corresponds to a grayscale pixel value of 255 (pure white), while 1.0 corresponds to a grayscale pixel value of 0 (pure black).
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)input_shape = (img_rows, img_cols, 1)# cast floats to single precisionX_train = X_train.astype('float32')X_test = X_test.astype('float32')# rescale data in interval [0,1]X_train /= 255X_test /= 255
We need to transform our classes into vectors. We do this by tapping the following line:
Y_train = keras.utils.to_categorical(Y_train, num_classes)Y_test = keras.utils.to_categorical(Y_test, num_classes)
To have a better explanation of this step, you should see this article.
Now that we have process our data, we can start to build out model.
As mentioned at the end of the article I wrote on Image processing, filters play a huge role in image recognition. We use filters to transform inputs and extract features that allow our model to recognize certain images. A very high-level example of this would be a curve detecting filter, which allows our model to distinguish between digits with curves and digits without curves.
1- Filters
Like all neural network weights, the filter’s weights are trainable variables. We train our neural network (via the kernel matrix weights) to produce filters that are able to extract the most useful hidden features.
When the input data has multiple channels, a filter will have a separate kernel matrix per channel. The MNIST dataset only has one channel, but for other types of image data (e.g. RGB), we would train the model to obtain optimal weights for each channel’s kernel matrix.
2-Convolution
We’ve now reached the focal point of convolutional neural networks: the convolution. The convolution represents how we apply our filter weights to the input data. The main operation used by a convolution is the matrix dot product, i.e. a summation over the element-wise product of two matrices.
The number of matrix dot products in a convolution depends on the dimensions of the input data and kernel matrix, as well as the stride size. The stride size is the vertical/horizontal offset of the kernel matrix as it moves along the input data.
3-Padding
Sometimes, when we do the dot product operation as seen before, we don’t use a row or a column. To avoid this phenomenon we can use padding.
Thus, if we want to use all the input data in our convolution, we can pad the input data matrix with 0’s. This means we add rows/columns made entirely of 0’s to the edges of the input data matrix. Since 0 multiplied by any number results in 0, the padding doesn’t affect matrix dot products. This is important because we don’t want to add any distortions to our convolution.
4-Convolution layer
A convolution layer in a CNN applies multiple filters to the input tensor. While each filter has a separate kernel matrix for each of the input channels, the overall result of a filter’s convolution is the sum of the convolutions across all the input channels.
Adding more filters to a convolution layer allows the layer to better extract hidden features. However, this comes at the cost of additional training time and computational complexity, since filters add extra weights to the model. The number of channels for the output data is equal to the number of filters the convolution layer uses.
While the convolution layer extracts important hidden features, the number of features can still be pretty large. We can use pooling to reduce the size of the data in the height and width dimensions. This allows the model to perform fewer computations and ultimately train faster. It also prevents overfitting, by extracting only the most salient features and ignoring potential distortions or uncommon features found in only a few examples.
How does pooling work?
Similar to a convolution, we use filter matrices in pooling. However, the pooling filter doesn’t have any weights, nor does it perform matrix dot products. Instead, it applies a reduction operation to subsections of the input data.
The type of pooling that is usually used in CNNs is referred to as max pooling. The filters of max pooling use the max operation to obtain the maximum number in each submatrix of the input data.
1- Adding extra layers
Like all neural networks, CNNs can benefit from additional layers. The additional layers allow a CNN to essentially stack multiple filters together for use on the image data. However, similar to building any neural network, we need to be careful of how many additional layers we add. If we add too many layers to a model, we run the risk of having it overfit to the training data and therefore generalizing very poorly. Furthermore, each additional layer adds computational complexity and increases training time for our model.
2- Increase filters
We usually increase the number of filters in a convolution layer the deeper it is in our model. In this case, our second convolution layer has 64 filters, compared to the 32 filters of the first convolution layer. The deeper the convolution layer, the more detailed the extracted features become. For example, the first convolution layer may have filters that extract features such as lines, edges, and curves. When we get to the second level, the filters of the convolution layer could now extract more distinguishing features, such as the sharp angle of a 77 or the intersecting curves of an 88.
1-Fully-connected layer
We apply a fully-connected layer of size 1024 (i.e. the number of neurons in the layer) to the output data of the second pooling layer. The number of units is somewhat arbitrary. Enough to be powerful, but not so much as to be too resource intensive. The purpose of the fully-connected layer is to aggregate the data features before we convert them to classes. This allows the model to make better predictions than if we had just converted the pooling output directly to classes.
2-Flattening
The data we have been using in our model is of the NHWC format. However, in order to use a fully-connected layer, we need the data to be a matrix, where the number of rows represents the batch size and the columns represent the data features. This time we need to reshape in the opposite direction and converting from NHWC to a 2-D matrix.
1- Co-adaptation
Co-adaptation refers to when multiple neurons in a layer extract the same, or very similar, hidden features from the input data. This can happen when the connection weights for two different neurons are nearly identical.
When a fully-connected layer has a large number of neurons, co-adaptation is more likely to occur. This can be a problem for two reasons. First, it is a waste of computation when we have redundant neurons computing the same output. Second, if many neurons are extracting the same features, it adds more significance to those features for our model. This leads to overfitting if the duplicate extracted features are specific to only the training set.
2-Dropout
The way we minimize co-adaptation for fully-connected layers with many neurons is by applying dropout during training. In dropout, we randomly shut down some fraction of a layer’s neurons at each training step by zeroing out the neuron values.
Since there are 10 possible digits an MNIST image can be, we use a 10 neuron fully-connected layer to obtain the classes for each digit class. The Softmax function is applied to the classes to convert them into per class probabilities.
Now we are ready to build our model. Here is the code:
from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Flatten from keras.layers import MaxPooling2D, Dropoutmodel = Sequential()#add model layersmodel.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape))model.add(MaxPooling2D(pool_size=(2, 2)))# add second convolutional layer with 20 filtersmodel.add(Conv2D(64, (5, 5), activation='relu')) # add 2D pooling layermodel.add(MaxPooling2D(pool_size=(2, 2))) # flatten datamodel.add(Flatten()) # add a dense all-to-all relu layermodel.add(Dense(1024, activation='relu')) # apply dropout with rate 0.5model.add(Dropout(0.5)) # soft-max layermodel.add(Dense(num_classes, activation='softmax'))
The model type that we will be using is Sequential. Sequential is the easiest way to build a model in Keras. It allows you to build a model layer by layer.
We use the add() method to attach layers to our model. For the purposes of our introductory example, it suffices to focus on Dense layers for simplicity. Every Dense() layer accepts as its first required argument an integer which specifies the number of neurons. The type of activation function for the layer is defined using the activation optional argument, the input of which is the name of the activation function in string format. Examples include relu, tanh, elu, sigmoid, softmax.
In this neural network, we have 2 convolution layers followed each time by a pooling layer. Then we flatten the data to add a dense layer on which we apply dropout with a rate of 0.5. Finally, we add a dense layer to allocate each image with the correct class.
Next, we need to compile our model. Compiling the model takes three parameters: optimizer, loss and metrics.
The optimizer controls the learning rate. We will be using ‘adam’ as our optimizer. Adam is generally a good optimizer to use for many cases. The adam optimizer adjusts the learning rate throughout training.
The learning rate determines how fast the optimal weights for the model are calculated. A smaller learning rate may lead to more accurate weights (up to a certain point), but the downsize is the computing time.
We will use ‘categorical_crossentropy’ for our loss function. This is the most common choice for classification. A lower score indicates that the model is performing better.
To make things even easier to interpret, we will use the ‘accuracy’ metric to see the accuracy score on the validation set when we train the model.
#compile model using accuracy to measure model performancemodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Now we will train our model. To train, we will use the ‘fit()’ function on our model with the following parameters: training data (X_train), target data (Y_train), validation data, and the number of epochs.
For our validation data, we will use the test set provided to us in our dataset, which we have split into X_test and Y_test.
The number of epochs is the number of times the model will cycle through the data. The more epochs we run, the more the model will improve, up to a certain point. After that point, the model will stop improving during each epoch. For our model, we will set the number of epochs to 3.
#train the modelmodel.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=3)
Now we have trained our model we can evaluate its performance:
# evaluate the modelscore = model.evaluate(X_test, Y_test, verbose=1)# print performanceprint()print('Test loss:', score[0])print('Test accuracy:', score[1])
Thus, we have an accuracy of 99,3% and a lost of 0.025 on the test set which is very good. We can still improve the model by increasing the number of epoch and by introducing a batch size.
If you want to see the actual predictions that our model has made for the test data, we can use the predict_classes function. We can also to this by using the predict function will give an array with 10 numbers. These numbers are the probabilities that the input image represents each digit (0–9). The array index with the highest number represents the model prediction. The sum of each array equals 1 (since each number is a probability).
To show this, we will show the predictions for the first 4 images in the test set.
Note: If we have new data, we can input our new data into the predict function to see the predictions our model makes on the new data. Since we don’t have any new unseen data, we will show predictions using the test set for now.
#predict first 4 images in the test setmodel.predict_classes(X_test[:4])
#predict first 4 images in the test setmodel.predict(X_test[:4])
We can see that our model predicted 7, 2, 1 and 0 for the first four images.
Let’s compare this with the actual results.
#actual results for first 4 images in test sety_test[:4]
The actual results show that the first four images are also 7, 2,1 and 0. Our model predicted correctly!
import tensorflow as tf # tensorflow 2.0from keras.datasets import mnistimport numpy as npseed=0np.random.seed(seed) # fix random seedtf.random.set_seed(seed)# input image dimensionsnum_classes = 10 # 10 digitsimg_rows, img_cols = 28, 28 # number of pixels# the data, shuffled and split between train and test sets(X_train, Y_train), (X_test, Y_test) = mnist.load_data()X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)input_shape = (img_rows, img_cols, 1)# cast floats to single precisionX_train = X_train.astype('float32')X_test = X_test.astype('float32')# rescale data in interval [0,1]X_train /= 255X_test /= 255Y_train = keras.utils.to_categorical(Y_train, num_classes)Y_test = keras.utils.to_categorical(Y_test, num_classes)from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Flatten from keras.layers import MaxPooling2D, Dropoutmodel = Sequential()#add model layersmodel.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape))model.add(MaxPooling2D(pool_size=(2, 2)))# add second convolutional layer with 20 filtersmodel.add(Conv2D(64, (5, 5), activation='relu')) # add 2D pooling layermodel.add(MaxPooling2D(pool_size=(2, 2))) # flatten datamodel.add(Flatten()) # add a dense all-to-all relu layermodel.add(Dense(1024, activation='relu')) # apply dropout with rate 0.5model.add(Dropout(0.5)) # soft-max layermodel.add(Dense(num_classes, activation='softmax'))#compile model using accuracy to measure model performancemodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])#train the modelmodel.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=3)# evaluate the modelscore = model.evaluate(X_test, Y_test, verbose=1)# print performanceprint()print('Test loss:', score[0])print('Test accuracy:', score[1])#predict first 4 images in the test setmodel.predict(X_test[:4])model.predict_classes(X_test[:4])#actual results for first 4 images in test setY_test[:4]
In this article, I tackled the second part of image recognition which is building a Convolution Neural Network.
I hope you found what you came here for in this article and stay with me for the next episodes of this image recognition trip!
PS: I am currently a Master of Engineering Student at Berkeley, and if you want to discuss the topic, feel free to reach me. Here is my email. | [
{
"code": null,
"e": 593,
"s": 172,
"text": "This article follows the article I wrote on image processing. After making the data available for image recognition task, it is time to create an algorithm that will perform the task. Among many techniques used to recognize images as multilayer perceptron model, Convolution Neural Network (CNN) appears as a very efficient one. In this article, we will see how to build a CNN and how to apply it on a dataset of images."
},
{
"code": null,
"e": 745,
"s": 593,
"text": "When we start building an image recognition model for the first time, it’s usually a good idea to train and evaluate it on a relatively simple dataset."
},
{
"code": null,
"e": 1248,
"s": 745,
"text": "One of the simplest tasks we can perform is handwritten digit recognition. Given an image of a handwritten digit (i.e., 0, 1, ..., 9), we want our model to be able to correctly classify its numeric value. Though this task seems relatively simple, it is actually used fairly often in real life, such as automatically extracting credit card numbers from a picture. The dataset we will use for digit recognition is the MNIST dataset, which is the dataset used for machine learning-based digit recognition."
},
{
"code": null,
"e": 1598,
"s": 1248,
"text": "The MNIST (Modified National Institute of Standards and Technology) database contains 60,000 training examples and 10,000 testing examples. The database contains grayscale handwritten digits that were resized to fit in a 20x20 pixel box, which was then centered in a 28x28 image (padded with whitespace). The MNIST database is accessible via Python."
},
{
"code": null,
"e": 1762,
"s": 1598,
"text": "In this article, I will show you how to code your Convolutional Neural Network using keras, TensorFlow’s high-level API. I am using tensorflow 2.0 in this article."
},
{
"code": null,
"e": 2353,
"s": 1762,
"text": "Since each grayscale image has dimensions 28x28, there are 784 pixels per image. Therefore, each input image corresponds to a tensor of 784 normalized floating point values between 0.0 and 1.0. The label for an image is a one-hot tensor with 10 classes (each class represents a digit). In terms of our code, we have img_rows = 28, img_cols = 28 and num_classes = 10. Thus the input has shape (number_examples, img_rows, img_cols) hence 60000x28x28. Another important element to set up is the random seed as we want to keep the start point when a computer generates a random number sequence."
},
{
"code": null,
"e": 2387,
"s": 2353,
"text": "We also import the MNIST dataset."
},
{
"code": null,
"e": 2759,
"s": 2387,
"text": "import tensorflow as tf # tensorflow 2.0from keras.datasets import mnistimport numpy as npseed=0np.random.seed(seed) # fix random seedtf.random.set_seed(seed)# input image dimensionsnum_classes = 10 # 10 digitsimg_rows, img_cols = 28, 28 # number of pixels # the data, shuffled and split between train and test sets(X_train, Y_train), (X_test, Y_test) = mnist.load_data()"
},
{
"code": null,
"e": 2963,
"s": 2759,
"text": "As mentioned in the previous section, inputs have shape (number_examples, img_rows, img_cols). However, in order to use the data with our convolutional neural network, we need to get it into NHWC format."
},
{
"code": null,
"e": 3009,
"s": 2963,
"text": "NHWC format has a shape with four dimensions:"
},
{
"code": null,
"e": 3108,
"s": 3009,
"text": "Number of image data samples (batch size)Height of each imageWidth of each imageChannels per image"
},
{
"code": null,
"e": 3150,
"s": 3108,
"text": "Number of image data samples (batch size)"
},
{
"code": null,
"e": 3171,
"s": 3150,
"text": "Height of each image"
},
{
"code": null,
"e": 3191,
"s": 3171,
"text": "Width of each image"
},
{
"code": null,
"e": 3210,
"s": 3191,
"text": "Channels per image"
},
{
"code": null,
"e": 3356,
"s": 3210,
"text": "The height and width of each image from the dataset is img_rows and img_cols, while the number of channels is 1 (since the images are grayscale)."
},
{
"code": null,
"e": 3672,
"s": 3356,
"text": "Also, each pixel contains a greyscale value quantified by an integer between 0 and 255. So, the database is normalized to have floating point values between 0.0 and 1.0. In this case, 0.0 corresponds to a grayscale pixel value of 255 (pure white), while 1.0 corresponds to a grayscale pixel value of 0 (pure black)."
},
{
"code": null,
"e": 4000,
"s": 3672,
"text": "X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)input_shape = (img_rows, img_cols, 1)# cast floats to single precisionX_train = X_train.astype('float32')X_test = X_test.astype('float32')# rescale data in interval [0,1]X_train /= 255X_test /= 255"
},
{
"code": null,
"e": 4089,
"s": 4000,
"text": "We need to transform our classes into vectors. We do this by tapping the following line:"
},
{
"code": null,
"e": 4204,
"s": 4089,
"text": "Y_train = keras.utils.to_categorical(Y_train, num_classes)Y_test = keras.utils.to_categorical(Y_test, num_classes)"
},
{
"code": null,
"e": 4276,
"s": 4204,
"text": "To have a better explanation of this step, you should see this article."
},
{
"code": null,
"e": 4344,
"s": 4276,
"text": "Now that we have process our data, we can start to build out model."
},
{
"code": null,
"e": 4726,
"s": 4344,
"text": "As mentioned at the end of the article I wrote on Image processing, filters play a huge role in image recognition. We use filters to transform inputs and extract features that allow our model to recognize certain images. A very high-level example of this would be a curve detecting filter, which allows our model to distinguish between digits with curves and digits without curves."
},
{
"code": null,
"e": 4737,
"s": 4726,
"text": "1- Filters"
},
{
"code": null,
"e": 4953,
"s": 4737,
"text": "Like all neural network weights, the filter’s weights are trainable variables. We train our neural network (via the kernel matrix weights) to produce filters that are able to extract the most useful hidden features."
},
{
"code": null,
"e": 5224,
"s": 4953,
"text": "When the input data has multiple channels, a filter will have a separate kernel matrix per channel. The MNIST dataset only has one channel, but for other types of image data (e.g. RGB), we would train the model to obtain optimal weights for each channel’s kernel matrix."
},
{
"code": null,
"e": 5238,
"s": 5224,
"text": "2-Convolution"
},
{
"code": null,
"e": 5533,
"s": 5238,
"text": "We’ve now reached the focal point of convolutional neural networks: the convolution. The convolution represents how we apply our filter weights to the input data. The main operation used by a convolution is the matrix dot product, i.e. a summation over the element-wise product of two matrices."
},
{
"code": null,
"e": 5780,
"s": 5533,
"text": "The number of matrix dot products in a convolution depends on the dimensions of the input data and kernel matrix, as well as the stride size. The stride size is the vertical/horizontal offset of the kernel matrix as it moves along the input data."
},
{
"code": null,
"e": 5790,
"s": 5780,
"text": "3-Padding"
},
{
"code": null,
"e": 5931,
"s": 5790,
"text": "Sometimes, when we do the dot product operation as seen before, we don’t use a row or a column. To avoid this phenomenon we can use padding."
},
{
"code": null,
"e": 6306,
"s": 5931,
"text": "Thus, if we want to use all the input data in our convolution, we can pad the input data matrix with 0’s. This means we add rows/columns made entirely of 0’s to the edges of the input data matrix. Since 0 multiplied by any number results in 0, the padding doesn’t affect matrix dot products. This is important because we don’t want to add any distortions to our convolution."
},
{
"code": null,
"e": 6326,
"s": 6306,
"text": "4-Convolution layer"
},
{
"code": null,
"e": 6587,
"s": 6326,
"text": "A convolution layer in a CNN applies multiple filters to the input tensor. While each filter has a separate kernel matrix for each of the input channels, the overall result of a filter’s convolution is the sum of the convolutions across all the input channels."
},
{
"code": null,
"e": 6923,
"s": 6587,
"text": "Adding more filters to a convolution layer allows the layer to better extract hidden features. However, this comes at the cost of additional training time and computational complexity, since filters add extra weights to the model. The number of channels for the output data is equal to the number of filters the convolution layer uses."
},
{
"code": null,
"e": 7365,
"s": 6923,
"text": "While the convolution layer extracts important hidden features, the number of features can still be pretty large. We can use pooling to reduce the size of the data in the height and width dimensions. This allows the model to perform fewer computations and ultimately train faster. It also prevents overfitting, by extracting only the most salient features and ignoring potential distortions or uncommon features found in only a few examples."
},
{
"code": null,
"e": 7388,
"s": 7365,
"text": "How does pooling work?"
},
{
"code": null,
"e": 7620,
"s": 7388,
"text": "Similar to a convolution, we use filter matrices in pooling. However, the pooling filter doesn’t have any weights, nor does it perform matrix dot products. Instead, it applies a reduction operation to subsections of the input data."
},
{
"code": null,
"e": 7815,
"s": 7620,
"text": "The type of pooling that is usually used in CNNs is referred to as max pooling. The filters of max pooling use the max operation to obtain the maximum number in each submatrix of the input data."
},
{
"code": null,
"e": 7838,
"s": 7815,
"text": "1- Adding extra layers"
},
{
"code": null,
"e": 8366,
"s": 7838,
"text": "Like all neural networks, CNNs can benefit from additional layers. The additional layers allow a CNN to essentially stack multiple filters together for use on the image data. However, similar to building any neural network, we need to be careful of how many additional layers we add. If we add too many layers to a model, we run the risk of having it overfit to the training data and therefore generalizing very poorly. Furthermore, each additional layer adds computational complexity and increases training time for our model."
},
{
"code": null,
"e": 8386,
"s": 8366,
"text": "2- Increase filters"
},
{
"code": null,
"e": 8984,
"s": 8386,
"text": "We usually increase the number of filters in a convolution layer the deeper it is in our model. In this case, our second convolution layer has 64 filters, compared to the 32 filters of the first convolution layer. The deeper the convolution layer, the more detailed the extracted features become. For example, the first convolution layer may have filters that extract features such as lines, edges, and curves. When we get to the second level, the filters of the convolution layer could now extract more distinguishing features, such as the sharp angle of a 77 or the intersecting curves of an 88."
},
{
"code": null,
"e": 9008,
"s": 8984,
"text": "1-Fully-connected layer"
},
{
"code": null,
"e": 9488,
"s": 9008,
"text": "We apply a fully-connected layer of size 1024 (i.e. the number of neurons in the layer) to the output data of the second pooling layer. The number of units is somewhat arbitrary. Enough to be powerful, but not so much as to be too resource intensive. The purpose of the fully-connected layer is to aggregate the data features before we convert them to classes. This allows the model to make better predictions than if we had just converted the pooling output directly to classes."
},
{
"code": null,
"e": 9501,
"s": 9488,
"text": "2-Flattening"
},
{
"code": null,
"e": 9841,
"s": 9501,
"text": "The data we have been using in our model is of the NHWC format. However, in order to use a fully-connected layer, we need the data to be a matrix, where the number of rows represents the batch size and the columns represent the data features. This time we need to reshape in the opposite direction and converting from NHWC to a 2-D matrix."
},
{
"code": null,
"e": 9858,
"s": 9841,
"text": "1- Co-adaptation"
},
{
"code": null,
"e": 10079,
"s": 9858,
"text": "Co-adaptation refers to when multiple neurons in a layer extract the same, or very similar, hidden features from the input data. This can happen when the connection weights for two different neurons are nearly identical."
},
{
"code": null,
"e": 10529,
"s": 10079,
"text": "When a fully-connected layer has a large number of neurons, co-adaptation is more likely to occur. This can be a problem for two reasons. First, it is a waste of computation when we have redundant neurons computing the same output. Second, if many neurons are extracting the same features, it adds more significance to those features for our model. This leads to overfitting if the duplicate extracted features are specific to only the training set."
},
{
"code": null,
"e": 10539,
"s": 10529,
"text": "2-Dropout"
},
{
"code": null,
"e": 10783,
"s": 10539,
"text": "The way we minimize co-adaptation for fully-connected layers with many neurons is by applying dropout during training. In dropout, we randomly shut down some fraction of a layer’s neurons at each training step by zeroing out the neuron values."
},
{
"code": null,
"e": 11019,
"s": 10783,
"text": "Since there are 10 possible digits an MNIST image can be, we use a 10 neuron fully-connected layer to obtain the classes for each digit class. The Softmax function is applied to the classes to convert them into per class probabilities."
},
{
"code": null,
"e": 11074,
"s": 11019,
"text": "Now we are ready to build our model. Here is the code:"
},
{
"code": null,
"e": 11815,
"s": 11074,
"text": "from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Flatten from keras.layers import MaxPooling2D, Dropoutmodel = Sequential()#add model layersmodel.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape))model.add(MaxPooling2D(pool_size=(2, 2)))# add second convolutional layer with 20 filtersmodel.add(Conv2D(64, (5, 5), activation='relu')) # add 2D pooling layermodel.add(MaxPooling2D(pool_size=(2, 2))) # flatten datamodel.add(Flatten()) # add a dense all-to-all relu layermodel.add(Dense(1024, activation='relu')) # apply dropout with rate 0.5model.add(Dropout(0.5)) # soft-max layermodel.add(Dense(num_classes, activation='softmax'))"
},
{
"code": null,
"e": 11971,
"s": 11815,
"text": "The model type that we will be using is Sequential. Sequential is the easiest way to build a model in Keras. It allows you to build a model layer by layer."
},
{
"code": null,
"e": 12459,
"s": 11971,
"text": "We use the add() method to attach layers to our model. For the purposes of our introductory example, it suffices to focus on Dense layers for simplicity. Every Dense() layer accepts as its first required argument an integer which specifies the number of neurons. The type of activation function for the layer is defined using the activation optional argument, the input of which is the name of the activation function in string format. Examples include relu, tanh, elu, sigmoid, softmax."
},
{
"code": null,
"e": 12720,
"s": 12459,
"text": "In this neural network, we have 2 convolution layers followed each time by a pooling layer. Then we flatten the data to add a dense layer on which we apply dropout with a rate of 0.5. Finally, we add a dense layer to allocate each image with the correct class."
},
{
"code": null,
"e": 12829,
"s": 12720,
"text": "Next, we need to compile our model. Compiling the model takes three parameters: optimizer, loss and metrics."
},
{
"code": null,
"e": 13037,
"s": 12829,
"text": "The optimizer controls the learning rate. We will be using ‘adam’ as our optimizer. Adam is generally a good optimizer to use for many cases. The adam optimizer adjusts the learning rate throughout training."
},
{
"code": null,
"e": 13248,
"s": 13037,
"text": "The learning rate determines how fast the optimal weights for the model are calculated. A smaller learning rate may lead to more accurate weights (up to a certain point), but the downsize is the computing time."
},
{
"code": null,
"e": 13422,
"s": 13248,
"text": "We will use ‘categorical_crossentropy’ for our loss function. This is the most common choice for classification. A lower score indicates that the model is performing better."
},
{
"code": null,
"e": 13570,
"s": 13422,
"text": "To make things even easier to interpret, we will use the ‘accuracy’ metric to see the accuracy score on the validation set when we train the model."
},
{
"code": null,
"e": 13715,
"s": 13570,
"text": "#compile model using accuracy to measure model performancemodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 13922,
"s": 13715,
"text": "Now we will train our model. To train, we will use the ‘fit()’ function on our model with the following parameters: training data (X_train), target data (Y_train), validation data, and the number of epochs."
},
{
"code": null,
"e": 14047,
"s": 13922,
"text": "For our validation data, we will use the test set provided to us in our dataset, which we have split into X_test and Y_test."
},
{
"code": null,
"e": 14331,
"s": 14047,
"text": "The number of epochs is the number of times the model will cycle through the data. The more epochs we run, the more the model will improve, up to a certain point. After that point, the model will stop improving during each epoch. For our model, we will set the number of epochs to 3."
},
{
"code": null,
"e": 14419,
"s": 14331,
"text": "#train the modelmodel.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=3)"
},
{
"code": null,
"e": 14482,
"s": 14419,
"text": "Now we have trained our model we can evaluate its performance:"
},
{
"code": null,
"e": 14640,
"s": 14482,
"text": "# evaluate the modelscore = model.evaluate(X_test, Y_test, verbose=1)# print performanceprint()print('Test loss:', score[0])print('Test accuracy:', score[1])"
},
{
"code": null,
"e": 14829,
"s": 14640,
"text": "Thus, we have an accuracy of 99,3% and a lost of 0.025 on the test set which is very good. We can still improve the model by increasing the number of epoch and by introducing a batch size."
},
{
"code": null,
"e": 15269,
"s": 14829,
"text": "If you want to see the actual predictions that our model has made for the test data, we can use the predict_classes function. We can also to this by using the predict function will give an array with 10 numbers. These numbers are the probabilities that the input image represents each digit (0–9). The array index with the highest number represents the model prediction. The sum of each array equals 1 (since each number is a probability)."
},
{
"code": null,
"e": 15352,
"s": 15269,
"text": "To show this, we will show the predictions for the first 4 images in the test set."
},
{
"code": null,
"e": 15581,
"s": 15352,
"text": "Note: If we have new data, we can input our new data into the predict function to see the predictions our model makes on the new data. Since we don’t have any new unseen data, we will show predictions using the test set for now."
},
{
"code": null,
"e": 15654,
"s": 15581,
"text": "#predict first 4 images in the test setmodel.predict_classes(X_test[:4])"
},
{
"code": null,
"e": 15719,
"s": 15654,
"text": "#predict first 4 images in the test setmodel.predict(X_test[:4])"
},
{
"code": null,
"e": 15796,
"s": 15719,
"text": "We can see that our model predicted 7, 2, 1 and 0 for the first four images."
},
{
"code": null,
"e": 15840,
"s": 15796,
"text": "Let’s compare this with the actual results."
},
{
"code": null,
"e": 15897,
"s": 15840,
"text": "#actual results for first 4 images in test sety_test[:4]"
},
{
"code": null,
"e": 16002,
"s": 15897,
"text": "The actual results show that the first four images are also 7, 2,1 and 0. Our model predicted correctly!"
},
{
"code": null,
"e": 18095,
"s": 16002,
"text": "import tensorflow as tf # tensorflow 2.0from keras.datasets import mnistimport numpy as npseed=0np.random.seed(seed) # fix random seedtf.random.set_seed(seed)# input image dimensionsnum_classes = 10 # 10 digitsimg_rows, img_cols = 28, 28 # number of pixels# the data, shuffled and split between train and test sets(X_train, Y_train), (X_test, Y_test) = mnist.load_data()X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)input_shape = (img_rows, img_cols, 1)# cast floats to single precisionX_train = X_train.astype('float32')X_test = X_test.astype('float32')# rescale data in interval [0,1]X_train /= 255X_test /= 255Y_train = keras.utils.to_categorical(Y_train, num_classes)Y_test = keras.utils.to_categorical(Y_test, num_classes)from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, Flatten from keras.layers import MaxPooling2D, Dropoutmodel = Sequential()#add model layersmodel.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape))model.add(MaxPooling2D(pool_size=(2, 2)))# add second convolutional layer with 20 filtersmodel.add(Conv2D(64, (5, 5), activation='relu')) # add 2D pooling layermodel.add(MaxPooling2D(pool_size=(2, 2))) # flatten datamodel.add(Flatten()) # add a dense all-to-all relu layermodel.add(Dense(1024, activation='relu')) # apply dropout with rate 0.5model.add(Dropout(0.5)) # soft-max layermodel.add(Dense(num_classes, activation='softmax'))#compile model using accuracy to measure model performancemodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])#train the modelmodel.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=3)# evaluate the modelscore = model.evaluate(X_test, Y_test, verbose=1)# print performanceprint()print('Test loss:', score[0])print('Test accuracy:', score[1])#predict first 4 images in the test setmodel.predict(X_test[:4])model.predict_classes(X_test[:4])#actual results for first 4 images in test setY_test[:4]"
},
{
"code": null,
"e": 18207,
"s": 18095,
"text": "In this article, I tackled the second part of image recognition which is building a Convolution Neural Network."
},
{
"code": null,
"e": 18334,
"s": 18207,
"text": "I hope you found what you came here for in this article and stay with me for the next episodes of this image recognition trip!"
}
]
|
Java Modifiers | By now, you are quite familiar with the public keyword that appears in almost
all of our examples:
public class Main
The public keyword is an access modifier,
meaning that it is used to set the access level for classes, attributes, methods and
constructors.
We divide modifiers into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level, but provides other functionality
For classes, you can use either public or default:
For attributes, methods and constructors, you can use the one of the
following:
For classes, you can use either final or abstract:
For attributes and methods, you can use the one of the
following:
If you don't want the ability to override existing attribute values, declare
attributes as final:
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
Try it Yourself »
A static method means that it can be
accessed without creating an object of the class, unlike public:
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method
}
}
Try it Yourself »
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:
// Code from filename: Main.java
// abstract classabstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Main)
class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
// End code from filename: Main.java
// Code from filename: Second.java
class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Main)
Student myObj = new Student();
System.out.println("Name: " + myObj.fname);
System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.study(); // call abstract method }
}
Try it Yourself »
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 100,
"s": 0,
"text": "By now, you are quite familiar with the public keyword that appears in almost \nall of our examples:"
},
{
"code": null,
"e": 119,
"s": 100,
"text": "public class Main\n"
},
{
"code": null,
"e": 262,
"s": 119,
"text": "The public keyword is an access modifier, \nmeaning that it is used to set the access level for classes, attributes, methods and \nconstructors."
},
{
"code": null,
"e": 299,
"s": 262,
"text": "We divide modifiers into two groups:"
},
{
"code": null,
"e": 344,
"s": 299,
"text": "Access Modifiers - controls the access level"
},
{
"code": null,
"e": 429,
"s": 344,
"text": "Non-Access Modifiers - do not control access level, but provides other functionality"
},
{
"code": null,
"e": 480,
"s": 429,
"text": "For classes, you can use either public or default:"
},
{
"code": null,
"e": 561,
"s": 480,
"text": "For attributes, methods and constructors, you can use the one of the \nfollowing:"
},
{
"code": null,
"e": 612,
"s": 561,
"text": "For classes, you can use either final or abstract:"
},
{
"code": null,
"e": 679,
"s": 612,
"text": "For attributes and methods, you can use the one of the \nfollowing:"
},
{
"code": null,
"e": 778,
"s": 679,
"text": "If you don't want the ability to override existing attribute values, declare \nattributes as final:"
},
{
"code": null,
"e": 1136,
"s": 778,
"text": "public class Main {\n final int x = 10;\n final double PI = 3.14;\n\n public static void main(String[] args) {\n Main myObj = new Main();\n myObj.x = 50; // will generate an error: cannot assign a value to a final variable\n myObj.PI = 25; // will generate an error: cannot assign a value to a final variable\n System.out.println(myObj.x);\n }\n}\n \n \n"
},
{
"code": null,
"e": 1156,
"s": 1136,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1259,
"s": 1156,
"text": "A static method means that it can be \naccessed without creating an object of the class, unlike public:"
},
{
"code": null,
"e": 1336,
"s": 1259,
"text": "An example to demonstrate the differences between static and public methods:"
},
{
"code": null,
"e": 1912,
"s": 1336,
"text": "public class Main {\n // Static method\n static void myStaticMethod() {\n System.out.println(\"Static methods can be called without creating objects\");\n }\n\n // Public method\n public void myPublicMethod() {\n System.out.println(\"Public methods must be called by creating objects\");\n }\n\n // Main method\n public static void main(String[ ] args) {\n myStaticMethod(); // Call the static method\n // myPublicMethod(); This would output an error\n\n Main myObj = new Main(); // Create an object of Main\n myObj.myPublicMethod(); // Call the public method\n }\n}\n \n \n"
},
{
"code": null,
"e": 1932,
"s": 1912,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2049,
"s": 1932,
"text": "An abstract method belongs to an abstract class, and it does not have a body. \nThe body is provided by the subclass:"
},
{
"code": null,
"e": 2936,
"s": 2049,
"text": "// Code from filename: Main.java\n// abstract classabstract class Main {\n public String fname = \"John\";\n public int age = 24;\n public abstract void study(); // abstract method\n}\n\n// Subclass (inherit from Main)\nclass Student extends Main {\n public int graduationYear = 2018;\n public void study() { // the body of the abstract method is provided here\n System.out.println(\"Studying all day long\");\n }\n}\n// End code from filename: Main.java\n\n// Code from filename: Second.java\nclass Second {\n public static void main(String[] args) {\n // create an object of the Student class (which inherits attributes and methods from Main)\n Student myObj = new Student();\n\n System.out.println(\"Name: \" + myObj.fname);\n System.out.println(\"Age: \" + myObj.age);\n System.out.println(\"Graduation Year: \" + myObj.graduationYear);\n myObj.study(); // call abstract method }\n}\n \n \n \n"
},
{
"code": null,
"e": 2956,
"s": 2936,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2989,
"s": 2956,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3031,
"s": 2989,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3138,
"s": 3031,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3157,
"s": 3138,
"text": "[email protected]"
}
]
|
Splitting an object into an array of objects in JavaScript | Suppose, we have an object like this −
const obj = {
"value 0": "value",
"value 1": "value",
"value 2": "value",
"value 3": "value",
"value 4": "value",
"value 5": "value",
"value 6": "value",
"value 7": "value",
"value 8": "value",
"value 9": "value"
};
We are required to write a JavaScript function that takes in one such object. The function should return a new array of objects in which each key/value pair is separated into its own separate object.
The code for this will be −
const obj = {
"value 0": "value",
"value 1": "value",
"value 2": "value",
"value 3": "value",
"value 4": "value",
"value 5": "value",
"value 6": "value",
"value 7": "value",
"value 8": "value",
"value 9": "value"
};
const separateObject = obj => {
const res = [];
const keys = Object.keys(obj);
keys.forEach(key => {
res.push({
key: obj[key]
});
});
return res;
};
console.log(separateObject(obj));
And the output in the console will be −
[
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' },
{ key: 'value' }
] | [
{
"code": null,
"e": 1101,
"s": 1062,
"text": "Suppose, we have an object like this −"
},
{
"code": null,
"e": 1347,
"s": 1101,
"text": "const obj = {\n \"value 0\": \"value\",\n \"value 1\": \"value\",\n \"value 2\": \"value\",\n \"value 3\": \"value\",\n \"value 4\": \"value\",\n \"value 5\": \"value\",\n \"value 6\": \"value\",\n \"value 7\": \"value\",\n \"value 8\": \"value\",\n \"value 9\": \"value\"\n};"
},
{
"code": null,
"e": 1547,
"s": 1347,
"text": "We are required to write a JavaScript function that takes in one such object. The function should return a new array of objects in which each key/value pair is separated into its own separate object."
},
{
"code": null,
"e": 1575,
"s": 1547,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2040,
"s": 1575,
"text": "const obj = {\n \"value 0\": \"value\",\n \"value 1\": \"value\",\n \"value 2\": \"value\",\n \"value 3\": \"value\",\n \"value 4\": \"value\",\n \"value 5\": \"value\",\n \"value 6\": \"value\",\n \"value 7\": \"value\",\n \"value 8\": \"value\",\n \"value 9\": \"value\"\n};\nconst separateObject = obj => {\n const res = [];\n const keys = Object.keys(obj);\n keys.forEach(key => {\n res.push({\n key: obj[key]\n });\n });\n return res;\n};\nconsole.log(separateObject(obj));"
},
{
"code": null,
"e": 2080,
"s": 2040,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2293,
"s": 2080,
"text": "[\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' },\n { key: 'value' }\n]"
}
]
|
Creating dictionary of sets in Python - GeeksforGeeks | 24 Oct, 2021
In this article, we will discuss how to create a dictionary of sets in Python.
We can create a dictionary of sets by passing sets as values to the keys.
Syntax:
{ ‘Key’: Set 1, ‘Key’:Set 2,..............,’Key’: Set n}
Example: Python program to create a dictionary of sets for student details
Python3
# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # displayprint(data)
Output:
{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}
As per definition, a set will not allow duplicates.
Example 2: Python program to show that it will not allow duplicates
Python3
# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5, 1, 2, 3, 2}, 'Student Aadhar No': {11, 22, 33, 44, 55, 22, 33, 44, 11}} # displayprint(data)
Output:
{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}
Here, in this approach, we are going to create a default set and then pass the key values to it.
Syntax:
defaultdict(set)
Syntax to pass the dictionary with key and value:
dictinary_name[“key”] |= {‘value1’, ‘value2′, ...............,’value n’}
where,
dictionary_name is the input dictionary
key is the key
values are the set
Example: Python code to create a dictionary of sets of student data
Python3
# import defaultdict modulefrom collections import defaultdict # create an empty set of dictionarydictionary = defaultdict(set) # enter key value pair 1dictionary["Student Roll-no"] |= {1, 2, 3, 4, 5} # ennter key value pair 2dictionary["Student Aadhar No"] |= {11, 22, 33, 44, 55} # displaydictionary
Output:
defaultdict(set,
{‘Student Aadhar No’: {11, 22, 33, 44, 55},
‘Student Roll-no’: {1, 2, 3, 4, 5}})
The setdefault() method returns the value of a key in the dictionary. If not, it inserts a key with a value to the dictionary.
Syntax:
dict.setdefault(key, default_value)
where,
key – Key to being searched in the dictionary.
default_value is the value of a particular key
Example: Python program to insert student names set into the dictionary
Python3
# Dictionary with student datadata = {'Student No': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student Aadhar No')) # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student No')) # set the third set using setdefault method for # student namesdata = data.setdefault( 'Student Names', {'sravan', 'gopi', 'ramya', 'durga', 'sudheer'}) # displaydata
Output:
{33, 11, 44, 22, 55}
{1, 2, 3, 4, 5}
{‘durga’, ‘gopi’, ‘ramya’, ‘sravan’, ‘sudheer’}
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 24371,
"s": 24292,
"text": "In this article, we will discuss how to create a dictionary of sets in Python."
},
{
"code": null,
"e": 24445,
"s": 24371,
"text": "We can create a dictionary of sets by passing sets as values to the keys."
},
{
"code": null,
"e": 24453,
"s": 24445,
"text": "Syntax:"
},
{
"code": null,
"e": 24510,
"s": 24453,
"text": "{ ‘Key’: Set 1, ‘Key’:Set 2,..............,’Key’: Set n}"
},
{
"code": null,
"e": 24585,
"s": 24510,
"text": "Example: Python program to create a dictionary of sets for student details"
},
{
"code": null,
"e": 24593,
"s": 24585,
"text": "Python3"
},
{
"code": "# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # displayprint(data)",
"e": 24759,
"s": 24593,
"text": null
},
{
"code": null,
"e": 24767,
"s": 24759,
"text": "Output:"
},
{
"code": null,
"e": 24847,
"s": 24767,
"text": "{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}"
},
{
"code": null,
"e": 24899,
"s": 24847,
"text": "As per definition, a set will not allow duplicates."
},
{
"code": null,
"e": 24967,
"s": 24899,
"text": "Example 2: Python program to show that it will not allow duplicates"
},
{
"code": null,
"e": 24975,
"s": 24967,
"text": "Python3"
},
{
"code": "# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5, 1, 2, 3, 2}, 'Student Aadhar No': {11, 22, 33, 44, 55, 22, 33, 44, 11}} # displayprint(data)",
"e": 25198,
"s": 24975,
"text": null
},
{
"code": null,
"e": 25206,
"s": 25198,
"text": "Output:"
},
{
"code": null,
"e": 25286,
"s": 25206,
"text": "{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}"
},
{
"code": null,
"e": 25383,
"s": 25286,
"text": "Here, in this approach, we are going to create a default set and then pass the key values to it."
},
{
"code": null,
"e": 25391,
"s": 25383,
"text": "Syntax:"
},
{
"code": null,
"e": 25408,
"s": 25391,
"text": "defaultdict(set)"
},
{
"code": null,
"e": 25458,
"s": 25408,
"text": "Syntax to pass the dictionary with key and value:"
},
{
"code": null,
"e": 25531,
"s": 25458,
"text": "dictinary_name[“key”] |= {‘value1’, ‘value2′, ...............,’value n’}"
},
{
"code": null,
"e": 25538,
"s": 25531,
"text": "where,"
},
{
"code": null,
"e": 25578,
"s": 25538,
"text": "dictionary_name is the input dictionary"
},
{
"code": null,
"e": 25593,
"s": 25578,
"text": "key is the key"
},
{
"code": null,
"e": 25612,
"s": 25593,
"text": "values are the set"
},
{
"code": null,
"e": 25680,
"s": 25612,
"text": "Example: Python code to create a dictionary of sets of student data"
},
{
"code": null,
"e": 25688,
"s": 25680,
"text": "Python3"
},
{
"code": "# import defaultdict modulefrom collections import defaultdict # create an empty set of dictionarydictionary = defaultdict(set) # enter key value pair 1dictionary[\"Student Roll-no\"] |= {1, 2, 3, 4, 5} # ennter key value pair 2dictionary[\"Student Aadhar No\"] |= {11, 22, 33, 44, 55} # displaydictionary",
"e": 25994,
"s": 25688,
"text": null
},
{
"code": null,
"e": 26002,
"s": 25994,
"text": "Output:"
},
{
"code": null,
"e": 26019,
"s": 26002,
"text": "defaultdict(set,"
},
{
"code": null,
"e": 26075,
"s": 26019,
"text": " {‘Student Aadhar No’: {11, 22, 33, 44, 55},"
},
{
"code": null,
"e": 26125,
"s": 26075,
"text": " ‘Student Roll-no’: {1, 2, 3, 4, 5}})"
},
{
"code": null,
"e": 26252,
"s": 26125,
"text": "The setdefault() method returns the value of a key in the dictionary. If not, it inserts a key with a value to the dictionary."
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Syntax:"
},
{
"code": null,
"e": 26296,
"s": 26260,
"text": "dict.setdefault(key, default_value)"
},
{
"code": null,
"e": 26303,
"s": 26296,
"text": "where,"
},
{
"code": null,
"e": 26350,
"s": 26303,
"text": "key – Key to being searched in the dictionary."
},
{
"code": null,
"e": 26397,
"s": 26350,
"text": "default_value is the value of a particular key"
},
{
"code": null,
"e": 26469,
"s": 26397,
"text": "Example: Python program to insert student names set into the dictionary"
},
{
"code": null,
"e": 26477,
"s": 26469,
"text": "Python3"
},
{
"code": "# Dictionary with student datadata = {'Student No': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student Aadhar No')) # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student No')) # set the third set using setdefault method for # student namesdata = data.setdefault( 'Student Names', {'sravan', 'gopi', 'ramya', 'durga', 'sudheer'}) # displaydata",
"e": 27002,
"s": 26477,
"text": null
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Output:"
},
{
"code": null,
"e": 27031,
"s": 27010,
"text": "{33, 11, 44, 22, 55}"
},
{
"code": null,
"e": 27047,
"s": 27031,
"text": "{1, 2, 3, 4, 5}"
},
{
"code": null,
"e": 27095,
"s": 27047,
"text": "{‘durga’, ‘gopi’, ‘ramya’, ‘sravan’, ‘sudheer’}"
},
{
"code": null,
"e": 27102,
"s": 27095,
"text": "Picked"
},
{
"code": null,
"e": 27129,
"s": 27102,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27141,
"s": 27129,
"text": "python-dict"
},
{
"code": null,
"e": 27148,
"s": 27141,
"text": "Python"
},
{
"code": null,
"e": 27164,
"s": 27148,
"text": "Python Programs"
},
{
"code": null,
"e": 27176,
"s": 27164,
"text": "python-dict"
},
{
"code": null,
"e": 27274,
"s": 27176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27283,
"s": 27274,
"text": "Comments"
},
{
"code": null,
"e": 27296,
"s": 27283,
"text": "Old Comments"
},
{
"code": null,
"e": 27328,
"s": 27296,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27384,
"s": 27328,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27439,
"s": 27384,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27481,
"s": 27439,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27523,
"s": 27481,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27545,
"s": 27523,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27591,
"s": 27545,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27630,
"s": 27591,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27668,
"s": 27630,
"text": "Python | Convert a list to dictionary"
}
]
|
How to a plot stem plot in Matplotlib Python? | To plot a stem plot in Matplotlib, we can use stem() method. It creates vertical lines from a baseline to the Y-coordinate and places a marker at the tip.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create a stem plot using stem() method.
Set the marker face color with red color.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0.1, 2 * np.pi, 41)
y = np.exp(np.sin(x))
markerline, stemlines, baseline = plt.stem(x, y, linefmt='grey', markerfmt='*', bottom=1.1)
markerline.set_markerfacecolor('red')
plt.show() | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "To plot a stem plot in Matplotlib, we can use stem() method. It creates vertical lines from a baseline to the Y-coordinate and places a marker at the tip."
},
{
"code": null,
"e": 1293,
"s": 1217,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1333,
"s": 1293,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1373,
"s": 1333,
"text": "Create a stem plot using stem() method."
},
{
"code": null,
"e": 1415,
"s": 1373,
"text": "Set the marker face color with red color."
},
{
"code": null,
"e": 1457,
"s": 1415,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1799,
"s": 1457,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(0.1, 2 * np.pi, 41)\ny = np.exp(np.sin(x))\n\nmarkerline, stemlines, baseline = plt.stem(x, y, linefmt='grey', markerfmt='*', bottom=1.1)\n\nmarkerline.set_markerfacecolor('red')\n\nplt.show()"
}
]
|
Output of Java Program | Set 2 - GeeksforGeeks | 18 May, 2021
Predict the output of the following Java programs.
Question 1:
Java
package main; class Base { public void Print() { System.out.println("Base"); }} class Derived extends Base { public void Print() { System.out.println("Derived"); }} class Main { public static void DoPrint(Base o) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Derived(); Derived z = new Derived(); DoPrint(x); DoPrint(y); DoPrint(z); }}
Output:
Base
Derived
Derived
Predicting the first line of output is easy. We create an object of type Base and call DoPrint(). DoPrint calls the print function and we get the first line.
DoPrint(y) causes the second line of output. Like C++, assigning a derived class reference to a base class reference is allowed in Java. Therefore, the expression Base y = new Derived() is a valid statement in Java. In DoPrint(), o starts referring to the same object as referred by y. Also, unlike C++, functions are virtual by default in Java. So, when we call o.print(), the print() method of Derived class is called due to run time polymorphism present by default in Java.
DoPrint(z) causes the third line of output, we pass a reference of Derived type and the print() method of Derived class is called again. The point to note here is: unlike C++, object slicing doesn’t happen in Java. Because non-primitive types are always assigned by reference.
Question 2:
Java
package main; // filename Main.javaclass Point { protected int x, y; public Point(int _x, int _y) { x = _x; y = _y; }} public class Main { public static void main(String args[]) { Point p = new Point(); System.out.println("x = " + p.x + ", y = " + p.y); }}
Output:
Compiler Error
In the above program, there are no access permission issues because the Point and Main are in the same package and protected members of a class can be accessed in other classes of the same package. The problem with the code is: there is no default constructor in Point.
Like C++, if we write our own parameterized constructor then Java compiler doesn’t create the default constructor. So there are following two changes to Point class that can fix the above program.
Remove the parameterized constructor.Add a constructor without any parameter.
Remove the parameterized constructor.
Add a constructor without any parameter.
Java doesn’t support default arguments, so that is not an option.Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.
BHAVY_PRATAP
saurabh1990aror
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Arrow operator -> in C/C++ with Examples
Output of Java Program | Set 1
delete keyword in C++
Output of C Programs | Set 1
Different ways to copy a string in C/C++ | [
{
"code": null,
"e": 25693,
"s": 25665,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 25745,
"s": 25693,
"text": "Predict the output of the following Java programs. "
},
{
"code": null,
"e": 25758,
"s": 25745,
"text": "Question 1: "
},
{
"code": null,
"e": 25763,
"s": 25758,
"text": "Java"
},
{
"code": "package main; class Base { public void Print() { System.out.println(\"Base\"); }} class Derived extends Base { public void Print() { System.out.println(\"Derived\"); }} class Main { public static void DoPrint(Base o) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Derived(); Derived z = new Derived(); DoPrint(x); DoPrint(y); DoPrint(z); }}",
"e": 26242,
"s": 25763,
"text": null
},
{
"code": null,
"e": 26251,
"s": 26242,
"text": "Output: "
},
{
"code": null,
"e": 26272,
"s": 26251,
"text": "Base\nDerived\nDerived"
},
{
"code": null,
"e": 26430,
"s": 26272,
"text": "Predicting the first line of output is easy. We create an object of type Base and call DoPrint(). DoPrint calls the print function and we get the first line."
},
{
"code": null,
"e": 26908,
"s": 26430,
"text": "DoPrint(y) causes the second line of output. Like C++, assigning a derived class reference to a base class reference is allowed in Java. Therefore, the expression Base y = new Derived() is a valid statement in Java. In DoPrint(), o starts referring to the same object as referred by y. Also, unlike C++, functions are virtual by default in Java. So, when we call o.print(), the print() method of Derived class is called due to run time polymorphism present by default in Java. "
},
{
"code": null,
"e": 27186,
"s": 26908,
"text": "DoPrint(z) causes the third line of output, we pass a reference of Derived type and the print() method of Derived class is called again. The point to note here is: unlike C++, object slicing doesn’t happen in Java. Because non-primitive types are always assigned by reference. "
},
{
"code": null,
"e": 27200,
"s": 27186,
"text": "Question 2: "
},
{
"code": null,
"e": 27205,
"s": 27200,
"text": "Java"
},
{
"code": "package main; // filename Main.javaclass Point { protected int x, y; public Point(int _x, int _y) { x = _x; y = _y; }} public class Main { public static void main(String args[]) { Point p = new Point(); System.out.println(\"x = \" + p.x + \", y = \" + p.y); }}",
"e": 27512,
"s": 27205,
"text": null
},
{
"code": null,
"e": 27521,
"s": 27512,
"text": "Output: "
},
{
"code": null,
"e": 27536,
"s": 27521,
"text": "Compiler Error"
},
{
"code": null,
"e": 27807,
"s": 27536,
"text": "In the above program, there are no access permission issues because the Point and Main are in the same package and protected members of a class can be accessed in other classes of the same package. The problem with the code is: there is no default constructor in Point. "
},
{
"code": null,
"e": 28005,
"s": 27807,
"text": "Like C++, if we write our own parameterized constructor then Java compiler doesn’t create the default constructor. So there are following two changes to Point class that can fix the above program. "
},
{
"code": null,
"e": 28083,
"s": 28005,
"text": "Remove the parameterized constructor.Add a constructor without any parameter."
},
{
"code": null,
"e": 28121,
"s": 28083,
"text": "Remove the parameterized constructor."
},
{
"code": null,
"e": 28162,
"s": 28121,
"text": "Add a constructor without any parameter."
},
{
"code": null,
"e": 28373,
"s": 28162,
"text": "Java doesn’t support default arguments, so that is not an option.Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above. "
},
{
"code": null,
"e": 28386,
"s": 28373,
"text": "BHAVY_PRATAP"
},
{
"code": null,
"e": 28402,
"s": 28386,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28414,
"s": 28402,
"text": "Java-Output"
},
{
"code": null,
"e": 28419,
"s": 28414,
"text": "Java"
},
{
"code": null,
"e": 28434,
"s": 28419,
"text": "Program Output"
},
{
"code": null,
"e": 28439,
"s": 28434,
"text": "Java"
},
{
"code": null,
"e": 28537,
"s": 28439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28552,
"s": 28537,
"text": "Stream In Java"
},
{
"code": null,
"e": 28571,
"s": 28552,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28589,
"s": 28571,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28609,
"s": 28589,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28633,
"s": 28609,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28674,
"s": 28633,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28705,
"s": 28674,
"text": "Output of Java Program | Set 1"
},
{
"code": null,
"e": 28727,
"s": 28705,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 28756,
"s": 28727,
"text": "Output of C Programs | Set 1"
}
]
|
How to find min/max values without Math functions in JavaScript ? - GeeksforGeeks | 09 Nov, 2021
In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed.
Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the numbers present in the array to find maximum and minimum values inside the array.
We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value. Thus, using the loop function, we can get the maximum and minimum values entered in an array/list.
The below example will demonstrate the above approach.
Example:
JavaScript
<script> // Array of numbers where the maximum // and minimum are to be found const array = [-1, 2, -5, 8, 16]; // Setting a number of the given array as // value of max and min we choose 0th index // element as atleast one element should be // present in the given array let max = array[0], min = array[0]; for (let i = 0; i < array.length; i++) { // If we get any element in array greater // than max, max takes value of that // larger number if (array[i] > max) { max = array[i]; } // If we get any element in array smaller // than min, min takes value of that // smaller number if (array[i] < min) { min = array[i]; } } console.log("max = " + max); console.log("min = " + min);</script>
Output: The maximum and the minimum number of the array is found using the approach.
max = 16
min = -5
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 26785,
"s": 26545,
"text": "In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed."
},
{
"code": null,
"e": 26976,
"s": 26785,
"text": "Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the numbers present in the array to find maximum and minimum values inside the array."
},
{
"code": null,
"e": 27395,
"s": 26976,
"text": "We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value. Thus, using the loop function, we can get the maximum and minimum values entered in an array/list."
},
{
"code": null,
"e": 27450,
"s": 27395,
"text": "The below example will demonstrate the above approach."
},
{
"code": null,
"e": 27459,
"s": 27450,
"text": "Example:"
},
{
"code": null,
"e": 27470,
"s": 27459,
"text": "JavaScript"
},
{
"code": "<script> // Array of numbers where the maximum // and minimum are to be found const array = [-1, 2, -5, 8, 16]; // Setting a number of the given array as // value of max and min we choose 0th index // element as atleast one element should be // present in the given array let max = array[0], min = array[0]; for (let i = 0; i < array.length; i++) { // If we get any element in array greater // than max, max takes value of that // larger number if (array[i] > max) { max = array[i]; } // If we get any element in array smaller // than min, min takes value of that // smaller number if (array[i] < min) { min = array[i]; } } console.log(\"max = \" + max); console.log(\"min = \" + min);</script>",
"e": 28263,
"s": 27470,
"text": null
},
{
"code": null,
"e": 28348,
"s": 28263,
"text": "Output: The maximum and the minimum number of the array is found using the approach."
},
{
"code": null,
"e": 28366,
"s": 28348,
"text": "max = 16\nmin = -5"
},
{
"code": null,
"e": 28387,
"s": 28366,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28394,
"s": 28387,
"text": "Picked"
},
{
"code": null,
"e": 28405,
"s": 28394,
"text": "JavaScript"
},
{
"code": null,
"e": 28422,
"s": 28405,
"text": "Web Technologies"
},
{
"code": null,
"e": 28520,
"s": 28422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28560,
"s": 28520,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28621,
"s": 28560,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28662,
"s": 28621,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28684,
"s": 28662,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28738,
"s": 28684,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28778,
"s": 28738,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28811,
"s": 28778,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28854,
"s": 28811,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28904,
"s": 28854,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to Get Bank Details from IFSC Code in Android? - GeeksforGeeks | 15 Jan, 2021
Many apps such as the E-commerce app requires to accept payments from their users for providing different products or services or for their users. So this apps requires the users to enter bank details for payments. In this payment gateway, users are asked to add their banks IFSC code to get the details of their banks. So many apps have features inside their app that while entering the bank IFSC code the user’s bank details such as Bank address, bank city, and other common details are fetched from that IFSC code. So in this article, we will take a look at How we can get the common bank details from the IFSC code in Android.
We will be building a simple application in which we will be getting IFSC code from the user via an EditText and after that, the user has to click on a simple button to get the data from that IFSC code such as Bank address, bank MICR code, contact number, and other details. For performing this task we will be using a simple API which we will be added to our application. This application will provide us the basic data from API which is related to the bank. Below is the GIF image in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language.
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. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
implementation ‘com.android.volley:volley:1.1.1’
After adding this dependency sync your project and now move toward the XML part.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--heading text view--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="IFSC Code Validator" android:textAlignment="center" android:textColor="@color/purple_500" android:textSize="30sp" /> <!-- edit text for entering our IFSC code we are specifying input type as number and we are also mentioning our input type as textcapCharacters because IFSC code is having all capital characters--> <EditText android:id="@+id/idedtIfscCode" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:hint="Enter IFSC code" android:importantForAutofill="no" android:inputType="textCapCharacters" android:maxLines="1" android:singleLine="true" android:textAllCaps="true" /> <!--button to get the data from IFSC code--> <Button android:id="@+id/idBtnGetBankDetails" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:text="Get Bank Details" android:textAllCaps="false" /> <!--text view to display the data received from IFSC code--> <TextView android:id="@+id/idTVBankDetails" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:padding="10dp" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/purple_500" android:textSize="15sp" /> </LinearLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for edit text // and our text views. private EditText ifscCodeEdt; private TextView bankDetailsTV; // creating a variable for // our ifsc code string. String ifscCode; // creating a variable for request queue. private RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. ifscCodeEdt = findViewById(R.id.idedtIfscCode); Button getBankDetailsBtn = findViewById(R.id.idBtnGetBankDetails); bankDetailsTV = findViewById(R.id.idTVBankDetails); // initializing our request que variable with request queue // and passing our context to it. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // initialing on click listener for our button. getBankDetailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting string from edittext. ifscCode = ifscCodeEdt.getText().toString(); // validating if the edit text // is empty or not. if (TextUtils.isEmpty(ifscCode)) { // displaying a toast message if the text field is empty Toast.makeText(MainActivity.this, "Please enter valid IFSC code", Toast.LENGTH_SHORT).show(); } else { // calling a method to display // our ifsc code details. getDataFromIFSCCode(ifscCode); } } }); } private void getDataFromIFSCCode(String ifscCode) { // clearing our cache of request queue. mRequestQueue.getCache().clear(); // below is the url from where we will be getting // our response in the json format. String url = "http://api.techm.co.in/api/v1/ifsc/" + ifscCode; // below line is use to initialize our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // creating a json object request for our API. JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // this method is used to get // the response from the API. try { if (response.getString("status").equals("failed")) { // checking if the response is not loaded and // status for the repose is fail. // if response status is failure we are displaying // an invalid IFSC code in our text view. bankDetailsTV.setText("Invalid IFSC Code"); } else { // if the status is successful we are // extracting data from JSON file JSONObject dataObj = response.getJSONObject("data"); String state = dataObj.optString("STATE"); String bankName = dataObj.optString("BANK"); String branch = dataObj.optString("BRANCH"); String address = dataObj.optString("ADDRESS"); String contact = dataObj.optString("CONTACT"); String micrcode = dataObj.optString("MICRCODE"); String city = dataObj.optString("CITY"); // after extracting this data we are displaying // that data in our text view. bankDetailsTV.setText("Bank Name : " + bankName + "\nBranch : " + branch + "\nAddress : " + address + "\nMICR Code : " + micrcode + "\nCity : " + city + "\nState : " + state + "\nContact : " + contact); } } catch (JSONException e) { // if we get any error while loading data // we are setting our text as invalid IFSC code. e.printStackTrace(); bankDetailsTV.setText("Invalid IFSC Code"); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // if we get any error while loading json // data we are setting our text to invalid IFSC code. bankDetailsTV.setText("Invalid IFSC Code"); } }); // below line is use for adding object // request to our request queue. queue.add(objectRequest); }}
Step 5: Add permission for the internet in the Manifest file
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.
XML
<uses-permission android:name="android.permission.INTERNET"/>
After adding this permission. Run your project and see the output on the below screen.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n15 Jan, 2021"
},
{
"code": null,
"e": 27013,
"s": 26381,
"text": "Many apps such as the E-commerce app requires to accept payments from their users for providing different products or services or for their users. So this apps requires the users to enter bank details for payments. In this payment gateway, users are asked to add their banks IFSC code to get the details of their banks. So many apps have features inside their app that while entering the bank IFSC code the user’s bank details such as Bank address, bank city, and other common details are fetched from that IFSC code. So in this article, we will take a look at How we can get the common bank details from the IFSC code in Android. "
},
{
"code": null,
"e": 27643,
"s": 27013,
"text": "We will be building a simple application in which we will be getting IFSC code from the user via an EditText and after that, the user has to click on a simple button to get the data from that IFSC code such as Bank address, bank MICR code, contact number, and other details. For performing this task we will be using a simple API which we will be added to our application. This application will provide us the basic data from API which is related to the bank. Below is the GIF image in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 27690,
"s": 27643,
"text": "Step 1: Create a new project in Android Studio"
},
{
"code": null,
"e": 27852,
"s": 27690,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27913,
"s": 27852,
"text": "Step 2: Add the below dependency in your build.gradle file "
},
{
"code": null,
"e": 28143,
"s": 27913,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 28192,
"s": 28143,
"text": "implementation ‘com.android.volley:volley:1.1.1’"
},
{
"code": null,
"e": 28275,
"s": 28192,
"text": "After adding this dependency sync your project and now move toward the XML part. "
},
{
"code": null,
"e": 28323,
"s": 28275,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28439,
"s": 28323,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 28443,
"s": 28439,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--heading text view--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:text=\"IFSC Code Validator\" android:textAlignment=\"center\" android:textColor=\"@color/purple_500\" android:textSize=\"30sp\" /> <!-- edit text for entering our IFSC code we are specifying input type as number and we are also mentioning our input type as textcapCharacters because IFSC code is having all capital characters--> <EditText android:id=\"@+id/idedtIfscCode\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:hint=\"Enter IFSC code\" android:importantForAutofill=\"no\" android:inputType=\"textCapCharacters\" android:maxLines=\"1\" android:singleLine=\"true\" android:textAllCaps=\"true\" /> <!--button to get the data from IFSC code--> <Button android:id=\"@+id/idBtnGetBankDetails\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"50dp\" android:text=\"Get Bank Details\" android:textAllCaps=\"false\" /> <!--text view to display the data received from IFSC code--> <TextView android:id=\"@+id/idTVBankDetails\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:padding=\"10dp\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/purple_500\" android:textSize=\"15sp\" /> </LinearLayout>",
"e": 30538,
"s": 28443,
"text": null
},
{
"code": null,
"e": 30586,
"s": 30538,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30776,
"s": 30586,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30781,
"s": 30776,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for edit text // and our text views. private EditText ifscCodeEdt; private TextView bankDetailsTV; // creating a variable for // our ifsc code string. String ifscCode; // creating a variable for request queue. private RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. ifscCodeEdt = findViewById(R.id.idedtIfscCode); Button getBankDetailsBtn = findViewById(R.id.idBtnGetBankDetails); bankDetailsTV = findViewById(R.id.idTVBankDetails); // initializing our request que variable with request queue // and passing our context to it. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // initialing on click listener for our button. getBankDetailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting string from edittext. ifscCode = ifscCodeEdt.getText().toString(); // validating if the edit text // is empty or not. if (TextUtils.isEmpty(ifscCode)) { // displaying a toast message if the text field is empty Toast.makeText(MainActivity.this, \"Please enter valid IFSC code\", Toast.LENGTH_SHORT).show(); } else { // calling a method to display // our ifsc code details. getDataFromIFSCCode(ifscCode); } } }); } private void getDataFromIFSCCode(String ifscCode) { // clearing our cache of request queue. mRequestQueue.getCache().clear(); // below is the url from where we will be getting // our response in the json format. String url = \"http://api.techm.co.in/api/v1/ifsc/\" + ifscCode; // below line is use to initialize our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // creating a json object request for our API. JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // this method is used to get // the response from the API. try { if (response.getString(\"status\").equals(\"failed\")) { // checking if the response is not loaded and // status for the repose is fail. // if response status is failure we are displaying // an invalid IFSC code in our text view. bankDetailsTV.setText(\"Invalid IFSC Code\"); } else { // if the status is successful we are // extracting data from JSON file JSONObject dataObj = response.getJSONObject(\"data\"); String state = dataObj.optString(\"STATE\"); String bankName = dataObj.optString(\"BANK\"); String branch = dataObj.optString(\"BRANCH\"); String address = dataObj.optString(\"ADDRESS\"); String contact = dataObj.optString(\"CONTACT\"); String micrcode = dataObj.optString(\"MICRCODE\"); String city = dataObj.optString(\"CITY\"); // after extracting this data we are displaying // that data in our text view. bankDetailsTV.setText(\"Bank Name : \" + bankName + \"\\nBranch : \" + branch + \"\\nAddress : \" + address + \"\\nMICR Code : \" + micrcode + \"\\nCity : \" + city + \"\\nState : \" + state + \"\\nContact : \" + contact); } } catch (JSONException e) { // if we get any error while loading data // we are setting our text as invalid IFSC code. e.printStackTrace(); bankDetailsTV.setText(\"Invalid IFSC Code\"); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // if we get any error while loading json // data we are setting our text to invalid IFSC code. bankDetailsTV.setText(\"Invalid IFSC Code\"); } }); // below line is use for adding object // request to our request queue. queue.add(objectRequest); }}",
"e": 36224,
"s": 30781,
"text": null
},
{
"code": null,
"e": 36286,
"s": 36224,
"text": "Step 5: Add permission for the internet in the Manifest file "
},
{
"code": null,
"e": 36371,
"s": 36286,
"text": "Navigate to the app > AndroidManifest.xml file and add the below permissions to it. "
},
{
"code": null,
"e": 36375,
"s": 36371,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.INTERNET\"/>",
"e": 36437,
"s": 36375,
"text": null
},
{
"code": null,
"e": 36526,
"s": 36437,
"text": "After adding this permission. Run your project and see the output on the below screen. "
},
{
"code": null,
"e": 36534,
"s": 36526,
"text": "android"
},
{
"code": null,
"e": 36558,
"s": 36534,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36566,
"s": 36558,
"text": "Android"
},
{
"code": null,
"e": 36571,
"s": 36566,
"text": "Java"
},
{
"code": null,
"e": 36590,
"s": 36571,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36595,
"s": 36590,
"text": "Java"
},
{
"code": null,
"e": 36603,
"s": 36595,
"text": "Android"
},
{
"code": null,
"e": 36701,
"s": 36603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36739,
"s": 36701,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 36778,
"s": 36739,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36828,
"s": 36778,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36870,
"s": 36828,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36921,
"s": 36870,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 36936,
"s": 36921,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36980,
"s": 36936,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37002,
"s": 36980,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37053,
"s": 37002,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
]
|
Power of 3 | Practice | GeeksforGeeks | Given a number N, the task is to count the numbers in the range [1, N] which can be represented as power of 3.
Note: 1 can be represented as the power of 3.
Input:
1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains single integer N.
Output: For each test case, print the answer
Constraints:
1. 1 <= T <= 104
2. 1 <= N <= 109
Example:
Input:
2
6
1
Output:
2
1
+2
chechipresh3 months ago
C++ solution:
#include <iostream>using namespace std;
class Solution{ public: long long int count(long long int n) { long long int i,ans=0; for (i=1;i<=n;i=i*3){ ans++; } return ans; }};
int main() { int t; cin>>t; long long int n,ans; while (t--) { cin>>n; Solution ob; ans=ob.count(n); cout<<ans<<endl; } return 0;}
+1
ankitparashxr3 months ago
java
Scanner sc = new Scanner(System.in); int t =sc.nextInt(); while(t!=0) { int n = sc.nextInt(); int count = 0; for(int i = 0;i<n;i++) { int mul = (int)Math.pow(3,i); if(mul<=n) { count++; } else if(mul>n) { break; } } System.out.println(count); t--;
0
chessnoobdj4 months ago
C++ O(1)
Size of pref is 20 only, so lower_bound and binary search both these operations cost O(1) time only
#include<iostream>
#include<algorithm>
const long MAX = 1e10;
int pref[20]; // 10^9 = 3^k (k~20)
void precompute(){
long int num = 1, i = 0;
while(num < MAX){
pref[i] = num;
i += 1;
num *= 3;
}
}
int main(){
int t;
std::cin >> t;
while(t--){
precompute();
int n;
std::cin >> n;
int ans = std::lower_bound(pref, pref+20, n)-pref;
if(std::binary_search(pref, pref+20, n))
ans += 1;
std::cout << ans << std::endl;
}
}
0
himanshujain4574 months ago
CORRECTED:
#include <iostream>using namespace std;#include<bits/stdc++.h>void solve(){ int n; cin>>n; int i=0; int temp=0; vector<int>v; while(temp<=n) { temp=pow(3,i); v.push_back(temp); i++; } cout<<v.size()-1<<endl;}int main() {int t;cin>>t;while(t--)solve();return 0;}
-1
shubhanshud96 months ago
#include <iostream>using namespace std;
int main() { int t; cin>>t; int count=1; while(t--) { int n; cin>>n; int count=1; for(int i=3;i<=n;i=i*3) { count++; } cout<<count<<endl; }return 0;}
0
e20040807 months ago
runtime: 0.1/7.6
import math
for i in range(int(input())):
print(int(math.log(int(input()), 3))+1)
0
msaravanansara4747 months ago
for _ in range(int(input())):
N=int(input())
co=0
total=0
while 3**co<=N:
total+=1
co+=1
print(total)
-1
pawan16087 months ago
Here the logic is n ≤3 to the power of x....Here x means number of digit who 3 to the power up to n.
#include<bits/stdc++.h>
using namespace std;
int main() {
//code
int t; cin>>t;
while(t--){
int n; cin>>n;
n = log(n)/log(3);
cout<<n+1<<endl;
}
return 0;
}
-2
ankitsinha1112008 months ago
0
Manish Patil10 months ago
Manish Patil
#include <bits stdc++.h="">using namespace std;
int main() {
int T;cin>>T;
while(T--){ int N; cin>>N;
cout<<int(log(n) log(3)="" +="" 1)<<endl;="" }="" return="" 0;="" }="">
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": 385,
"s": 226,
"text": "Given a number N, the task is to count the numbers in the range [1, N] which can be represented as power of 3.\n\nNote: 1 can be represented as the power of 3. "
},
{
"code": null,
"e": 592,
"s": 385,
"text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains single integer N."
},
{
"code": null,
"e": 709,
"s": 592,
"text": "\nOutput: For each test case, print the answer\n\nConstraints:\n1. 1 <= T <= 104\n2. 1 <= N <= 109\n\nExample:\nInput:\n2\n6\n1"
},
{
"code": null,
"e": 721,
"s": 709,
"text": "Output:\n2\n1"
},
{
"code": null,
"e": 724,
"s": 721,
"text": "+2"
},
{
"code": null,
"e": 748,
"s": 724,
"text": "chechipresh3 months ago"
},
{
"code": null,
"e": 762,
"s": 748,
"text": "C++ solution:"
},
{
"code": null,
"e": 802,
"s": 762,
"text": "#include <iostream>using namespace std;"
},
{
"code": null,
"e": 976,
"s": 802,
"text": "class Solution{ public: long long int count(long long int n) { long long int i,ans=0; for (i=1;i<=n;i=i*3){ ans++; } return ans; }};"
},
{
"code": null,
"e": 1147,
"s": 976,
"text": "int main() { int t; cin>>t; long long int n,ans; while (t--) { cin>>n; Solution ob; ans=ob.count(n); cout<<ans<<endl; } return 0;} "
},
{
"code": null,
"e": 1150,
"s": 1147,
"text": "+1"
},
{
"code": null,
"e": 1176,
"s": 1150,
"text": "ankitparashxr3 months ago"
},
{
"code": null,
"e": 1181,
"s": 1176,
"text": "java"
},
{
"code": null,
"e": 1556,
"s": 1181,
"text": "Scanner sc = new Scanner(System.in); int t =sc.nextInt(); while(t!=0) { int n = sc.nextInt(); int count = 0; for(int i = 0;i<n;i++) { int mul = (int)Math.pow(3,i); if(mul<=n) { count++; } else if(mul>n) { break; } } System.out.println(count); t--;"
},
{
"code": null,
"e": 1558,
"s": 1556,
"text": "0"
},
{
"code": null,
"e": 1582,
"s": 1558,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 1591,
"s": 1582,
"text": "C++ O(1)"
},
{
"code": null,
"e": 1691,
"s": 1591,
"text": "Size of pref is 20 only, so lower_bound and binary search both these operations cost O(1) time only"
},
{
"code": null,
"e": 2221,
"s": 1691,
"text": "#include<iostream>\n#include<algorithm>\n\nconst long MAX = 1e10;\nint pref[20]; // 10^9 = 3^k (k~20)\n\nvoid precompute(){\n long int num = 1, i = 0;\n while(num < MAX){\n pref[i] = num;\n i += 1;\n num *= 3;\n }\n}\n\nint main(){\n int t;\n std::cin >> t;\n while(t--){\n precompute();\n int n;\n std::cin >> n;\n int ans = std::lower_bound(pref, pref+20, n)-pref;\n if(std::binary_search(pref, pref+20, n))\n ans += 1;\n std::cout << ans << std::endl;\n }\n}"
},
{
"code": null,
"e": 2223,
"s": 2221,
"text": "0"
},
{
"code": null,
"e": 2251,
"s": 2223,
"text": "himanshujain4574 months ago"
},
{
"code": null,
"e": 2262,
"s": 2251,
"text": "CORRECTED:"
},
{
"code": null,
"e": 2560,
"s": 2262,
"text": "#include <iostream>using namespace std;#include<bits/stdc++.h>void solve(){ int n; cin>>n; int i=0; int temp=0; vector<int>v; while(temp<=n) { temp=pow(3,i); v.push_back(temp); i++; } cout<<v.size()-1<<endl;}int main() {int t;cin>>t;while(t--)solve();return 0;}"
},
{
"code": null,
"e": 2563,
"s": 2560,
"text": "-1"
},
{
"code": null,
"e": 2588,
"s": 2563,
"text": "shubhanshud96 months ago"
},
{
"code": null,
"e": 2628,
"s": 2588,
"text": "#include <iostream>using namespace std;"
},
{
"code": null,
"e": 2856,
"s": 2628,
"text": "int main() { int t; cin>>t; int count=1; while(t--) { int n; cin>>n; int count=1; for(int i=3;i<=n;i=i*3) { count++; } cout<<count<<endl; }return 0;}"
},
{
"code": null,
"e": 2858,
"s": 2856,
"text": "0"
},
{
"code": null,
"e": 2879,
"s": 2858,
"text": "e20040807 months ago"
},
{
"code": null,
"e": 2896,
"s": 2879,
"text": "runtime: 0.1/7.6"
},
{
"code": null,
"e": 2982,
"s": 2896,
"text": "import math\nfor i in range(int(input())):\n print(int(math.log(int(input()), 3))+1)"
},
{
"code": null,
"e": 2984,
"s": 2982,
"text": "0"
},
{
"code": null,
"e": 3014,
"s": 2984,
"text": "msaravanansara4747 months ago"
},
{
"code": null,
"e": 3152,
"s": 3014,
"text": "for _ in range(int(input())):\n N=int(input())\n co=0\n total=0\n while 3**co<=N:\n total+=1\n co+=1\n print(total)"
},
{
"code": null,
"e": 3155,
"s": 3152,
"text": "-1"
},
{
"code": null,
"e": 3177,
"s": 3155,
"text": "pawan16087 months ago"
},
{
"code": null,
"e": 3278,
"s": 3177,
"text": "Here the logic is n ≤3 to the power of x....Here x means number of digit who 3 to the power up to n."
},
{
"code": null,
"e": 3456,
"s": 3278,
"text": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\t//code\n\tint t; cin>>t;\n\twhile(t--){\n\t int n; cin>>n;\n\t n = log(n)/log(3);\n\t cout<<n+1<<endl;\n\t}\n\treturn 0;\n}"
},
{
"code": null,
"e": 3459,
"s": 3456,
"text": "-2"
},
{
"code": null,
"e": 3488,
"s": 3459,
"text": "ankitsinha1112008 months ago"
},
{
"code": null,
"e": 3490,
"s": 3488,
"text": "0"
},
{
"code": null,
"e": 3516,
"s": 3490,
"text": "Manish Patil10 months ago"
},
{
"code": null,
"e": 3529,
"s": 3516,
"text": "Manish Patil"
},
{
"code": null,
"e": 3577,
"s": 3529,
"text": "#include <bits stdc++.h=\"\">using namespace std;"
},
{
"code": null,
"e": 3590,
"s": 3577,
"text": "int main() {"
},
{
"code": null,
"e": 3604,
"s": 3590,
"text": "int T;cin>>T;"
},
{
"code": null,
"e": 3640,
"s": 3604,
"text": "while(T--){ int N; cin>>N;"
},
{
"code": null,
"e": 3716,
"s": 3640,
"text": " cout<<int(log(n) log(3)=\"\" +=\"\" 1)<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 3862,
"s": 3716,
"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": 3898,
"s": 3862,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3908,
"s": 3898,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3918,
"s": 3908,
"text": "\nContest\n"
},
{
"code": null,
"e": 3981,
"s": 3918,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4129,
"s": 3981,
"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": 4337,
"s": 4129,
"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": 4443,
"s": 4337,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Python | Pandas Series.set_value() - GeeksforGeeks | 05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.set_value() function is used to set value of the given series object using the index labels.
Syntax: Series.set_value(label, value, takeable=False)
Parameter :label : Partial indexing with MultiIndex not allowedvalue : Scalar valuetakeable : interpret the index as indexers, default False
Returns : series
Example #1: Use Series.set_value() function to set the value in the given series object using the index labels.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.set_value() function to set the value corresponding to the passed index label.
# set the valuesr.set_value('City 2', 'Dublin')
Output :
As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label. Example #2: Use Series.set_value() function to set the value in the given series object using the index labels.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr)
Output :
Now we will use Series.set_value() function to set the value in the given series object.
# set the value to 1000 of# the passed index labelsr.set_value(3, 1000)
Output :
As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 25794,
"s": 25537,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 25901,
"s": 25794,
"text": "Pandas Series.set_value() function is used to set value of the given series object using the index labels."
},
{
"code": null,
"e": 25956,
"s": 25901,
"text": "Syntax: Series.set_value(label, value, takeable=False)"
},
{
"code": null,
"e": 26097,
"s": 25956,
"text": "Parameter :label : Partial indexing with MultiIndex not allowedvalue : Scalar valuetakeable : interpret the index as indexers, default False"
},
{
"code": null,
"e": 26114,
"s": 26097,
"text": "Returns : series"
},
{
"code": null,
"e": 26226,
"s": 26114,
"text": "Example #1: Use Series.set_value() function to set the value in the given series object using the index labels."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 26522,
"s": 26226,
"text": null
},
{
"code": null,
"e": 26531,
"s": 26522,
"text": "Output :"
},
{
"code": null,
"e": 26633,
"s": 26531,
"text": "Now we will use Series.set_value() function to set the value corresponding to the passed index label."
},
{
"code": "# set the valuesr.set_value('City 2', 'Dublin')",
"e": 26681,
"s": 26633,
"text": null
},
{
"code": null,
"e": 26690,
"s": 26681,
"text": "Output :"
},
{
"code": null,
"e": 26921,
"s": 26690,
"text": "As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label. Example #2: Use Series.set_value() function to set the value in the given series object using the index labels."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr)",
"e": 27059,
"s": 26921,
"text": null
},
{
"code": null,
"e": 27068,
"s": 27059,
"text": "Output :"
},
{
"code": null,
"e": 27157,
"s": 27068,
"text": "Now we will use Series.set_value() function to set the value in the given series object."
},
{
"code": "# set the value to 1000 of# the passed index labelsr.set_value(3, 1000)",
"e": 27229,
"s": 27157,
"text": null
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "Output :"
},
{
"code": null,
"e": 27357,
"s": 27238,
"text": "As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label."
},
{
"code": null,
"e": 27378,
"s": 27357,
"text": "Python pandas-series"
},
{
"code": null,
"e": 27407,
"s": 27378,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 27421,
"s": 27407,
"text": "Python-pandas"
},
{
"code": null,
"e": 27428,
"s": 27421,
"text": "Python"
},
{
"code": null,
"e": 27526,
"s": 27428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27558,
"s": 27526,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27600,
"s": 27558,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27642,
"s": 27600,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27669,
"s": 27642,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27725,
"s": 27669,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27764,
"s": 27725,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27786,
"s": 27764,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27817,
"s": 27786,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27846,
"s": 27817,
"text": "Create a directory in Python"
}
]
|
Check if the array has an element which is equal to product of remaining elements - GeeksforGeeks | 25 Aug, 2021
Given an array of N elements, the task is to check if the array has an element which is equal to the product of all the remaining elements.
Examples:
Input: arr[] = {1, 2, 12, 3, 2}
Output: YES
12 is the product of all the remaining elements
i.e. 1 * 2 * 3 * 2 = 12
Input: arr[] = {1, 2, 3}
Output: NO
Method-1:
First, take the product of all the element of the array.Now traverse the whole array again.For any element a[i] check if it is equal to the product of all elements divided by that element.Print Yes if at least one such element is found.
First, take the product of all the element of the array.
Now traverse the whole array again.
For any element a[i] check if it is equal to the product of all elements divided by that element.
Print Yes if at least one such element is found.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to Check if the array// has an element which is equal to// product of all the remaining elementsbool CheckArray(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} int main(){ int arr[] = { 1, 2, 12, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (CheckArray(arr, n)) cout << "YES"; else cout << "NO"; return 0;}
// Java implementation of the above approach import java.io.*; class GFG { // Function to Check if the array// has an element which is equal to// product of all the remaining elementsstatic boolean CheckArray(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} public static void main (String[] args) { int arr[] = { 1, 2, 12, 3, 2 }; int n =arr.length; if (CheckArray(arr, n)) System.out.println("YES"); else System.out.println("NO"); }}// This code is contributed by shs..
# Python 3 implementation of the above approach # Function to Check if the array# has an element which is equal to# product of all the remaining elementsdef CheckArray(arr, n): prod = 1 # Calculate the product of all # the elements for i in range(0, n, 1): prod *= arr[i] # Return true if any such element # is found for i in range(0, n, 1): if (arr[i] == prod / arr[i]): return True # If no element is found return False # Driver codeif __name__ == '__main__': arr = [1, 2, 12, 3, 2] n = len(arr) if (CheckArray(arr, n)): print("YES") else: print("NO") # This code is contributed by# Surendra_Gangwar
// C# implementation of the above approachclass GFG{// Function to Check if the array// has an element which is equal to// product of all the remaining elementsstatic bool CheckArray(int[] arr, int n){ int prod = 1; // Calculate the product of // all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such // element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} // Driver Codepublic static void Main (){ int[] arr = new int[] { 1, 2, 12, 3, 2 }; int n = arr.Length; if (CheckArray(arr, n)) System.Console.WriteLine("YES"); else System.Console.WriteLine("NO");}} // This code is contributed by mits
<?php// PHP implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray($arr, $n){ $prod = 1; // Calculate the product of // all the elements for ($i = 0; $i < $n; ++$i) $prod *= $arr[$i]; // Return true if any such element // is found for ($i = 0; $i < $n; ++$i) if ($arr[$i] == $prod / $arr[$i]) return true; // If no element is found return false;} // Driver Code$arr = array(1, 2, 12, 3, 2);$n = sizeof($arr); if (CheckArray($arr, $n)) echo "YES";else echo "NO"; // This code is contributed// by Akanksha Rai
<script>// Java script implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray(arr,n){ let prod = 1; // Calculate the product of all the elements for (let i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (let i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} let arr = [ 1, 2, 12, 3, 2 ]; let n =arr.length; if (CheckArray(arr, n)) document.write("YES"); else document.write("NO"); // This code is contributed by sravan kumar Gottumukkala</script>
YES
Method-2: The approach is to find the product of all the elements of the array and check if it is a perfect square or not. If it is a perfect square then check if the square root of the product exists in the array or not. If exists then print Yes else print No.
According to the problem statement, a * b = N where b is the product of all the remaining elements of the array except a i.e arr[i] And it is also mentioned that find the index such that a = b. So, it simply means that a*a = N i.e. N is a perfect square. and a is its square root.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to Check if the array// has an element which is equal to// product of all the remaining elementsbool CheckArray(int arr[], int n){ int prod = 1; // Storing frequency in map unordered_set<int> freq; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.insert(arr[i]); prod *= arr[i]; } int root = sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not if (freq.find(root) != freq.end()) return true; return false;} // Driver codeint main(){ int arr[] = { 1, 2, 12, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (CheckArray(arr, n)) cout << "YES"; else cout << "NO"; return 0;}
import java.util.ArrayList; // Java implementation of the above approachclass GFG { // Function to Check if the array// has an element which is equal to// product of all the remaining elements static boolean CheckArray(int arr[], int n) { int prod = 1; // Storing frequency in map ArrayList<Integer> freq = new ArrayList<>(); // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.add(arr[i]); prod *= arr[i]; } int root = (int) Math.sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not { if (freq.contains(root) & freq.lastIndexOf(root) != (freq.size())) { return true; } } return false; }// Driver code public static void main(String[] args) { int arr[] = {1, 2, 12, 3, 2}; int n = arr.length; if (CheckArray(arr, n)) { System.out.println("YES"); } else { System.out.println("NO"); } }}//This code is contributed by 29AjayKumar
# Python3 implementation of the above approach import math # Function to Check if the array# has an element which is equal to# product of all the remaining elementsdef CheckArray( arr, n): prod = 1 # Storing frequency in map freq = [] # Calculate the product of all the elements for i in range(n) : freq.append(arr[i]) prod *= arr[i] root = math.sqrt(prod) # If the prod is a perfect square if (root * root == prod): # then check if its square root # exist in the array or not if root in freq: return True return False # Driver codeif __name__ == "__main__": arr = [1, 2, 12, 3, 2 ] n = len(arr) if (CheckArray(arr, n)): print ("YES") else: print ("NO")
// C# implementation of above approachusing System;using System.Collections; class GFG{ // Function to Check if the array // has an element which is equal to // product of all the remaining elements static bool CheckArray(int []arr, int n) { int prod = 1; // Storing frequency in map ArrayList freq = new ArrayList(); // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.Add(arr[i]); prod *= arr[i]; } int root = (int) Math.Sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not { if (freq.Contains(root) & freq.LastIndexOf(root) != (freq.Count)) { return true; } } return false; } // Driver code public static void Main() { int []arr = {1, 2, 12, 3, 2}; int n = arr.Length; if (CheckArray(arr, n)) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } }} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray($arr, $n){ $prod = 1; // Storing frequency in map $freq = array(); // Calculate the product of all the elements for ($i = 0; $i < $n; ++$i) { array_push($freq, $arr[$i]); $prod *= $arr[$i]; } $freq = array_unique($freq); $root = (int)(sqrt($prod)); // If the prod is a perfect square if ($root * $root == $prod) // then check if its square root // exist in the array or not if (in_array($root, $freq)) return true; return false;} // Driver code$arr = array( 1, 2, 12, 3, 2 );$n = count($arr); if (CheckArray($arr, $n)) echo "YES"; else echo "NO"; // This code is contributed by mits?>
<script> // JavaScript implementation of// the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elements function CheckArray(arr,n) { let prod = 1; // Storing frequency in map let freq = []; // Calculate the product of all the elements for (let i = 0; i < n; ++i) { freq.push(arr[i]); prod *= arr[i]; } let root = Math.floor(Math.sqrt(prod)); // If the prod is a perfect square // then check if its square root if (root * root == prod) // exist in the array or not { if (freq.includes(root) & freq.lastIndexOf(root) != (freq.length)) { return true; } } return false; } // Driver code let arr=[1, 2, 12, 3, 2]; let n = arr.length; if (CheckArray(arr, n)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by avanitrachhadiya2155 </script>
YES
Shashank12
Mithun Kumar
Akanksha_Rai
SURENDRA_GANGWAR
29AjayKumar
ukasp
princiraj1992
sravankumar8128
avanitrachhadiya2155
akshaysingh98088
cpp-unordered_set
Technical Scripter 2018
Arrays
Mathematical
Technical Scripter
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7 | [
{
"code": null,
"e": 26443,
"s": 26415,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 26583,
"s": 26443,
"text": "Given an array of N elements, the task is to check if the array has an element which is equal to the product of all the remaining elements."
},
{
"code": null,
"e": 26594,
"s": 26583,
"text": "Examples: "
},
{
"code": null,
"e": 26748,
"s": 26594,
"text": "Input: arr[] = {1, 2, 12, 3, 2}\nOutput: YES\n12 is the product of all the remaining elements \ni.e. 1 * 2 * 3 * 2 = 12\n\nInput: arr[] = {1, 2, 3}\nOutput: NO"
},
{
"code": null,
"e": 26760,
"s": 26748,
"text": "Method-1: "
},
{
"code": null,
"e": 26997,
"s": 26760,
"text": "First, take the product of all the element of the array.Now traverse the whole array again.For any element a[i] check if it is equal to the product of all elements divided by that element.Print Yes if at least one such element is found."
},
{
"code": null,
"e": 27054,
"s": 26997,
"text": "First, take the product of all the element of the array."
},
{
"code": null,
"e": 27090,
"s": 27054,
"text": "Now traverse the whole array again."
},
{
"code": null,
"e": 27188,
"s": 27090,
"text": "For any element a[i] check if it is equal to the product of all elements divided by that element."
},
{
"code": null,
"e": 27237,
"s": 27188,
"text": "Print Yes if at least one such element is found."
},
{
"code": null,
"e": 27290,
"s": 27237,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27294,
"s": 27290,
"text": "C++"
},
{
"code": null,
"e": 27299,
"s": 27294,
"text": "Java"
},
{
"code": null,
"e": 27307,
"s": 27299,
"text": "Python3"
},
{
"code": null,
"e": 27310,
"s": 27307,
"text": "C#"
},
{
"code": null,
"e": 27314,
"s": 27310,
"text": "PHP"
},
{
"code": null,
"e": 27325,
"s": 27314,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to Check if the array// has an element which is equal to// product of all the remaining elementsbool CheckArray(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} int main(){ int arr[] = { 1, 2, 12, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (CheckArray(arr, n)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 28046,
"s": 27325,
"text": null
},
{
"code": "// Java implementation of the above approach import java.io.*; class GFG { // Function to Check if the array// has an element which is equal to// product of all the remaining elementsstatic boolean CheckArray(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} public static void main (String[] args) { int arr[] = { 1, 2, 12, 3, 2 }; int n =arr.length; if (CheckArray(arr, n)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}// This code is contributed by shs..",
"e": 28842,
"s": 28046,
"text": null
},
{
"code": "# Python 3 implementation of the above approach # Function to Check if the array# has an element which is equal to# product of all the remaining elementsdef CheckArray(arr, n): prod = 1 # Calculate the product of all # the elements for i in range(0, n, 1): prod *= arr[i] # Return true if any such element # is found for i in range(0, n, 1): if (arr[i] == prod / arr[i]): return True # If no element is found return False # Driver codeif __name__ == '__main__': arr = [1, 2, 12, 3, 2] n = len(arr) if (CheckArray(arr, n)): print(\"YES\") else: print(\"NO\") # This code is contributed by# Surendra_Gangwar",
"e": 29527,
"s": 28842,
"text": null
},
{
"code": "// C# implementation of the above approachclass GFG{// Function to Check if the array// has an element which is equal to// product of all the remaining elementsstatic bool CheckArray(int[] arr, int n){ int prod = 1; // Calculate the product of // all the elements for (int i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such // element is found for (int i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} // Driver Codepublic static void Main (){ int[] arr = new int[] { 1, 2, 12, 3, 2 }; int n = arr.Length; if (CheckArray(arr, n)) System.Console.WriteLine(\"YES\"); else System.Console.WriteLine(\"NO\");}} // This code is contributed by mits",
"e": 30320,
"s": 29527,
"text": null
},
{
"code": "<?php// PHP implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray($arr, $n){ $prod = 1; // Calculate the product of // all the elements for ($i = 0; $i < $n; ++$i) $prod *= $arr[$i]; // Return true if any such element // is found for ($i = 0; $i < $n; ++$i) if ($arr[$i] == $prod / $arr[$i]) return true; // If no element is found return false;} // Driver Code$arr = array(1, 2, 12, 3, 2);$n = sizeof($arr); if (CheckArray($arr, $n)) echo \"YES\";else echo \"NO\"; // This code is contributed// by Akanksha Rai",
"e": 30999,
"s": 30320,
"text": null
},
{
"code": "<script>// Java script implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray(arr,n){ let prod = 1; // Calculate the product of all the elements for (let i = 0; i < n; ++i) prod *= arr[i]; // Return true if any such element is found for (let i = 0; i < n; ++i) if (arr[i] == prod / arr[i]) return true; // If no element is found return false;} let arr = [ 1, 2, 12, 3, 2 ]; let n =arr.length; if (CheckArray(arr, n)) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by sravan kumar Gottumukkala</script>",
"e": 31722,
"s": 30999,
"text": null
},
{
"code": null,
"e": 31726,
"s": 31722,
"text": "YES"
},
{
"code": null,
"e": 31990,
"s": 31728,
"text": "Method-2: The approach is to find the product of all the elements of the array and check if it is a perfect square or not. If it is a perfect square then check if the square root of the product exists in the array or not. If exists then print Yes else print No."
},
{
"code": null,
"e": 32271,
"s": 31990,
"text": "According to the problem statement, a * b = N where b is the product of all the remaining elements of the array except a i.e arr[i] And it is also mentioned that find the index such that a = b. So, it simply means that a*a = N i.e. N is a perfect square. and a is its square root."
},
{
"code": null,
"e": 32324,
"s": 32271,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32328,
"s": 32324,
"text": "C++"
},
{
"code": null,
"e": 32333,
"s": 32328,
"text": "Java"
},
{
"code": null,
"e": 32341,
"s": 32333,
"text": "Python3"
},
{
"code": null,
"e": 32344,
"s": 32341,
"text": "C#"
},
{
"code": null,
"e": 32348,
"s": 32344,
"text": "PHP"
},
{
"code": null,
"e": 32359,
"s": 32348,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to Check if the array// has an element which is equal to// product of all the remaining elementsbool CheckArray(int arr[], int n){ int prod = 1; // Storing frequency in map unordered_set<int> freq; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.insert(arr[i]); prod *= arr[i]; } int root = sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not if (freq.find(root) != freq.end()) return true; return false;} // Driver codeint main(){ int arr[] = { 1, 2, 12, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (CheckArray(arr, n)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 33258,
"s": 32359,
"text": null
},
{
"code": "import java.util.ArrayList; // Java implementation of the above approachclass GFG { // Function to Check if the array// has an element which is equal to// product of all the remaining elements static boolean CheckArray(int arr[], int n) { int prod = 1; // Storing frequency in map ArrayList<Integer> freq = new ArrayList<>(); // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.add(arr[i]); prod *= arr[i]; } int root = (int) Math.sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not { if (freq.contains(root) & freq.lastIndexOf(root) != (freq.size())) { return true; } } return false; }// Driver code public static void main(String[] args) { int arr[] = {1, 2, 12, 3, 2}; int n = arr.length; if (CheckArray(arr, n)) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } }}//This code is contributed by 29AjayKumar",
"e": 34422,
"s": 33258,
"text": null
},
{
"code": "# Python3 implementation of the above approach import math # Function to Check if the array# has an element which is equal to# product of all the remaining elementsdef CheckArray( arr, n): prod = 1 # Storing frequency in map freq = [] # Calculate the product of all the elements for i in range(n) : freq.append(arr[i]) prod *= arr[i] root = math.sqrt(prod) # If the prod is a perfect square if (root * root == prod): # then check if its square root # exist in the array or not if root in freq: return True return False # Driver codeif __name__ == \"__main__\": arr = [1, 2, 12, 3, 2 ] n = len(arr) if (CheckArray(arr, n)): print (\"YES\") else: print (\"NO\")",
"e": 35195,
"s": 34422,
"text": null
},
{
"code": "// C# implementation of above approachusing System;using System.Collections; class GFG{ // Function to Check if the array // has an element which is equal to // product of all the remaining elements static bool CheckArray(int []arr, int n) { int prod = 1; // Storing frequency in map ArrayList freq = new ArrayList(); // Calculate the product of all the elements for (int i = 0; i < n; ++i) { freq.Add(arr[i]); prod *= arr[i]; } int root = (int) Math.Sqrt(prod); // If the prod is a perfect square if (root * root == prod) // then check if its square root // exist in the array or not { if (freq.Contains(root) & freq.LastIndexOf(root) != (freq.Count)) { return true; } } return false; } // Driver code public static void Main() { int []arr = {1, 2, 12, 3, 2}; int n = arr.Length; if (CheckArray(arr, n)) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); } }} /* This code contributed by PrinciRaj1992 */",
"e": 36401,
"s": 35195,
"text": null
},
{
"code": "<?php// PHP implementation of the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elementsfunction CheckArray($arr, $n){ $prod = 1; // Storing frequency in map $freq = array(); // Calculate the product of all the elements for ($i = 0; $i < $n; ++$i) { array_push($freq, $arr[$i]); $prod *= $arr[$i]; } $freq = array_unique($freq); $root = (int)(sqrt($prod)); // If the prod is a perfect square if ($root * $root == $prod) // then check if its square root // exist in the array or not if (in_array($root, $freq)) return true; return false;} // Driver code$arr = array( 1, 2, 12, 3, 2 );$n = count($arr); if (CheckArray($arr, $n)) echo \"YES\"; else echo \"NO\"; // This code is contributed by mits?>",
"e": 37256,
"s": 36401,
"text": null
},
{
"code": "<script> // JavaScript implementation of// the above approach // Function to Check if the array// has an element which is equal to// product of all the remaining elements function CheckArray(arr,n) { let prod = 1; // Storing frequency in map let freq = []; // Calculate the product of all the elements for (let i = 0; i < n; ++i) { freq.push(arr[i]); prod *= arr[i]; } let root = Math.floor(Math.sqrt(prod)); // If the prod is a perfect square // then check if its square root if (root * root == prod) // exist in the array or not { if (freq.includes(root) & freq.lastIndexOf(root) != (freq.length)) { return true; } } return false; } // Driver code let arr=[1, 2, 12, 3, 2]; let n = arr.length; if (CheckArray(arr, n)) { document.write(\"YES\"); } else { document.write(\"NO\"); } // This code is contributed by avanitrachhadiya2155 </script>",
"e": 38342,
"s": 37256,
"text": null
},
{
"code": null,
"e": 38346,
"s": 38342,
"text": "YES"
},
{
"code": null,
"e": 38359,
"s": 38348,
"text": "Shashank12"
},
{
"code": null,
"e": 38372,
"s": 38359,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 38385,
"s": 38372,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 38402,
"s": 38385,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 38414,
"s": 38402,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38420,
"s": 38414,
"text": "ukasp"
},
{
"code": null,
"e": 38434,
"s": 38420,
"text": "princiraj1992"
},
{
"code": null,
"e": 38450,
"s": 38434,
"text": "sravankumar8128"
},
{
"code": null,
"e": 38471,
"s": 38450,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 38488,
"s": 38471,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 38506,
"s": 38488,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 38530,
"s": 38506,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 38537,
"s": 38530,
"text": "Arrays"
},
{
"code": null,
"e": 38550,
"s": 38537,
"text": "Mathematical"
},
{
"code": null,
"e": 38569,
"s": 38550,
"text": "Technical Scripter"
},
{
"code": null,
"e": 38576,
"s": 38569,
"text": "Arrays"
},
{
"code": null,
"e": 38589,
"s": 38576,
"text": "Mathematical"
},
{
"code": null,
"e": 38687,
"s": 38589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38710,
"s": 38687,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 38742,
"s": 38710,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38756,
"s": 38742,
"text": "Linear Search"
},
{
"code": null,
"e": 38777,
"s": 38756,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 38862,
"s": 38777,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38892,
"s": 38862,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38952,
"s": 38892,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38995,
"s": 38952,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 39010,
"s": 38995,
"text": "C++ Data Types"
}
]
|
Maximum number of multiplication by 3 or division by 2 operations possible on an array - GeeksforGeeks | 12 Jul, 2021
Given an array arr[] consisting of N positive integers, the task is to find the maximum number of times each array element can either be multiplied by M or divided by K. Note: At least one element needs to be divided by M and K respectively in each operation.
Examples:
Input: arr[] = {5, 2, 4}, M = 3, K = 2Output: 3Explanation:One possible way to perform the operations is:
Multiply arr[1] and arr[2] by 3, and divide arr[3] by 2. The array modifies to {15, 6, 2}.Multiply arr[1] and arr[3] by 3, divide arr[2] by 2. The array modifies to {45, 3, 6}.Multiply arr[1] by 3 and arr[2] by 3 and divide arr[3] by 2. The array modifies to {135, 9, 3}.No further operation is possible since no element is divisible by 2.
Multiply arr[1] and arr[2] by 3, and divide arr[3] by 2. The array modifies to {15, 6, 2}.
Multiply arr[1] and arr[3] by 3, divide arr[2] by 2. The array modifies to {45, 3, 6}.
Multiply arr[1] by 3 and arr[2] by 3 and divide arr[3] by 2. The array modifies to {135, 9, 3}.
No further operation is possible since no element is divisible by 2.
Therefore, the maximum number of operations possible is 3.
Input: arr[] = {3, 5, 7}Output: 0
Approach: This problem can be solved by observing that, successively dividing an array element by 2, the count of even elements will decrease after some constant number of steps. So, to maximize the number of turns, only one even element is divided by 2, and all others are multiplied by 3 in a single step. Follow the steps below to solve the problem:
Initialize a variable, say, Count as 0, that will store the count of power of 2 in every element of the array.
Iterate in the range [0, N-1] using the variable i and perform the following steps:Iterate until the arr[i] is divisible by 2, then increment the Count by 1 and divide arr[i] by 2.
Iterate until the arr[i] is divisible by 2, then increment the Count by 1 and divide arr[i] by 2.
After performing the above steps, print the value of Count as the answer.
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 count maximum number// of multiplication by 3 or division// by 2 operations that can be performedint maximumTurns(int arr[], int N){ // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count;} // Driver Codeint main(){ // Given Input int arr[] = { 5, 2, 4 }; int M = 3, K = 2; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << maximumTurns(arr, N); return 0;}
// Java program for the above approachpublic class GFG{ // Function to count maximum number // of multiplication by 3 or division // by 2 operations that can be performed static int maximumTurns(int arr[], int N) { // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count; } // Driver code public static void main(String[] args) { // Given Input // Given Input int arr[] = { 5, 2, 4 }; int M = 3, K = 2; int N = arr.length; // Function Call System.out.println(maximumTurns(arr, N)); }} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to count maximum number# of multiplication by 3 or division# by 2 operations that can be performeddef maximumTurns(arr, N): # Stores the maximum number # of operations possible Count = 0 # Traverse the array arr[] for i in range(0, N): # Iterate until arr[i] is even while (arr[i] % 2 == 0): # Increment count by 1 Count += 1 # Update arr[i] arr[i] = arr[i] // 2 # Return the value of # Count as the answer return Count # Driver code # Given Inputarr = [ 5, 2, 4 ]M = 3K = 2N = len(arr) # Function Callprint(maximumTurns(arr, N)) # This code is contributed by amreshkumar3
// C# program for the above approach using System;using System.Collections.Generic; class GFG{ // Function to count maximum number// of multiplication by 3 or division// by 2 operations that can be performedstatic int maximumTurns(int []arr, int N){ // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count;} // Driver Codepublic static void Main(){ // Given Input int []arr = { 5, 2, 4 }; int N = arr.Length; // Function Call Console.Write(maximumTurns(arr, N));}} // This code is contributed by ipg2016107.
<script> // JavaScript program for the above approach // Function to count maximum number// of multiplication by 3 or division// by 2 operations that can be performedfunction maximumTurns(arr, N) { // Stores the maximum number // of operations possible let Count = 0; // Traverse the array arr[] for (let i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = Math.floor(arr[i] / 2); } } // Return the value of // Count as the answer return Count;} // Driver Code // Given Inputlet arr = [5, 2, 4];let M = 3, K = 2;let N = arr.length; // Function Calldocument.write(maximumTurns(arr, N)); </script>
3
Time complexity: O(N*log(M)) where M is the maximum value of the array.Auxiliary Space: O(1)
amreshkumar3
_saurabh_jaiswal
abhinavjain194
ipg2016107
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 26327,
"s": 26067,
"text": "Given an array arr[] consisting of N positive integers, the task is to find the maximum number of times each array element can either be multiplied by M or divided by K. Note: At least one element needs to be divided by M and K respectively in each operation."
},
{
"code": null,
"e": 26337,
"s": 26327,
"text": "Examples:"
},
{
"code": null,
"e": 26443,
"s": 26337,
"text": "Input: arr[] = {5, 2, 4}, M = 3, K = 2Output: 3Explanation:One possible way to perform the operations is:"
},
{
"code": null,
"e": 26783,
"s": 26443,
"text": "Multiply arr[1] and arr[2] by 3, and divide arr[3] by 2. The array modifies to {15, 6, 2}.Multiply arr[1] and arr[3] by 3, divide arr[2] by 2. The array modifies to {45, 3, 6}.Multiply arr[1] by 3 and arr[2] by 3 and divide arr[3] by 2. The array modifies to {135, 9, 3}.No further operation is possible since no element is divisible by 2."
},
{
"code": null,
"e": 26874,
"s": 26783,
"text": "Multiply arr[1] and arr[2] by 3, and divide arr[3] by 2. The array modifies to {15, 6, 2}."
},
{
"code": null,
"e": 26961,
"s": 26874,
"text": "Multiply arr[1] and arr[3] by 3, divide arr[2] by 2. The array modifies to {45, 3, 6}."
},
{
"code": null,
"e": 27057,
"s": 26961,
"text": "Multiply arr[1] by 3 and arr[2] by 3 and divide arr[3] by 2. The array modifies to {135, 9, 3}."
},
{
"code": null,
"e": 27126,
"s": 27057,
"text": "No further operation is possible since no element is divisible by 2."
},
{
"code": null,
"e": 27185,
"s": 27126,
"text": "Therefore, the maximum number of operations possible is 3."
},
{
"code": null,
"e": 27219,
"s": 27185,
"text": "Input: arr[] = {3, 5, 7}Output: 0"
},
{
"code": null,
"e": 27572,
"s": 27219,
"text": "Approach: This problem can be solved by observing that, successively dividing an array element by 2, the count of even elements will decrease after some constant number of steps. So, to maximize the number of turns, only one even element is divided by 2, and all others are multiplied by 3 in a single step. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27683,
"s": 27572,
"text": "Initialize a variable, say, Count as 0, that will store the count of power of 2 in every element of the array."
},
{
"code": null,
"e": 27864,
"s": 27683,
"text": "Iterate in the range [0, N-1] using the variable i and perform the following steps:Iterate until the arr[i] is divisible by 2, then increment the Count by 1 and divide arr[i] by 2."
},
{
"code": null,
"e": 27962,
"s": 27864,
"text": "Iterate until the arr[i] is divisible by 2, then increment the Count by 1 and divide arr[i] by 2."
},
{
"code": null,
"e": 28036,
"s": 27962,
"text": "After performing the above steps, print the value of Count as the answer."
},
{
"code": null,
"e": 28087,
"s": 28036,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28091,
"s": 28087,
"text": "C++"
},
{
"code": null,
"e": 28096,
"s": 28091,
"text": "Java"
},
{
"code": null,
"e": 28104,
"s": 28096,
"text": "Python3"
},
{
"code": null,
"e": 28107,
"s": 28104,
"text": "C#"
},
{
"code": null,
"e": 28118,
"s": 28107,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count maximum number// of multiplication by 3 or division// by 2 operations that can be performedint maximumTurns(int arr[], int N){ // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count;} // Driver Codeint main(){ // Given Input int arr[] = { 5, 2, 4 }; int M = 3, K = 2; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << maximumTurns(arr, N); return 0;}",
"e": 28973,
"s": 28118,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG{ // Function to count maximum number // of multiplication by 3 or division // by 2 operations that can be performed static int maximumTurns(int arr[], int N) { // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count; } // Driver code public static void main(String[] args) { // Given Input // Given Input int arr[] = { 5, 2, 4 }; int M = 3, K = 2; int N = arr.length; // Function Call System.out.println(maximumTurns(arr, N)); }} // This code is contributed by abhinavjain194",
"e": 30019,
"s": 28973,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count maximum number# of multiplication by 3 or division# by 2 operations that can be performeddef maximumTurns(arr, N): # Stores the maximum number # of operations possible Count = 0 # Traverse the array arr[] for i in range(0, N): # Iterate until arr[i] is even while (arr[i] % 2 == 0): # Increment count by 1 Count += 1 # Update arr[i] arr[i] = arr[i] // 2 # Return the value of # Count as the answer return Count # Driver code # Given Inputarr = [ 5, 2, 4 ]M = 3K = 2N = len(arr) # Function Callprint(maximumTurns(arr, N)) # This code is contributed by amreshkumar3",
"e": 30772,
"s": 30019,
"text": null
},
{
"code": "// C# program for the above approach using System;using System.Collections.Generic; class GFG{ // Function to count maximum number// of multiplication by 3 or division// by 2 operations that can be performedstatic int maximumTurns(int []arr, int N){ // Stores the maximum number // of operations possible int Count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = arr[i] / 2; } } // Return the value of // Count as the answer return Count;} // Driver Codepublic static void Main(){ // Given Input int []arr = { 5, 2, 4 }; int N = arr.Length; // Function Call Console.Write(maximumTurns(arr, N));}} // This code is contributed by ipg2016107.",
"e": 31659,
"s": 30772,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to count maximum number// of multiplication by 3 or division// by 2 operations that can be performedfunction maximumTurns(arr, N) { // Stores the maximum number // of operations possible let Count = 0; // Traverse the array arr[] for (let i = 0; i < N; i++) { // Iterate until arr[i] is even while (arr[i] % 2 == 0) { // Increment count by 1 Count++; // Update arr[i] arr[i] = Math.floor(arr[i] / 2); } } // Return the value of // Count as the answer return Count;} // Driver Code // Given Inputlet arr = [5, 2, 4];let M = 3, K = 2;let N = arr.length; // Function Calldocument.write(maximumTurns(arr, N)); </script>",
"e": 32440,
"s": 31659,
"text": null
},
{
"code": null,
"e": 32442,
"s": 32440,
"text": "3"
},
{
"code": null,
"e": 32538,
"s": 32444,
"text": "Time complexity: O(N*log(M)) where M is the maximum value of the array.Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32551,
"s": 32538,
"text": "amreshkumar3"
},
{
"code": null,
"e": 32568,
"s": 32551,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32583,
"s": 32568,
"text": "abhinavjain194"
},
{
"code": null,
"e": 32594,
"s": 32583,
"text": "ipg2016107"
},
{
"code": null,
"e": 32601,
"s": 32594,
"text": "Arrays"
},
{
"code": null,
"e": 32614,
"s": 32601,
"text": "Mathematical"
},
{
"code": null,
"e": 32621,
"s": 32614,
"text": "Arrays"
},
{
"code": null,
"e": 32634,
"s": 32621,
"text": "Mathematical"
},
{
"code": null,
"e": 32732,
"s": 32634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32759,
"s": 32732,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32790,
"s": 32759,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32815,
"s": 32790,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32853,
"s": 32815,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32874,
"s": 32853,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32904,
"s": 32874,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32964,
"s": 32904,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32979,
"s": 32964,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33022,
"s": 32979,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.