title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Plot scatter points on polar axis in Matplotlib
To plot scatter points on polar axis in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Initialize a variable, N, for number of sample data. Get r, theta, area and color data using numpy Create a new figure or activate an existing figure. Plot theta, r, colors and area, using scatter() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True N = 150 r = 2 * np.random.rand(N) theta = 2 * np.pi * np.random.rand(N) area = 200 * r**2 colors = theta fig = plt.figure() ax = fig.add_subplot(projection='polar') c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75) plt.show()
[ { "code": null, "e": 1148, "s": 1062, "text": "To plot scatter points on polar axis in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1224, "s": 1148, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1277, "s": 1224, "text": "Initialize a variable, N, for number of sample data." }, { "code": null, "e": 1323, "s": 1277, "text": "Get r, theta, area and color data using numpy" }, { "code": null, "e": 1375, "s": 1323, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1431, "s": 1375, "text": "Plot theta, r, colors and area, using scatter() method." }, { "code": null, "e": 1473, "s": 1431, "text": "To display the figure, use show() method." }, { "code": null, "e": 1858, "s": 1473, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nN = 150\nr = 2 * np.random.rand(N)\ntheta = 2 * np.pi * np.random.rand(N)\narea = 200 * r**2\ncolors = theta\n\nfig = plt.figure()\nax = fig.add_subplot(projection='polar')\nc = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)\n\nplt.show()" } ]
Get started with Apache Spark and TensorFlow on Azure Databricks | by Adi Polak | Towards Data Science
This is a step by step tutorial on how to get new Spark TensorFrame library running on Azure Databricks. Big Data is a huge topic that consists of many domains and expertise. All the way from DevOps, Data Engineers to Data Scientist, AI, Machine Learning, algorithm developers and many more. We all struggle with massive amounts of data. When we deal with a massive amount of data, we need the best minds and tools. This is where the magical combination of Apache Spark and Tensor Flow takes place and we call it TensorFrame. Apache Spark took over the Big Data world, giving answers and supporting Data Engineers to be a more successful while, Data Scientist had to figure their way around the limitation of the machine learning library that Spark provides, the Spark MLlib. But no more, now, there is TensorFlow support for Apache Spark users. These tools combined makes the work of Data Scientists more productive, more accurate and faster. And taking outcome from Research to Develop to Production, faster than ever. Before we start, let's align the terms: Tensor Flow is an open source machine learning framework for high-performance numerical computations created by Google. It comes with strong support for AI: machine learning and deep learning. Azure Databricks is an Apache Spark-based analytics platform optimized for the Microsoft Azure cloud services platform. Azure Databricks also acts as Software as a Service( SaaS) / Big Data as a Service (BDaaS). TensorFrames is an Apache Spark component that enables us to create our own scalable TensorFlow learning algorithms on Spark Clusters. First, we need to create the workspace, we are using Databricks workspace and here is a tutorial for creating it. After we have the workspace, we need to create the cluster itself. Let’s create our spark cluster using this tutorial, make sure you have the next configurations in your cluster: A working version of Apache Spark (2.4 or greater) Java 8+ (Optional) python 2.7+/3.6+ if you want to use the python interface. (Optional) the python TensorFlow package if you want to use the python interface. See the official instructions on how to get the latest release of TensorFlow. (Optional) pandas >= 0.19.1 if you want to use the python interface The configuration: with Databricks runtime versions or above : Press start to launch the cluster Under Azure Databricks, go to Common Tasks and click Import Library: TensorFrame can be found on maven repository, so choose the Maven tag. Under Coordinates, insert the library of your choice, for now, it will be: databricks:tensorframes:0.6.0-s_2.11 Click the Create button. Click Install. You will see this: BOOM. you have TensorFrame on your Databricks Cluster. We use the notebook as our code notebook where we can write the code and run it directly on our Spark Cluster. Now that we have a running cluster, let’s run a notebook: Click the New Notebook and choose the programming language of your choice ( here we chose Scala) This is how it looks like with scala code on the notebook portal with TensorFrames: The code example is from Databricks git repository. You can check it here as well: Now that you have everything up and running, create your own triggered/scheduled job that uses TensorFrame in Apache Spark cluster. and ... Since you’ve got all the way to here, Click the Clap button👏 and Follow me on Medium and Twitter for more posts about Scala, Kotlin, Big data, clean code and software engineers challenges. Cheers!
[ { "code": null, "e": 277, "s": 172, "text": "This is a step by step tutorial on how to get new Spark TensorFrame library running on Azure Databricks." }, { "code": null, "e": 698, "s": 277, "text": "Big Data is a huge topic that consists of many domains and expertise. All the way from DevOps, Data Engineers to Data Scientist, AI, Machine Learning, algorithm developers and many more. We all struggle with massive amounts of data. When we deal with a massive amount of data, we need the best minds and tools. This is where the magical combination of Apache Spark and Tensor Flow takes place and we call it TensorFrame." }, { "code": null, "e": 948, "s": 698, "text": "Apache Spark took over the Big Data world, giving answers and supporting Data Engineers to be a more successful while, Data Scientist had to figure their way around the limitation of the machine learning library that Spark provides, the Spark MLlib." }, { "code": null, "e": 1193, "s": 948, "text": "But no more, now, there is TensorFlow support for Apache Spark users. These tools combined makes the work of Data Scientists more productive, more accurate and faster. And taking outcome from Research to Develop to Production, faster than ever." }, { "code": null, "e": 1233, "s": 1193, "text": "Before we start, let's align the terms:" }, { "code": null, "e": 1426, "s": 1233, "text": "Tensor Flow is an open source machine learning framework for high-performance numerical computations created by Google. It comes with strong support for AI: machine learning and deep learning." }, { "code": null, "e": 1638, "s": 1426, "text": "Azure Databricks is an Apache Spark-based analytics platform optimized for the Microsoft Azure cloud services platform. Azure Databricks also acts as Software as a Service( SaaS) / Big Data as a Service (BDaaS)." }, { "code": null, "e": 1773, "s": 1638, "text": "TensorFrames is an Apache Spark component that enables us to create our own scalable TensorFlow learning algorithms on Spark Clusters." }, { "code": null, "e": 1887, "s": 1773, "text": "First, we need to create the workspace, we are using Databricks workspace and here is a tutorial for creating it." }, { "code": null, "e": 2066, "s": 1887, "text": "After we have the workspace, we need to create the cluster itself. Let’s create our spark cluster using this tutorial, make sure you have the next configurations in your cluster:" }, { "code": null, "e": 2117, "s": 2066, "text": "A working version of Apache Spark (2.4 or greater)" }, { "code": null, "e": 2125, "s": 2117, "text": "Java 8+" }, { "code": null, "e": 2194, "s": 2125, "text": "(Optional) python 2.7+/3.6+ if you want to use the python interface." }, { "code": null, "e": 2354, "s": 2194, "text": "(Optional) the python TensorFlow package if you want to use the python interface. See the official instructions on how to get the latest release of TensorFlow." }, { "code": null, "e": 2422, "s": 2354, "text": "(Optional) pandas >= 0.19.1 if you want to use the python interface" }, { "code": null, "e": 2441, "s": 2422, "text": "The configuration:" }, { "code": null, "e": 2485, "s": 2441, "text": "with Databricks runtime versions or above :" }, { "code": null, "e": 2519, "s": 2485, "text": "Press start to launch the cluster" }, { "code": null, "e": 2588, "s": 2519, "text": "Under Azure Databricks, go to Common Tasks and click Import Library:" }, { "code": null, "e": 2734, "s": 2588, "text": "TensorFrame can be found on maven repository, so choose the Maven tag. Under Coordinates, insert the library of your choice, for now, it will be:" }, { "code": null, "e": 2771, "s": 2734, "text": "databricks:tensorframes:0.6.0-s_2.11" }, { "code": null, "e": 2796, "s": 2771, "text": "Click the Create button." }, { "code": null, "e": 2811, "s": 2796, "text": "Click Install." }, { "code": null, "e": 2830, "s": 2811, "text": "You will see this:" }, { "code": null, "e": 2885, "s": 2830, "text": "BOOM. you have TensorFrame on your Databricks Cluster." }, { "code": null, "e": 2996, "s": 2885, "text": "We use the notebook as our code notebook where we can write the code and run it directly on our Spark Cluster." }, { "code": null, "e": 3054, "s": 2996, "text": "Now that we have a running cluster, let’s run a notebook:" }, { "code": null, "e": 3151, "s": 3054, "text": "Click the New Notebook and choose the programming language of your choice ( here we chose Scala)" }, { "code": null, "e": 3235, "s": 3151, "text": "This is how it looks like with scala code on the notebook portal with TensorFrames:" }, { "code": null, "e": 3287, "s": 3235, "text": "The code example is from Databricks git repository." }, { "code": null, "e": 3318, "s": 3287, "text": "You can check it here as well:" }, { "code": null, "e": 3450, "s": 3318, "text": "Now that you have everything up and running, create your own triggered/scheduled job that uses TensorFrame in Apache Spark cluster." }, { "code": null, "e": 3458, "s": 3450, "text": "and ..." } ]
How to limit maximum items on multiple input (<input type=“file” multiple />)?
To allow multiple file uploads in HTML forms, use the multiple attributes. The multiple attributes work with email and file input types. For limiting maximum items on multiple inputs, use JavaScript. Through this, limit the number of files to be uploaded. For example, let’s say only 2 files to be uploaded at once. You can try to run the following code to learn how to use multiple attributes in HTML. With that, we will limit the number of files uploaded using JavaScript. Live Demo <!DOCTYPE html> <html> <head> <title>HTML file upload</title> </head> <body> <form> <input type="file" action="/action_page.php" name="name" multiple><br/> Upload multiple files, and click Submit.<br> <input type = "submit" value = "submit"> </form> <script> $(function(){ $("input[type = 'submit']").click(function(){ var $fileUpload = $("input[type='file']"); if (parseInt($fileUpload.get(0).files.length) > 3){ alert("You are only allowed to upload a maximum of 3 files"); } }); }); </script> </body> </html>
[ { "code": null, "e": 1199, "s": 1062, "text": "To allow multiple file uploads in HTML forms, use the multiple attributes. The multiple attributes work with email and file input types." }, { "code": null, "e": 1378, "s": 1199, "text": "For limiting maximum items on multiple inputs, use JavaScript. Through this, limit the number of files to be uploaded. For example, let’s say only 2 files to be uploaded at once." }, { "code": null, "e": 1537, "s": 1378, "text": "You can try to run the following code to learn how to use multiple attributes in HTML. With that, we will limit the number of files uploaded using JavaScript." }, { "code": null, "e": 1547, "s": 1537, "text": "Live Demo" }, { "code": null, "e": 2235, "s": 1547, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML file upload</title>\n </head>\n <body>\n <form>\n <input type=\"file\" action=\"/action_page.php\" name=\"name\" multiple><br/>\n Upload multiple files, and click Submit.<br>\n <input type = \"submit\" value = \"submit\">\n </form>\n <script>\n $(function(){\n $(\"input[type = 'submit']\").click(function(){\n var $fileUpload = $(\"input[type='file']\");\n if (parseInt($fileUpload.get(0).files.length) > 3){\n alert(\"You are only allowed to upload a maximum of 3 files\");\n }\n });\n });\n </script>\n </body>\n</html>" } ]
JavaScript Array Ranking - JavaScript
Suppose, we have three JavaScript arrays of Number like these − const array1 = [10,23,53,74,33,56,6,0,43,45,11]; const array2 = [52,46,27,28,4,11,53,6,75,75,22]; const array3 = [26,18,10,12,31,12,5,8,44,34,65]; The length of all the arrays will always be the same. We are required to write a JavaScript function that in any number of such arrays maps the corresponding elements of an existing array according to their rank (i.e., their order in decreasing sense). Therefore, for the above arrays, the output should look like − const array1= [3,2,1,1,1,1,2,3,2,2,3]; const array2= [1,1,2,2,2,2,1,2,1,1,2]; const array3= [2,3,3,3,3,3,3,1,2,3,1]; Following is the code − const array1 = [10,23,53,74,33,56,6,0,43,45,11]; const array2 = [52,46,27,28,4,11,53,6,75,75,22]; const array3 = [26,18,10,12,31,12,5,8,44,34,65]; const transpose = (rank, arr) => { return arr.map((el, ind) => { return [...(rank[ind] || []), el]; }); }; const ranks = arr => { return arr.map( Map.prototype.get, [...arr] .sort((a, b) => b - a) .reduce((r => (m, v) => m.set(v, (r++, m.get(v)) || r))(0), new Map) ); }; const findRanks = (...arrs) => { return arrs .reduce(transpose, []) .map(ranks) .reduce(transpose, []); }; console.log(findRanks(array1, array2, array3)); This will produce the following output on console − [ [ 3, 2, 1, 1, 1, 1, 2, 3, 3, 2, 3 ], [ 1, 1, 2, 2, 3, 3, 1, 2, 1, 1, 2 ], [ 2, 3, 3, 3, 2, 2, 3, 1, 2, 3, 1 ] ]
[ { "code": null, "e": 1126, "s": 1062, "text": "Suppose, we have three JavaScript arrays of Number like these −" }, { "code": null, "e": 1273, "s": 1126, "text": "const array1 = [10,23,53,74,33,56,6,0,43,45,11];\nconst array2 = [52,46,27,28,4,11,53,6,75,75,22];\nconst array3 = [26,18,10,12,31,12,5,8,44,34,65];" }, { "code": null, "e": 1327, "s": 1273, "text": "The length of all the arrays will always be the same." }, { "code": null, "e": 1526, "s": 1327, "text": "We are required to write a JavaScript function that in any number of such arrays maps the corresponding elements of an existing array according to their rank (i.e., their order in decreasing sense)." }, { "code": null, "e": 1589, "s": 1526, "text": "Therefore, for the above arrays, the output should look like −" }, { "code": null, "e": 1706, "s": 1589, "text": "const array1= [3,2,1,1,1,1,2,3,2,2,3];\nconst array2= [1,1,2,2,2,2,1,2,1,1,2];\nconst array3= [2,3,3,3,3,3,3,1,2,3,1];" }, { "code": null, "e": 1730, "s": 1706, "text": "Following is the code −" }, { "code": null, "e": 2358, "s": 1730, "text": "const array1 = [10,23,53,74,33,56,6,0,43,45,11];\nconst array2 = [52,46,27,28,4,11,53,6,75,75,22];\nconst array3 = [26,18,10,12,31,12,5,8,44,34,65];\nconst transpose = (rank, arr) => {\n return arr.map((el, ind) => {\n return [...(rank[ind] || []), el];\n });\n};\nconst ranks = arr => {\n return arr.map(\n Map.prototype.get,\n [...arr]\n .sort((a, b) => b - a)\n .reduce((r => (m, v) => m.set(v, (r++, m.get(v)) || r))(0), new Map)\n );\n};\nconst findRanks = (...arrs) => {\n return arrs\n .reduce(transpose, [])\n .map(ranks)\n .reduce(transpose, []);\n};\nconsole.log(findRanks(array1, array2, array3));" }, { "code": null, "e": 2410, "s": 2358, "text": "This will produce the following output on console −" }, { "code": null, "e": 2557, "s": 2410, "text": "[\n [\n 3, 2, 1, 1, 1,\n 1, 2, 3, 3, 2,\n 3\n ],\n [\n 1, 1, 2, 2, 3,\n 3, 1, 2, 1, 1,\n 2\n ],\n [\n 2, 3, 3, 3, 2,\n 2, 3, 1, 2, 3,\n 1\n ]\n]" } ]
TreeSet contains() Method in Java With Examples - GeeksforGeeks
26 Jan, 2022 TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. This class provides numerous methods of which let us discuss contains() method of TreeSet class present inside java.util package is used to check if a specific element is present in the TreeSet or not. So basically it is used to check if a TreeSet contains any particular element. Syntax: Tree_Set.contains(Object element) Parameters: The type of TreeSet. This is the element that needs to be checked if it is present in the TreeSet or not. Return Value: A boolean value, true if the element is present in the set else it returns false. Exceptions: It throws two types of exceptions listed below as follows: NullPointerException: If the specified element is null ClassCastException: If the specified element cannot be compared with the elements that currently exist in the set. Tip: As we do know treeSet uses natural ordering and its comparator does not permit the null elements hence forth NullPointerException arises into play. Example Java // Java Program to Illustrate contains() method// of TreeSet class // Importing required classesimport java.io.*;import java.util.TreeSet; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty TreeSet of string type TreeSet<String> tree = new TreeSet<String>(); // Adding elements in TreeSet // Using add() method to tree.add("Welcome"); tree.add("To"); tree.add("Geeks"); tree.add("4"); tree.add("Geeks"); tree.add("TreeSet"); // Displaying the TreeSet System.out.println("TreeSet: " + tree); // Use-case 1 // Check for specific element in the above TreeSet // object using contains() method of TreeSet class // Printing a boolean value System.out.println( "Does the Set contains 'TreeSet'? " + tree.contains("TreeSet")); // Use-case 2 // Check for specific element in the above TreeSet // object Say custom element be "4" System.out.println("Does the Set contains '4'? " + tree.contains("4")); // Use-case 3 // Check if the list contains "No" System.out.println("Does the Set contains 'No'? " + tree.contains("No")); }} TreeSet: [4, Geeks, To, TreeSet, Welcome] Does the Set contains 'TreeSet'? true Does the Set contains '4'? true Does the Set contains 'No'? false Output Explanation: As we inserted elements in TreeSet {“Welcome”, “To”, “Geeks”, “4”, “Geeks”, “TreeSet”} then we checks for a specific elements bypassing element as an argument to contains() method which we now returns boolean true if present else boolean false. The key point to remember is in java we only have true-false in boolean value nor do 0-1, take this note with you geeks. adnanirshad158 solankimayank clintra saurabh1990aror Java - util package Java-Collections Java-Functions java-treeset Java Java Java-Collections 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 Multidimensional Arrays in Java Singleton Class in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java
[ { "code": null, "e": 25486, "s": 25458, "text": "\n26 Jan, 2022" }, { "code": null, "e": 25824, "s": 25486, "text": "TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. " }, { "code": null, "e": 26105, "s": 25824, "text": "This class provides numerous methods of which let us discuss contains() method of TreeSet class present inside java.util package is used to check if a specific element is present in the TreeSet or not. So basically it is used to check if a TreeSet contains any particular element." }, { "code": null, "e": 26115, "s": 26105, "text": "Syntax: " }, { "code": null, "e": 26149, "s": 26115, "text": "Tree_Set.contains(Object element)" }, { "code": null, "e": 26267, "s": 26149, "text": "Parameters: The type of TreeSet. This is the element that needs to be checked if it is present in the TreeSet or not." }, { "code": null, "e": 26363, "s": 26267, "text": "Return Value: A boolean value, true if the element is present in the set else it returns false." }, { "code": null, "e": 26434, "s": 26363, "text": "Exceptions: It throws two types of exceptions listed below as follows:" }, { "code": null, "e": 26489, "s": 26434, "text": "NullPointerException: If the specified element is null" }, { "code": null, "e": 26604, "s": 26489, "text": "ClassCastException: If the specified element cannot be compared with the elements that currently exist in the set." }, { "code": null, "e": 26757, "s": 26604, "text": "Tip: As we do know treeSet uses natural ordering and its comparator does not permit the null elements hence forth NullPointerException arises into play." }, { "code": null, "e": 26765, "s": 26757, "text": "Example" }, { "code": null, "e": 26770, "s": 26765, "text": "Java" }, { "code": "// Java Program to Illustrate contains() method// of TreeSet class // Importing required classesimport java.io.*;import java.util.TreeSet; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty TreeSet of string type TreeSet<String> tree = new TreeSet<String>(); // Adding elements in TreeSet // Using add() method to tree.add(\"Welcome\"); tree.add(\"To\"); tree.add(\"Geeks\"); tree.add(\"4\"); tree.add(\"Geeks\"); tree.add(\"TreeSet\"); // Displaying the TreeSet System.out.println(\"TreeSet: \" + tree); // Use-case 1 // Check for specific element in the above TreeSet // object using contains() method of TreeSet class // Printing a boolean value System.out.println( \"Does the Set contains 'TreeSet'? \" + tree.contains(\"TreeSet\")); // Use-case 2 // Check for specific element in the above TreeSet // object Say custom element be \"4\" System.out.println(\"Does the Set contains '4'? \" + tree.contains(\"4\")); // Use-case 3 // Check if the list contains \"No\" System.out.println(\"Does the Set contains 'No'? \" + tree.contains(\"No\")); }}", "e": 28116, "s": 26770, "text": null }, { "code": null, "e": 28262, "s": 28116, "text": "TreeSet: [4, Geeks, To, TreeSet, Welcome]\nDoes the Set contains 'TreeSet'? true\nDoes the Set contains '4'? true\nDoes the Set contains 'No'? false" }, { "code": null, "e": 28284, "s": 28264, "text": "Output Explanation:" }, { "code": null, "e": 28652, "s": 28284, "text": "As we inserted elements in TreeSet {“Welcome”, “To”, “Geeks”, “4”, “Geeks”, “TreeSet”} then we checks for a specific elements bypassing element as an argument to contains() method which we now returns boolean true if present else boolean false. The key point to remember is in java we only have true-false in boolean value nor do 0-1, take this note with you geeks. " }, { "code": null, "e": 28667, "s": 28652, "text": "adnanirshad158" }, { "code": null, "e": 28681, "s": 28667, "text": "solankimayank" }, { "code": null, "e": 28689, "s": 28681, "text": "clintra" }, { "code": null, "e": 28705, "s": 28689, "text": "saurabh1990aror" }, { "code": null, "e": 28725, "s": 28705, "text": "Java - util package" }, { "code": null, "e": 28742, "s": 28725, "text": "Java-Collections" }, { "code": null, "e": 28757, "s": 28742, "text": "Java-Functions" }, { "code": null, "e": 28770, "s": 28757, "text": "java-treeset" }, { "code": null, "e": 28775, "s": 28770, "text": "Java" }, { "code": null, "e": 28780, "s": 28775, "text": "Java" }, { "code": null, "e": 28797, "s": 28780, "text": "Java-Collections" }, { "code": null, "e": 28895, "s": 28797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28910, "s": 28895, "text": "Stream In Java" }, { "code": null, "e": 28929, "s": 28910, "text": "Interfaces in Java" }, { "code": null, "e": 28947, "s": 28929, "text": "ArrayList in Java" }, { "code": null, "e": 28967, "s": 28947, "text": "Stack Class in Java" }, { "code": null, "e": 28999, "s": 28967, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29023, "s": 28999, "text": "Singleton Class in Java" }, { "code": null, "e": 29046, "s": 29023, "text": "Multithreading in Java" }, { "code": null, "e": 29066, "s": 29046, "text": "Collections in Java" }, { "code": null, "e": 29090, "s": 29066, "text": "Queue Interface In Java" } ]
Number of smaller circles that can be inscribed in a larger circle - GeeksforGeeks
22 Apr, 2021 Given two positive integers R1 and R2, where R1 and R2 represent the radius of the larger and smaller circles respectively, the task is to find out the number of smaller circles that can be placed inside the larger circle such that the smaller circle touches the boundary of the larger circle. Examples: Input: R1 = 3, R2 = 1Output: 6Explanation: The radii of the circles are 3 and 1. Therefore, the circle of radius 1 can be inscribed in the circle of radius 3. From the above representation, the total number of smaller circles that can be inscribed with touching of the boundary of the larger circle is 6. Input: R1 = 5, R2 = 4Output: 1 Approach: The given problem can be solved by finding the angle that the smaller circle of radius R2 makes at the centre of the circle with radius R1 and then divide it by 360 degrees. Follow the steps below to solve the given problem: If the value of R1 is less than R2, then it is impossible to inscribe a single circle. Therefore, print 0. If the value of R1 is less than 2 * R2, i.e. if the diameter of the smaller circle is greater than the radius of the larger circle, then only one circle can be inscribed. Therefore, print 1. Otherwise, find the angle made by the smaller circle at the centreof the larger circle using the below formula and then, divide by 360 degrees to get the total number of circles that can be inscribed and print that value. 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 number of smaller// circles that can be inscribed in// the larger circle touching its boundaryint countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = abs(asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = 360 / (2 * floor(angle)); } // Return the final result return number_of_circles;} // Driver Codeint main(){ int R1 = 3; int R2 = 1; cout << countInscribed(R1, R2); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to count number of smaller// circles that can be inscribed in// the larger circle touching its boundarystatic int countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.abs(Math.asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = (int)(360 / (2 * Math.floor(angle))); } // Return the final result return number_of_circles;} // Driver Codepublic static void main(String args[]){ int R1 = 3; int R2 = 1; System.out.println(countInscribed(R1, R2));}} // This code is contributed by ipg2016107 # Python3 program for the above approachimport math # Function to count number of smaller# circles that can be inscribed in# the larger circle touching its boundarydef countInscribed(R1, R2): # If R2 is greater than R1 if (R2 > R1): return 0 # Stores the angle made # by the smaller circle angle = 0 # Stores the ratio # of R2 / (R1 - R2) ratio = 0 # Stores the count of smaller # circles that can be inscribed number_of_circles = 0 # Stores the ratio ratio = R2 / (R1 - R2) # If the diameter of smaller # circle is greater than the # radius of the larger circle if (R1 < 2 * R2): number_of_circles = 1 # Otherwise else: # Find the angle using formula angle = (abs(math.asin(ratio) * 180) / 3.14159265) # Divide 360 with angle # and take the floor value number_of_circles = (360 / (2 * math.floor(angle))) # Return the final result return number_of_circles # Driver Codeif __name__ == "__main__": R1 = 3 R2 = 1 print (int(countInscribed(R1, R2))) # This code is contributed by ukasp // C# program for the above approachusing System; class GFG{ // Function to count number of smaller// circles that can be inscribed in// the larger circle touching its boundarystatic int countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.Abs(Math.Asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = (int)(360 / (2 * Math.Floor(angle))); } // Return the final result return number_of_circles;} // Driver Codepublic static void Main(){ int R1 = 3; int R2 = 1; Console.WriteLine(countInscribed(R1, R2));}} // This code is contributed by mohit kumar 29 <script> // Javascript program for the above approach // Function to count number of smaller // circles that can be inscribed in // the larger circle touching its boundary function countInscribed(R1, R2) { // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle let angle; // Stores the ratio // of R2 / (R1 - R2) let ratio; // Stores the count of smaller // circles that can be inscribed let number_of_circles = 0; // Stores the ratio ratio = R2 / (R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.abs(Math.asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = 360 / (2 * Math.floor(angle)); } // Return the final result return number_of_circles; } // Driver Code let R1 = 3; let R2 = 1; document.write(countInscribed(R1, R2)) // This code is contributed by Hritik </script> 6 Time Complexity: O(1)Auxiliary Space: O(1) ukasp ipg2016107 mohit kumar 29 hritikrommie Circle-Theorems Circles Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Equation of circle when three points on the circle are given Program to find line passing through 2 Points Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26855, "s": 26561, "text": "Given two positive integers R1 and R2, where R1 and R2 represent the radius of the larger and smaller circles respectively, the task is to find out the number of smaller circles that can be placed inside the larger circle such that the smaller circle touches the boundary of the larger circle." }, { "code": null, "e": 26865, "s": 26855, "text": "Examples:" }, { "code": null, "e": 27024, "s": 26865, "text": "Input: R1 = 3, R2 = 1Output: 6Explanation: The radii of the circles are 3 and 1. Therefore, the circle of radius 1 can be inscribed in the circle of radius 3." }, { "code": null, "e": 27170, "s": 27024, "text": "From the above representation, the total number of smaller circles that can be inscribed with touching of the boundary of the larger circle is 6." }, { "code": null, "e": 27201, "s": 27170, "text": "Input: R1 = 5, R2 = 4Output: 1" }, { "code": null, "e": 27436, "s": 27201, "text": "Approach: The given problem can be solved by finding the angle that the smaller circle of radius R2 makes at the centre of the circle with radius R1 and then divide it by 360 degrees. Follow the steps below to solve the given problem:" }, { "code": null, "e": 27543, "s": 27436, "text": "If the value of R1 is less than R2, then it is impossible to inscribe a single circle. Therefore, print 0." }, { "code": null, "e": 27734, "s": 27543, "text": "If the value of R1 is less than 2 * R2, i.e. if the diameter of the smaller circle is greater than the radius of the larger circle, then only one circle can be inscribed. Therefore, print 1." }, { "code": null, "e": 27956, "s": 27734, "text": "Otherwise, find the angle made by the smaller circle at the centreof the larger circle using the below formula and then, divide by 360 degrees to get the total number of circles that can be inscribed and print that value." }, { "code": null, "e": 28007, "s": 27956, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28011, "s": 28007, "text": "C++" }, { "code": null, "e": 28016, "s": 28011, "text": "Java" }, { "code": null, "e": 28024, "s": 28016, "text": "Python3" }, { "code": null, "e": 28027, "s": 28024, "text": "C#" }, { "code": null, "e": 28038, "s": 28027, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count number of smaller// circles that can be inscribed in// the larger circle touching its boundaryint countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = abs(asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = 360 / (2 * floor(angle)); } // Return the final result return number_of_circles;} // Driver Codeint main(){ int R1 = 3; int R2 = 1; cout << countInscribed(R1, R2); return 0;}", "e": 29278, "s": 28038, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to count number of smaller// circles that can be inscribed in// the larger circle touching its boundarystatic int countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.abs(Math.asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = (int)(360 / (2 * Math.floor(angle))); } // Return the final result return number_of_circles;} // Driver Codepublic static void main(String args[]){ int R1 = 3; int R2 = 1; System.out.println(countInscribed(R1, R2));}} // This code is contributed by ipg2016107", "e": 30580, "s": 29278, "text": null }, { "code": "# Python3 program for the above approachimport math # Function to count number of smaller# circles that can be inscribed in# the larger circle touching its boundarydef countInscribed(R1, R2): # If R2 is greater than R1 if (R2 > R1): return 0 # Stores the angle made # by the smaller circle angle = 0 # Stores the ratio # of R2 / (R1 - R2) ratio = 0 # Stores the count of smaller # circles that can be inscribed number_of_circles = 0 # Stores the ratio ratio = R2 / (R1 - R2) # If the diameter of smaller # circle is greater than the # radius of the larger circle if (R1 < 2 * R2): number_of_circles = 1 # Otherwise else: # Find the angle using formula angle = (abs(math.asin(ratio) * 180) / 3.14159265) # Divide 360 with angle # and take the floor value number_of_circles = (360 / (2 * math.floor(angle))) # Return the final result return number_of_circles # Driver Codeif __name__ == \"__main__\": R1 = 3 R2 = 1 print (int(countInscribed(R1, R2))) # This code is contributed by ukasp", "e": 31745, "s": 30580, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to count number of smaller// circles that can be inscribed in// the larger circle touching its boundarystatic int countInscribed(int R1, int R2){ // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle double angle; // Stores the ratio // of R2 / (R1 - R2) double ratio; // Stores the count of smaller // circles that can be inscribed int number_of_circles = 0; // Stores the ratio ratio = R2 / (double)(R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.Abs(Math.Asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = (int)(360 / (2 * Math.Floor(angle))); } // Return the final result return number_of_circles;} // Driver Codepublic static void Main(){ int R1 = 3; int R2 = 1; Console.WriteLine(countInscribed(R1, R2));}} // This code is contributed by mohit kumar 29", "e": 33029, "s": 31745, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to count number of smaller // circles that can be inscribed in // the larger circle touching its boundary function countInscribed(R1, R2) { // If R2 is greater than R1 if (R2 > R1) return 0; // Stores the angle made // by the smaller circle let angle; // Stores the ratio // of R2 / (R1 - R2) let ratio; // Stores the count of smaller // circles that can be inscribed let number_of_circles = 0; // Stores the ratio ratio = R2 / (R1 - R2); // If the diameter of smaller // circle is greater than the // radius of the larger circle if (R1 < 2 * R2) { number_of_circles = 1; } // Otherwise else { // Find the angle using formula angle = Math.abs(Math.asin(ratio) * 180) / 3.14159265; // Divide 360 with angle // and take the floor value number_of_circles = 360 / (2 * Math.floor(angle)); } // Return the final result return number_of_circles; } // Driver Code let R1 = 3; let R2 = 1; document.write(countInscribed(R1, R2)) // This code is contributed by Hritik </script>", "e": 34593, "s": 33029, "text": null }, { "code": null, "e": 34595, "s": 34593, "text": "6" }, { "code": null, "e": 34640, "s": 34597, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 34646, "s": 34640, "text": "ukasp" }, { "code": null, "e": 34657, "s": 34646, "text": "ipg2016107" }, { "code": null, "e": 34672, "s": 34657, "text": "mohit kumar 29" }, { "code": null, "e": 34685, "s": 34672, "text": "hritikrommie" }, { "code": null, "e": 34701, "s": 34685, "text": "Circle-Theorems" }, { "code": null, "e": 34709, "s": 34701, "text": "Circles" }, { "code": null, "e": 34719, "s": 34709, "text": "Geometric" }, { "code": null, "e": 34732, "s": 34719, "text": "Mathematical" }, { "code": null, "e": 34745, "s": 34732, "text": "Mathematical" }, { "code": null, "e": 34755, "s": 34745, "text": "Geometric" }, { "code": null, "e": 34853, "s": 34755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34919, "s": 34853, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 34951, "s": 34919, "text": "Program to find slope of a line" }, { "code": null, "e": 35012, "s": 34951, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 35058, "s": 35012, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 35128, "s": 35058, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 35158, "s": 35128, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35218, "s": 35158, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35233, "s": 35218, "text": "C++ Data Types" }, { "code": null, "e": 35276, "s": 35233, "text": "Set in C++ Standard Template Library (STL)" } ]
How to use React.cloneElement() function? - GeeksforGeeks
31 Mar, 2021 We can use React.cloneElement() method when a parent component wants to add or modify the props of its children. The React.cloneElement() function creates a clone of a given element, and we can also pass props and children in the function. The resultant element would have the initial element’s props mixed in shallowly with the new props. Existing children will be replaced by new children. The original element’s key and the ref will be preserved. Syntax: React.cloneElement( element, [props], [...children] ) The first argument is the element that we want to clone. The second argument will be additional props that we want to add with the element. And the third argument will be the children of cloned elements and children of the existing element will not be copied in cloned elements. Cloning an element with React.cloneElement() is almost the same as: <element.type {...element.props} {...new_props}> {new_children} </element.type> However, it also preserves refs. This means you won’t unintentionally steal a ref from your ancestor if you have a child with one. The same ref will be assigned to your new element. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';class App extends React.Component { render() { return ( <Parent> <Button /> <br /><br /> <Button /> </Parent> ) }} class Parent extends React.Component { render() { let btncolor = 'red'; return ( <div> {React.Children.map(this.props.children, child => { return React.cloneElement(child, { btncolor }, null); //third parameter is null // Because we are not adding any children })} </div> ) }} class Button extends React.Component { render() { return ( <button style= {{ color: this.props.btncolor }}> Hello from GFG </button> ) }} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Explanation: As we can see from the above code Parent component is adding new props for the text color to the child (Button) component using React.cloneElement() method. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26311, "s": 26071, "text": "We can use React.cloneElement() method when a parent component wants to add or modify the props of its children. The React.cloneElement() function creates a clone of a given element, and we can also pass props and children in the function." }, { "code": null, "e": 26521, "s": 26311, "text": "The resultant element would have the initial element’s props mixed in shallowly with the new props. Existing children will be replaced by new children. The original element’s key and the ref will be preserved." }, { "code": null, "e": 26529, "s": 26521, "text": "Syntax:" }, { "code": null, "e": 26586, "s": 26529, "text": "React.cloneElement(\n element,\n [props],\n [...children]\n)" }, { "code": null, "e": 26865, "s": 26586, "text": "The first argument is the element that we want to clone. The second argument will be additional props that we want to add with the element. And the third argument will be the children of cloned elements and children of the existing element will not be copied in cloned elements." }, { "code": null, "e": 26933, "s": 26865, "text": "Cloning an element with React.cloneElement() is almost the same as:" }, { "code": null, "e": 27016, "s": 26933, "text": "<element.type {...element.props} {...new_props}>\n {new_children}\n</element.type>" }, { "code": null, "e": 27198, "s": 27016, "text": "However, it also preserves refs. This means you won’t unintentionally steal a ref from your ancestor if you have a child with one. The same ref will be assigned to your new element." }, { "code": null, "e": 27226, "s": 27198, "text": "Creating React Application:" }, { "code": null, "e": 27321, "s": 27226, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 27385, "s": 27321, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27417, "s": 27385, "text": "npx create-react-app foldername" }, { "code": null, "e": 27530, "s": 27417, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 27630, "s": 27530, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 27644, "s": 27630, "text": "cd foldername" }, { "code": null, "e": 27696, "s": 27644, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27825, "s": 27696, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27832, "s": 27825, "text": "App.js" }, { "code": "import React from 'react';class App extends React.Component { render() { return ( <Parent> <Button /> <br /><br /> <Button /> </Parent> ) }} class Parent extends React.Component { render() { let btncolor = 'red'; return ( <div> {React.Children.map(this.props.children, child => { return React.cloneElement(child, { btncolor }, null); //third parameter is null // Because we are not adding any children })} </div> ) }} class Button extends React.Component { render() { return ( <button style= {{ color: this.props.btncolor }}> Hello from GFG </button> ) }} export default App", "e": 28564, "s": 27832, "text": null }, { "code": null, "e": 28677, "s": 28564, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28687, "s": 28677, "text": "npm start" }, { "code": null, "e": 28786, "s": 28687, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28956, "s": 28786, "text": "Explanation: As we can see from the above code Parent component is adding new props for the text color to the child (Button) component using React.cloneElement() method." }, { "code": null, "e": 28963, "s": 28956, "text": "Picked" }, { "code": null, "e": 28979, "s": 28963, "text": "React-Questions" }, { "code": null, "e": 28987, "s": 28979, "text": "ReactJS" }, { "code": null, "e": 29004, "s": 28987, "text": "Web Technologies" }, { "code": null, "e": 29102, "s": 29004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29129, "s": 29102, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29171, "s": 29129, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29209, "s": 29171, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 29244, "s": 29209, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29302, "s": 29244, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29342, "s": 29302, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29375, "s": 29342, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29420, "s": 29375, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29470, "s": 29420, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to prevent text in a table cell from wrapping using CSS? - GeeksforGeeks
26 Feb, 2019 Given a table which contains the table head and body section. The task is to prevent the text in a table cell from wrapping using CSS. To achieve this we use white-space property of CSS. This property forces the contents of th to display in one line. There are many property values exists to the white-space function. Syntax: white-space: normal|nowrap|pre|pre-wrap|pre-line; Example 1: This example uses white-space property to prevent cell wrapping using CSS. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>white-space property</title> <style> th { white-space: nowrap; } </style> </head> <body> <table border="1" collap> <thead> <tr> <th>First Heading of GeeksforGeeks</th> <th>Second Heading of GeeksforGeeks</th> <th>Third Heading of GeeksforGeeks</th> <th>Fourth Heading of GeeksforGeeks</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>Value</td> <td>Value</td> <td>Value</td> </tr> </tbody> </table> </body></html> Output:Before applying white-space property:After applying white-space property: Example 2: This example uses inline white-space property. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>white-space property</title> </head> <body> <table border="1" collap> <thead> <tr> <th style="white-space: nowrap;"> First Heading of GeeksforGeeks </th> <th>Second Heading of GeeksforGeeks</th> <th style="white-space: nowrap;"> Third Heading of GeeksforGeeks </th> <th>Fourth Heading of GeeksforGeeks</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>Value</td> <td>Value</td> <td>Value</td> </tr> </tbody> </table> </body></html> Output:Before applying white-space property:After applying white-space property: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 25925, "s": 25897, "text": "\n26 Feb, 2019" }, { "code": null, "e": 26243, "s": 25925, "text": "Given a table which contains the table head and body section. The task is to prevent the text in a table cell from wrapping using CSS. To achieve this we use white-space property of CSS. This property forces the contents of th to display in one line. There are many property values exists to the white-space function." }, { "code": null, "e": 26251, "s": 26243, "text": "Syntax:" }, { "code": null, "e": 26301, "s": 26251, "text": "white-space: normal|nowrap|pre|pre-wrap|pre-line;" }, { "code": null, "e": 26387, "s": 26301, "text": "Example 1: This example uses white-space property to prevent cell wrapping using CSS." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title>white-space property</title> <style> th { white-space: nowrap; } </style> </head> <body> <table border=\"1\" collap> <thead> <tr> <th>First Heading of GeeksforGeeks</th> <th>Second Heading of GeeksforGeeks</th> <th>Third Heading of GeeksforGeeks</th> <th>Fourth Heading of GeeksforGeeks</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>Value</td> <td>Value</td> <td>Value</td> </tr> </tbody> </table> </body></html>", "e": 27148, "s": 26387, "text": null }, { "code": null, "e": 27229, "s": 27148, "text": "Output:Before applying white-space property:After applying white-space property:" }, { "code": null, "e": 27287, "s": 27229, "text": "Example 2: This example uses inline white-space property." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title>white-space property</title> </head> <body> <table border=\"1\" collap> <thead> <tr> <th style=\"white-space: nowrap;\"> First Heading of GeeksforGeeks </th> <th>Second Heading of GeeksforGeeks</th> <th style=\"white-space: nowrap;\"> Third Heading of GeeksforGeeks </th> <th>Fourth Heading of GeeksforGeeks</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td>Value</td> <td>Value</td> <td>Value</td> </tr> </tbody> </table> </body></html>", "e": 28135, "s": 27287, "text": null }, { "code": null, "e": 28216, "s": 28135, "text": "Output:Before applying white-space property:After applying white-space property:" }, { "code": null, "e": 28353, "s": 28216, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28362, "s": 28353, "text": "CSS-Misc" }, { "code": null, "e": 28369, "s": 28362, "text": "Picked" }, { "code": null, "e": 28373, "s": 28369, "text": "CSS" }, { "code": null, "e": 28378, "s": 28373, "text": "HTML" }, { "code": null, "e": 28395, "s": 28378, "text": "Web Technologies" }, { "code": null, "e": 28400, "s": 28395, "text": "HTML" }, { "code": null, "e": 28498, "s": 28400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28546, "s": 28498, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28601, "s": 28546, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28638, "s": 28601, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28702, "s": 28638, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28741, "s": 28702, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28789, "s": 28741, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28849, "s": 28789, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28902, "s": 28849, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28963, "s": 28902, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Convert an arbitrary Binary Tree to a tree that holds Children Sum Property - GeeksforGeeks
01 Apr, 2022 Question: Given an arbitrary binary tree, convert it to a binary tree that holds Children Sum Property. You can only increment data values in any node (You cannot change the structure of the tree and cannot decrement the value of any node). For example, the below tree doesn’t hold the children sum property, convert it to a tree that holds the property. 50 / \ / \ 7 2 / \ /\ / \ / \ 3 5 1 30 Algorithm: Traverse the given tree in post order to convert it, i.e., first change left and right children to hold the children sum property then change the parent node. Let difference between node’s data and children sum be diff. diff = node’s children sum - node’s data If diff is 0 then nothing needs to be done. If diff > 0 ( node’s data is smaller than node’s children sum) increment the node’s data by diff.If diff < 0 (node’s data is greater than the node’s children sum) then increment one child’s data. We can choose to increment either left or right child if they both are not NULL. Let us always first increment the left child. Incrementing a child changes the subtree’s children sum property so we need to change left subtree also. So we recursively increment the left child. If left child is empty then we recursively call increment() for right child.Let us run the algorithm for the given example. First convert the left subtree (increment 7 to 8). 50 / \ / \ 8 2 / \ /\ / \ / \ 3 5 1 30 Then convert the right subtree (increment 2 to 31) 50 / \ / \ 8 31 / \ / \ / \ / \ 3 5 1 30 Now convert the root, we have to increment left subtree for converting the root. 50 / \ / \ 19 31 / \ / \ / \ / \ 14 5 1 30 Please note the last step – we have incremented 8 to 19, and to fix the subtree we have incremented 3 to 14.Implementation: C++ C Java Python3 C# Javascript /* C++ Program to convert an arbitrarybinary tree to a tree that holdchildren sum property */#include<bits/stdc++.h>using namespace std; class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; /* This function is usedto increment left subtree */void increment(node* node, int diff); /* This function changes a treeto hold children sum property */void convertTree(node* node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == NULL || (node->left == NULL && node->right == NULL)) return; else { /* convert left and right subtrees */ convertTree(node->left); convertTree(node->right); /* If left child is not present then 0 is used as data of left child */ if (node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if (node->right != NULL) right_data = node->right->data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node->data; /* If node's children sum is greater than the node's data */ if (diff > 0) node->data = node->data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) increment(node, -diff); // -diff is used to make diff positive }} /* This function is usedto increment subtree by diff */void increment(node* node, int diff){ /* IF left child is not NULL then increment it */ if(node->left != NULL) { node->left->data = node->left->data + diff; // Recursively call to fix // the descendants of node->left increment(node->left, diff); } else if (node->right != NULL) // Else increment right child { node->right->data = node->right->data + diff; // Recursively call to fix // the descendants of node->right increment(node->right, diff); }} /* Given a binary tree,printInorder() prints out itsinorder traversal*/void printInorder(node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout<<node->data<<" "; /* now recur on right child */ printInorder(node->right);} /* Driver code */int main(){ node *root = new node(50); root->left = new node(7); root->right = new node(2); root->left->left = new node(3); root->left->right = new node(5); root->right->left = new node(1); root->right->right = new node(30); cout << "\nInorder traversal before conversion: " << endl; printInorder(root); convertTree(root); cout << "\nInorder traversal after conversion: " << endl; printInorder(root); return 0;} // This code is contributed by rathbhupendra /* Program to convert an arbitrary binary tree to a tree that holds children sum property */ #include <stdio.h>#include <stdlib.h> struct node{ int data; struct node* left; struct node* right;}; /* This function is used to increment left subtree */void increment(struct node* node, int diff); /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data); /* This function changes a tree to hold children sum property */void convertTree(struct node* node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == NULL || (node->left == NULL && node->right == NULL)) return; else { /* convert left and right subtrees */ convertTree(node->left); convertTree(node->right); /* If left child is not present then 0 is used as data of left child */ if (node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if (node->right != NULL) right_data = node->right->data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node->data; /* If node's children sum is greater than the node's data */ if (diff > 0) node->data = node->data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) increment(node, -diff); // -diff is used to make diff positive }} /* This function is used to increment subtree by diff */void increment(struct node* node, int diff){ /* IF left child is not NULL then increment it */ if(node->left != NULL) { node->left->data = node->left->data + diff; // Recursively call to fix the descendants of node->left increment(node->left, diff); } else if (node->right != NULL) // Else increment right child { node->right->data = node->right->data + diff; // Recursively call to fix the descendants of node->right increment(node->right, diff); }} /* Given a binary tree, printInorder() prints out its inorder traversal*/void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ printInorder(node->right);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions */int main(){ struct node *root = newNode(50); root->left = newNode(7); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(1); root->right->right = newNode(30); printf("\n Inorder traversal before conversion "); printInorder(root); convertTree(root); printf("\n Inorder traversal after conversion "); printInorder(root); getchar(); return 0;} // Java program to convert an arbitrary binary tree to a tree that holds// children sum property // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function changes a tree to hold children sum property */ void convertTree(Node node) { int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return; else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) node.data = node.data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) // -diff is used to make diff positive increment(node, -diff); } } /* This function is used to increment subtree by diff */ void increment(Node node, int diff) { /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the descendants of node->right increment(node.right, diff); } } /* Given a binary tree, printInorder() prints out its inorder traversal*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " "); /* now recur on right child */ printInorder(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(50); tree.root.left = new Node(7); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(1); tree.root.right.right = new Node(30); System.out.println("Inorder traversal before conversion is :"); tree.printInorder(tree.root); tree.convertTree(tree.root); System.out.println(""); System.out.println("Inorder traversal after conversion is :"); tree.printInorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Program to convert an arbitrary binary tree# to a tree that holds children sum property # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # This function changes a tree to# hold children sum propertydef convertTree(node): left_data = 0 right_data = 0 diff=0 # If tree is empty or it's a # leaf node then return true if (node == None or (node.left == None and node.right == None)): return else: """ convert left and right subtrees """ convertTree(node.left) convertTree(node.right) """ If left child is not present then 0 is used as data of left child """ if (node.left != None): left_data = node.left.data """ If right child is not present then 0 is used as data of right child """ if (node.right != None): right_data = node.right.data """ get the diff of node's data and children sum """ diff = left_data + right_data - node.data """ If node's children sum is greater than the node's data """ if (diff > 0): node.data = node.data + diff """ THIS IS TRICKY -. If node's data is greater than children sum, then increment subtree by diff """ if (diff < 0): increment(node, -diff) # -diff is used to # make diff positive """ This function is used to increment subtree by diff """def increment(node, diff): """ IF left child is not None then increment it """ if(node.left != None): node.left.data = node.left.data + diff # Recursively call to fix the # descendants of node.left increment(node.left, diff) elif(node.right != None): # Else increment right child node.right.data = node.right.data + diff # Recursively call to fix the # descendants of node.right increment(node.right, diff) """ Given a binary tree, printInorder()prints out its inorder traversal"""def printInorder(node): if (node == None): return """ first recur on left child """ printInorder(node.left) """ then print the data of node """ print(node.data,end=" ") """ now recur on right child """ printInorder(node.right) # Driver Codeif __name__ == '__main__': root = newNode(50) root.left = newNode(7) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) root.right.left = newNode(1) root.right.right = newNode(30) print("Inorder traversal before conversion") printInorder(root) convertTree(root) print("\nInorder traversal after conversion ") printInorder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to convert an arbitrary// binary tree to a tree that holds// children sum propertyusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; /* This function changes a tree tohold children sum property */public virtual void convertTree(Node node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) { return; } else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) { left_data = node.left.data; } /* If right child is not present then 0 is used as data of right child */ if (node.right != null) { right_data = node.right.data; } /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) { node.data = node.data + diff; } /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) { // -diff is used to make diff positive increment(node, -diff); } }} /* This function is used to incrementsubtree by diff */public virtual void increment(Node node, int diff){ /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the // descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the // descendants of node->right increment(node.right, diff); }} /* Given a binary tree, printInorder()prints out its inorder traversal*/public virtual void printInorder(Node node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + " "); /* now recur on right child */ printInorder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(50); tree.root.left = new Node(7); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(1); tree.root.right.right = new Node(30); Console.WriteLine("Inorder traversal " + "before conversion is :"); tree.printInorder(tree.root); tree.convertTree(tree.root); Console.WriteLine(""); Console.WriteLine("Inorder traversal " + "after conversion is :"); tree.printInorder(tree.root);}} // This code is contributed by Shrikant13 <script> // JavaScript program to convert an arbitrary binary tree // to a tree that holds children sum property class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function changes a tree to hold children sum property */ function convertTree(node) { let left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return; else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) node.data = node.data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) // -diff is used to make diff positive increment(node, -diff); } } /* This function is used to increment subtree by diff */ function increment(node, diff) { /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the // descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the // descendants of node->right increment(node.right, diff); } } /* Given a binary tree, printInorder() prints out its inorder traversal*/ function printInorder(node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + " "); /* now recur on right child */ printInorder(node.right); } root = new Node(50); root.left = new Node(7); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.left = new Node(1); root.right.right = new Node(30); document.write("Inorder traversal before conversion is :" + "</br>"); printInorder(root); convertTree(root); document.write("</br>"); document.write("Inorder traversal after conversion is :" + "</br>"); printInorder(root); </script> Output: Inorder traversal before conversion is : 3 7 5 50 1 2 30 Inorder traversal after conversion is : 14 19 5 50 1 31 30 Time Complexity: O(n^2), Worst case complexity is for a skewed tree such that nodes are in decreasing order from root to leaf. YouTubeGeeksforGeeks508K subscribersConvert an arbitrary Binary Tree to a tree that holds Children Sum Property | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=N5GfUMSKslo" 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 any bug in the above algorithm or a better way to solve the same problem. shrikanth13 SHUBHAMSINGH10 rathbhupendra Akanksha_Rai nidhi_biet rameshtravel07 simmytarika5 nikhatkhan11 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Print Binary Tree in 2-Dimensions Real-time application of Data Structures Iterative Postorder Traversal | Set 2 (Using One Stack) Find maximum (or minimum) in Binary Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Min Heap and Max Heap
[ { "code": null, "e": 26185, "s": 26157, "text": "\n01 Apr, 2022" }, { "code": null, "e": 26541, "s": 26185, "text": "Question: Given an arbitrary binary tree, convert it to a binary tree that holds Children Sum Property. You can only increment data values in any node (You cannot change the structure of the tree and cannot decrement the value of any node). For example, the below tree doesn’t hold the children sum property, convert it to a tree that holds the property. " }, { "code": null, "e": 26703, "s": 26541, "text": " 50\n / \\ \n / \\\n 7 2\n / \\ /\\\n / \\ / \\\n 3 5 1 30" }, { "code": null, "e": 26936, "s": 26703, "text": "Algorithm: Traverse the given tree in post order to convert it, i.e., first change left and right children to hold the children sum property then change the parent node. Let difference between node’s data and children sum be diff. " }, { "code": null, "e": 26984, "s": 26936, "text": " diff = node’s children sum - node’s data " }, { "code": null, "e": 27677, "s": 26984, "text": "If diff is 0 then nothing needs to be done. If diff > 0 ( node’s data is smaller than node’s children sum) increment the node’s data by diff.If diff < 0 (node’s data is greater than the node’s children sum) then increment one child’s data. We can choose to increment either left or right child if they both are not NULL. Let us always first increment the left child. Incrementing a child changes the subtree’s children sum property so we need to change left subtree also. So we recursively increment the left child. If left child is empty then we recursively call increment() for right child.Let us run the algorithm for the given example. First convert the left subtree (increment 7 to 8). " }, { "code": null, "e": 27839, "s": 27677, "text": " 50\n / \\ \n / \\\n 8 2\n / \\ /\\\n / \\ / \\\n 3 5 1 30" }, { "code": null, "e": 27891, "s": 27839, "text": "Then convert the right subtree (increment 2 to 31) " }, { "code": null, "e": 28029, "s": 27891, "text": " 50\n / \\ \n / \\\n 8 31\n / \\ / \\\n / \\ / \\\n3 5 1 30" }, { "code": null, "e": 28112, "s": 28029, "text": "Now convert the root, we have to increment left subtree for converting the root. " }, { "code": null, "e": 28253, "s": 28112, "text": " 50\n / \\ \n / \\\n 19 31\n / \\ / \\\n / \\ / \\\n14 5 1 30" }, { "code": null, "e": 28379, "s": 28253, "text": "Please note the last step – we have incremented 8 to 19, and to fix the subtree we have incremented 3 to 14.Implementation: " }, { "code": null, "e": 28383, "s": 28379, "text": "C++" }, { "code": null, "e": 28385, "s": 28383, "text": "C" }, { "code": null, "e": 28390, "s": 28385, "text": "Java" }, { "code": null, "e": 28398, "s": 28390, "text": "Python3" }, { "code": null, "e": 28401, "s": 28398, "text": "C#" }, { "code": null, "e": 28412, "s": 28401, "text": "Javascript" }, { "code": "/* C++ Program to convert an arbitrarybinary tree to a tree that holdchildren sum property */#include<bits/stdc++.h>using namespace std; class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; /* This function is usedto increment left subtree */void increment(node* node, int diff); /* This function changes a treeto hold children sum property */void convertTree(node* node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == NULL || (node->left == NULL && node->right == NULL)) return; else { /* convert left and right subtrees */ convertTree(node->left); convertTree(node->right); /* If left child is not present then 0 is used as data of left child */ if (node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if (node->right != NULL) right_data = node->right->data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node->data; /* If node's children sum is greater than the node's data */ if (diff > 0) node->data = node->data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) increment(node, -diff); // -diff is used to make diff positive }} /* This function is usedto increment subtree by diff */void increment(node* node, int diff){ /* IF left child is not NULL then increment it */ if(node->left != NULL) { node->left->data = node->left->data + diff; // Recursively call to fix // the descendants of node->left increment(node->left, diff); } else if (node->right != NULL) // Else increment right child { node->right->data = node->right->data + diff; // Recursively call to fix // the descendants of node->right increment(node->right, diff); }} /* Given a binary tree,printInorder() prints out itsinorder traversal*/void printInorder(node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout<<node->data<<\" \"; /* now recur on right child */ printInorder(node->right);} /* Driver code */int main(){ node *root = new node(50); root->left = new node(7); root->right = new node(2); root->left->left = new node(3); root->left->right = new node(5); root->right->left = new node(1); root->right->right = new node(30); cout << \"\\nInorder traversal before conversion: \" << endl; printInorder(root); convertTree(root); cout << \"\\nInorder traversal after conversion: \" << endl; printInorder(root); return 0;} // This code is contributed by rathbhupendra", "e": 31638, "s": 28412, "text": null }, { "code": "/* Program to convert an arbitrary binary tree to a tree that holds children sum property */ #include <stdio.h>#include <stdlib.h> struct node{ int data; struct node* left; struct node* right;}; /* This function is used to increment left subtree */void increment(struct node* node, int diff); /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data); /* This function changes a tree to hold children sum property */void convertTree(struct node* node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == NULL || (node->left == NULL && node->right == NULL)) return; else { /* convert left and right subtrees */ convertTree(node->left); convertTree(node->right); /* If left child is not present then 0 is used as data of left child */ if (node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if (node->right != NULL) right_data = node->right->data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node->data; /* If node's children sum is greater than the node's data */ if (diff > 0) node->data = node->data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) increment(node, -diff); // -diff is used to make diff positive }} /* This function is used to increment subtree by diff */void increment(struct node* node, int diff){ /* IF left child is not NULL then increment it */ if(node->left != NULL) { node->left->data = node->left->data + diff; // Recursively call to fix the descendants of node->left increment(node->left, diff); } else if (node->right != NULL) // Else increment right child { node->right->data = node->right->data + diff; // Recursively call to fix the descendants of node->right increment(node->right, diff); }} /* Given a binary tree, printInorder() prints out its inorder traversal*/void printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf(\"%d \", node->data); /* now recur on right child */ printInorder(node->right);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions */int main(){ struct node *root = newNode(50); root->left = newNode(7); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(1); root->right->right = newNode(30); printf(\"\\n Inorder traversal before conversion \"); printInorder(root); convertTree(root); printf(\"\\n Inorder traversal after conversion \"); printInorder(root); getchar(); return 0;}", "e": 34812, "s": 31638, "text": null }, { "code": " // Java program to convert an arbitrary binary tree to a tree that holds// children sum property // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function changes a tree to hold children sum property */ void convertTree(Node node) { int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return; else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) node.data = node.data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) // -diff is used to make diff positive increment(node, -diff); } } /* This function is used to increment subtree by diff */ void increment(Node node, int diff) { /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the descendants of node->right increment(node.right, diff); } } /* Given a binary tree, printInorder() prints out its inorder traversal*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(50); tree.root.left = new Node(7); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(1); tree.root.right.right = new Node(30); System.out.println(\"Inorder traversal before conversion is :\"); tree.printInorder(tree.root); tree.convertTree(tree.root); System.out.println(\"\"); System.out.println(\"Inorder traversal after conversion is :\"); tree.printInorder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 38294, "s": 34812, "text": null }, { "code": "# Program to convert an arbitrary binary tree# to a tree that holds children sum property # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # This function changes a tree to# hold children sum propertydef convertTree(node): left_data = 0 right_data = 0 diff=0 # If tree is empty or it's a # leaf node then return true if (node == None or (node.left == None and node.right == None)): return else: \"\"\" convert left and right subtrees \"\"\" convertTree(node.left) convertTree(node.right) \"\"\" If left child is not present then 0 is used as data of left child \"\"\" if (node.left != None): left_data = node.left.data \"\"\" If right child is not present then 0 is used as data of right child \"\"\" if (node.right != None): right_data = node.right.data \"\"\" get the diff of node's data and children sum \"\"\" diff = left_data + right_data - node.data \"\"\" If node's children sum is greater than the node's data \"\"\" if (diff > 0): node.data = node.data + diff \"\"\" THIS IS TRICKY -. If node's data is greater than children sum, then increment subtree by diff \"\"\" if (diff < 0): increment(node, -diff) # -diff is used to # make diff positive \"\"\" This function is used to increment subtree by diff \"\"\"def increment(node, diff): \"\"\" IF left child is not None then increment it \"\"\" if(node.left != None): node.left.data = node.left.data + diff # Recursively call to fix the # descendants of node.left increment(node.left, diff) elif(node.right != None): # Else increment right child node.right.data = node.right.data + diff # Recursively call to fix the # descendants of node.right increment(node.right, diff) \"\"\" Given a binary tree, printInorder()prints out its inorder traversal\"\"\"def printInorder(node): if (node == None): return \"\"\" first recur on left child \"\"\" printInorder(node.left) \"\"\" then print the data of node \"\"\" print(node.data,end=\" \") \"\"\" now recur on right child \"\"\" printInorder(node.right) # Driver Codeif __name__ == '__main__': root = newNode(50) root.left = newNode(7) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) root.right.left = newNode(1) root.right.right = newNode(30) print(\"Inorder traversal before conversion\") printInorder(root) convertTree(root) print(\"\\nInorder traversal after conversion \") printInorder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 41215, "s": 38294, "text": null }, { "code": "// C# program to convert an arbitrary// binary tree to a tree that holds// children sum propertyusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; /* This function changes a tree tohold children sum property */public virtual void convertTree(Node node){ int left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) { return; } else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) { left_data = node.left.data; } /* If right child is not present then 0 is used as data of right child */ if (node.right != null) { right_data = node.right.data; } /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) { node.data = node.data + diff; } /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) { // -diff is used to make diff positive increment(node, -diff); } }} /* This function is used to incrementsubtree by diff */public virtual void increment(Node node, int diff){ /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the // descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the // descendants of node->right increment(node.right, diff); }} /* Given a binary tree, printInorder()prints out its inorder traversal*/public virtual void printInorder(Node node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + \" \"); /* now recur on right child */ printInorder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(50); tree.root.left = new Node(7); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(1); tree.root.right.right = new Node(30); Console.WriteLine(\"Inorder traversal \" + \"before conversion is :\"); tree.printInorder(tree.root); tree.convertTree(tree.root); Console.WriteLine(\"\"); Console.WriteLine(\"Inorder traversal \" + \"after conversion is :\"); tree.printInorder(tree.root);}} // This code is contributed by Shrikant13", "e": 44499, "s": 41215, "text": null }, { "code": "<script> // JavaScript program to convert an arbitrary binary tree // to a tree that holds children sum property class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function changes a tree to hold children sum property */ function convertTree(node) { let left_data = 0, right_data = 0, diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return; else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0) node.data = node.data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0) // -diff is used to make diff positive increment(node, -diff); } } /* This function is used to increment subtree by diff */ function increment(node, diff) { /* IF left child is not NULL then increment it */ if (node.left != null) { node.left.data = node.left.data + diff; // Recursively call to fix the // descendants of node->left increment(node.left, diff); } else if (node.right != null) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the // descendants of node->right increment(node.right, diff); } } /* Given a binary tree, printInorder() prints out its inorder traversal*/ function printInorder(node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } root = new Node(50); root.left = new Node(7); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.left = new Node(1); root.right.right = new Node(30); document.write(\"Inorder traversal before conversion is :\" + \"</br>\"); printInorder(root); convertTree(root); document.write(\"</br>\"); document.write(\"Inorder traversal after conversion is :\" + \"</br>\"); printInorder(root); </script>", "e": 47774, "s": 44499, "text": null }, { "code": null, "e": 47784, "s": 47774, "text": "Output: " }, { "code": null, "e": 47900, "s": 47784, "text": "Inorder traversal before conversion is :\n3 7 5 50 1 2 30\nInorder traversal after conversion is :\n14 19 5 50 1 31 30" }, { "code": null, "e": 48028, "s": 47900, "text": "Time Complexity: O(n^2), Worst case complexity is for a skewed tree such that nodes are in decreasing order from root to leaf. " }, { "code": null, "e": 48902, "s": 48028, "text": "YouTubeGeeksforGeeks508K subscribersConvert an arbitrary Binary Tree to a tree that holds Children Sum Property | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=N5GfUMSKslo\" 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": 49011, "s": 48902, "text": "Please write comments if you find any bug in the above algorithm or a better way to solve the same problem. " }, { "code": null, "e": 49023, "s": 49011, "text": "shrikanth13" }, { "code": null, "e": 49038, "s": 49023, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 49052, "s": 49038, "text": "rathbhupendra" }, { "code": null, "e": 49065, "s": 49052, "text": "Akanksha_Rai" }, { "code": null, "e": 49076, "s": 49065, "text": "nidhi_biet" }, { "code": null, "e": 49091, "s": 49076, "text": "rameshtravel07" }, { "code": null, "e": 49104, "s": 49091, "text": "simmytarika5" }, { "code": null, "e": 49117, "s": 49104, "text": "nikhatkhan11" }, { "code": null, "e": 49122, "s": 49117, "text": "Tree" }, { "code": null, "e": 49127, "s": 49122, "text": "Tree" }, { "code": null, "e": 49225, "s": 49127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49261, "s": 49225, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 49301, "s": 49261, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 49344, "s": 49301, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 49401, "s": 49344, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 49435, "s": 49401, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 49476, "s": 49435, "text": "Real-time application of Data Structures" }, { "code": null, "e": 49532, "s": 49476, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 49573, "s": 49532, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 49643, "s": 49573, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" } ]
Find the total guests that are present at the party - GeeksforGeeks
01 Apr, 2021 A person hosts a party and invites N guests to it. However, each guest has a condition, that each guest ‘Gi’ only stays at the party if there are at least ‘Pi’ people already at the party, otherwise leaves. The total number of guests N and the number of people each guest needs ‘Pi’ are given as input for each guest. The task is to find the total guests that are present at the party. It is also given that the guests arrive at the party in the order given in the array ‘Pi’Examples: Input: N = 5, Pi = {1, 0, 2, 1, 3} Output: 2 Explanation: Since 5 guests are invited to the party. Total guest present initially = 0 For Guest number 1: The 1st guest needs at least 1 person, since he is the first to arrive, and there is no one else, so he leaves. Therefore, Total guest so far = 0 For Guest number 2: The 2nd guest needs 0 people, so he stays. Therefore, Total guest so far = 0 + 1 = 1 For Guest number 3: The 3rd guest needs at least 2 people, And there are still only 1 guest present, so he leaves. Therefore, Total guest so far = 1 + 0 = 1 For Guest number 4: The 4th guest needs at least 1 people, And there is 1 guest present, so he stays. Therefore, Total guest so far = 1 + 1 = 2 For Guest number 5: The 5th guest needs at least 3 people, And there is only 2 guest present, so he leaves. Therefore, Total guest so far = 2 + 0 = 2 Total guests that are present at the party = 2. Input: N = 3, Pi = {0, 2, 1} Output: 2 Explanation: Since 3 guests are invited to the party. Total guest present initially = 0 For Guest number 1: The 1st guest needs 0 people, so he stays. Therefore, Total guest so far = 1 For Guest number 2: The 2nd guest needs at least 2 people, And there are still only 1 guest present, so he leaves. Therefore, Total guest so far = 1 + 0 = 1 For Guest number 3: The 3rd guest needs at least 1 people, And there is 1 guest present, so he stays. Therefore, Total guest so far = 1 + 1 = 2 Total guests that are present at the party = 2. Approach: Get the number of guests invited in N and the requirement of each guest in array guest[]. Initialize totalGuests to 0, as the total number of guests present. Iterate in the array guest[] from 0 to N-1. If the requirement of the guest is less than or equal to totalGuests, Increment totalGuests by 1 When complete array guest[] has been traversed, print the total number of guests ‘totalGuests’ Implementation: C++ Java Python3 C# PHP Javascript // C++ program to get the// total number of guests at the party #include <bits/stdc++.h>using namespace std; // Function to find the totalGuestsint findGuest(int array[], int N){ // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count;} // Driver codeint main(){ // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int guests[] = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); cout << totalGuests << endl; return 0;} // Java program to get the// total number of guests at the partyclass GFG{ // Function to find the totalGuestsstatic int findGuest(int array[], int N){ // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count;} // Driver codepublic static void main(String[] args){ // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int guests[] = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); System.out.println(totalGuests);}} // This code is contributed by Code_Mech # Python3 program to get the# total number of guests at the party # Function to find the totalGuestsdef findGuest(guests, N): count = 0 # Checking requirements for each guest for i in range(N): # If requirements are met if guests[i] <= count: # The Gi guest decides to stay # So increment total guest by 1 count += 1 # Return the totalnumber of gues return count # Driver codeN = 5guests = [1, 0, 2, 1, 3]totalGusets = findGuest(guests, N)print(totalGusets) # This code is contributed by Shrikant13 // C# program to get the// total number of guests at the partyusing System; class GFG{ // Function to find the totalGuests static int findGuest(int [] array, int N) { // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count; } // Driver code public static void Main () { // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int [] guests = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); Console.WriteLine(totalGuests); }} // This code is contributed by ihritik <?php// PHP program to get the// total number of guests at the party // Function to find the totalGuestsfunction findGuest($array, $N){ // Total guest before the party are 0 $count = 0; // Checking requirements for each guest for ($i = 0; $i < $N; $i++) { // If requirements are met if ($array[$i] <= $count) { // The Gi guest decides to stay // So increment total guest by 1 $count++; } } // Return the totalnumber of guest return $count;} // Driver code // Get the number of guests invited$N = 5; // Guests array stores// the requirement by each Guest$guests = array(1, 0, 2, 1, 3 ); // Get the total number of guests present$totalGuests = findGuest($guests, $N); echo $totalGuests; // This code is contributed by ihritik ?> <script> // javascript program to get the// total number of guests at the party // Function to find the totalGuests function findGuest(array , N) { // Total guest before the party are 0 var count = 0; // Checking requirements for each guest for (i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count; } // Driver code // Get the number of guests invited var N = 5; // Guests array stores // the requirement by each guest var guests = [ 1, 0, 2, 1, 3 ]; // Get the total number of guests present var totalGuests = findGuest(guests, N); document.write(totalGuests); // This code contributed by gauravrajput1 </script> 2 shrikanth13 Code_Mech ihritik GauravRajput1 Puzzles School Programming Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation Algorithm to solve Rubik's Cube Puzzle 7 | (3 Bulbs and 3 Switches) Top 20 Puzzles Commonly Asked During SDE Interviews Puzzle 4 | (Pay an employee using a gold rod of 7 units ?) Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26521, "s": 26493, "text": "\n01 Apr, 2021" }, { "code": null, "e": 27008, "s": 26521, "text": "A person hosts a party and invites N guests to it. However, each guest has a condition, that each guest ‘Gi’ only stays at the party if there are at least ‘Pi’ people already at the party, otherwise leaves. The total number of guests N and the number of people each guest needs ‘Pi’ are given as input for each guest. The task is to find the total guests that are present at the party. It is also given that the guests arrive at the party in the order given in the array ‘Pi’Examples: " }, { "code": null, "e": 28503, "s": 27008, "text": "Input: N = 5, Pi = {1, 0, 2, 1, 3}\nOutput: 2\nExplanation: \nSince 5 guests are invited to the party.\nTotal guest present initially = 0\n\nFor Guest number 1:\nThe 1st guest needs at least 1 person, \nsince he is the first to arrive, \nand there is no one else, so he leaves.\nTherefore, Total guest so far = 0\n\nFor Guest number 2:\nThe 2nd guest needs 0 people, so he stays. \nTherefore, Total guest so far = 0 + 1 = 1\n\nFor Guest number 3:\nThe 3rd guest needs at least 2 people,\nAnd there are still only 1 guest present,\nso he leaves.\nTherefore, Total guest so far = 1 + 0 = 1\n\nFor Guest number 4:\nThe 4th guest needs at least 1 people,\nAnd there is 1 guest present, so he stays. \nTherefore, Total guest so far = 1 + 1 = 2\n\nFor Guest number 5:\nThe 5th guest needs at least 3 people,\nAnd there is only 2 guest present, so he leaves. \nTherefore, Total guest so far = 2 + 0 = 2\n\nTotal guests that are present at the party = 2.\n\nInput: N = 3, Pi = {0, 2, 1}\nOutput: 2\nExplanation: \nSince 3 guests are invited to the party.\nTotal guest present initially = 0\n\nFor Guest number 1:\nThe 1st guest needs 0 people, so he stays.\nTherefore, Total guest so far = 1\n\nFor Guest number 2:\nThe 2nd guest needs at least 2 people,\nAnd there are still only 1 guest present,\nso he leaves.\nTherefore, Total guest so far = 1 + 0 = 1\n\nFor Guest number 3:\nThe 3rd guest needs at least 1 people,\nAnd there is 1 guest present, so he stays. \nTherefore, Total guest so far = 1 + 1 = 2\n\nTotal guests that are present at the party = 2." }, { "code": null, "e": 28517, "s": 28505, "text": "Approach: " }, { "code": null, "e": 28607, "s": 28517, "text": "Get the number of guests invited in N and the requirement of each guest in array guest[]." }, { "code": null, "e": 28675, "s": 28607, "text": "Initialize totalGuests to 0, as the total number of guests present." }, { "code": null, "e": 28719, "s": 28675, "text": "Iterate in the array guest[] from 0 to N-1." }, { "code": null, "e": 28816, "s": 28719, "text": "If the requirement of the guest is less than or equal to totalGuests, Increment totalGuests by 1" }, { "code": null, "e": 28911, "s": 28816, "text": "When complete array guest[] has been traversed, print the total number of guests ‘totalGuests’" }, { "code": null, "e": 28929, "s": 28911, "text": "Implementation: " }, { "code": null, "e": 28933, "s": 28929, "text": "C++" }, { "code": null, "e": 28938, "s": 28933, "text": "Java" }, { "code": null, "e": 28946, "s": 28938, "text": "Python3" }, { "code": null, "e": 28949, "s": 28946, "text": "C#" }, { "code": null, "e": 28953, "s": 28949, "text": "PHP" }, { "code": null, "e": 28964, "s": 28953, "text": "Javascript" }, { "code": "// C++ program to get the// total number of guests at the party #include <bits/stdc++.h>using namespace std; // Function to find the totalGuestsint findGuest(int array[], int N){ // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count;} // Driver codeint main(){ // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int guests[] = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); cout << totalGuests << endl; return 0;}", "e": 29842, "s": 28964, "text": null }, { "code": "// Java program to get the// total number of guests at the partyclass GFG{ // Function to find the totalGuestsstatic int findGuest(int array[], int N){ // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count;} // Driver codepublic static void main(String[] args){ // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int guests[] = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); System.out.println(totalGuests);}} // This code is contributed by Code_Mech", "e": 30767, "s": 29842, "text": null }, { "code": "# Python3 program to get the# total number of guests at the party # Function to find the totalGuestsdef findGuest(guests, N): count = 0 # Checking requirements for each guest for i in range(N): # If requirements are met if guests[i] <= count: # The Gi guest decides to stay # So increment total guest by 1 count += 1 # Return the totalnumber of gues return count # Driver codeN = 5guests = [1, 0, 2, 1, 3]totalGusets = findGuest(guests, N)print(totalGusets) # This code is contributed by Shrikant13", "e": 31344, "s": 30767, "text": null }, { "code": "// C# program to get the// total number of guests at the partyusing System; class GFG{ // Function to find the totalGuests static int findGuest(int [] array, int N) { // Total guest before the party are 0 int count = 0; // Checking requirements for each guest for (int i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count; } // Driver code public static void Main () { // Get the number of guests invited int N = 5; // Guests array stores // the requirement by each guest int [] guests = { 1, 0, 2, 1, 3 }; // Get the total number of guests present int totalGuests = findGuest(guests, N); Console.WriteLine(totalGuests); }} // This code is contributed by ihritik", "e": 32432, "s": 31344, "text": null }, { "code": "<?php// PHP program to get the// total number of guests at the party // Function to find the totalGuestsfunction findGuest($array, $N){ // Total guest before the party are 0 $count = 0; // Checking requirements for each guest for ($i = 0; $i < $N; $i++) { // If requirements are met if ($array[$i] <= $count) { // The Gi guest decides to stay // So increment total guest by 1 $count++; } } // Return the totalnumber of guest return $count;} // Driver code // Get the number of guests invited$N = 5; // Guests array stores// the requirement by each Guest$guests = array(1, 0, 2, 1, 3 ); // Get the total number of guests present$totalGuests = findGuest($guests, $N); echo $totalGuests; // This code is contributed by ihritik ?>", "e": 33254, "s": 32432, "text": null }, { "code": "<script> // javascript program to get the// total number of guests at the party // Function to find the totalGuests function findGuest(array , N) { // Total guest before the party are 0 var count = 0; // Checking requirements for each guest for (i = 0; i < N; i++) { // If requirements are met if (array[i] <= count) { // The Gi guest decides to stay // So increment total guest by 1 count++; } } // Return the totalnumber of guest return count; } // Driver code // Get the number of guests invited var N = 5; // Guests array stores // the requirement by each guest var guests = [ 1, 0, 2, 1, 3 ]; // Get the total number of guests present var totalGuests = findGuest(guests, N); document.write(totalGuests); // This code contributed by gauravrajput1 </script>", "e": 34224, "s": 33254, "text": null }, { "code": null, "e": 34226, "s": 34224, "text": "2" }, { "code": null, "e": 34240, "s": 34228, "text": "shrikanth13" }, { "code": null, "e": 34250, "s": 34240, "text": "Code_Mech" }, { "code": null, "e": 34258, "s": 34250, "text": "ihritik" }, { "code": null, "e": 34272, "s": 34258, "text": "GauravRajput1" }, { "code": null, "e": 34280, "s": 34272, "text": "Puzzles" }, { "code": null, "e": 34299, "s": 34280, "text": "School Programming" }, { "code": null, "e": 34307, "s": 34299, "text": "Puzzles" }, { "code": null, "e": 34405, "s": 34307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34454, "s": 34405, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 34486, "s": 34454, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 34522, "s": 34486, "text": "Puzzle 7 | (3 Bulbs and 3 Switches)" }, { "code": null, "e": 34574, "s": 34522, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 34633, "s": 34574, "text": "Puzzle 4 | (Pay an employee using a gold rod of 7 units ?)" }, { "code": null, "e": 34651, "s": 34633, "text": "Python Dictionary" }, { "code": null, "e": 34667, "s": 34651, "text": "Arrays in C/C++" }, { "code": null, "e": 34686, "s": 34667, "text": "Inheritance in C++" }, { "code": null, "e": 34711, "s": 34686, "text": "Reverse a string in Java" } ]
HTML | DOM Audio duration Property - GeeksforGeeks
14 Nov, 2019 The Audio duration property is used for returning the length of an audio. The Audio duration property returns the value in seconds.Different browsers return different precision values such as with safari returning up to 14 decimal places followed by opera returning up to 9 decimal places.The Audio duration property is a read-only property.The Audio duration function returns “NaN” if no video is set whereas if the audio is streamed and has no predefined length, it returns “Inf” (Infinity). Syntax: audioObject.duration Below program illustrates the Audio duration Property:Example: Getting the length of an audio. <!DOCTYPE html><html> <head> <title> Audio duration Property </title></head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2 style="font-family: Impact"> Audio duration Property </h2> <br> <audio id="Test_Audio" controls> <source src="sample1.ogg" type="audio/ogg"> <source src="sample1.mp3" type="audio/mpeg"> </audio> <p>To get the exact length of the audio, double click the "Return Audio Length" button. </p> <br> <button ondblclick="My_Audio()"> Return Audio Length </button> <p id="test"></p> <script> var a = document.getElementById("Test_Audio"); function My_Audio() { var a = document.getElementById( "Test_Audio").duration; document.getElementById("test").innerHTML = a; } </script> </body> </html> Output: Before clicking the button: After clicking the button: Supported Browsers: The browser supported by HTML | DOM Audio duration Property are listed below: Google Chrome Internet Explorer Firefox Opera Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31621, "s": 31593, "text": "\n14 Nov, 2019" }, { "code": null, "e": 32115, "s": 31621, "text": "The Audio duration property is used for returning the length of an audio. The Audio duration property returns the value in seconds.Different browsers return different precision values such as with safari returning up to 14 decimal places followed by opera returning up to 9 decimal places.The Audio duration property is a read-only property.The Audio duration function returns “NaN” if no video is set whereas if the audio is streamed and has no predefined length, it returns “Inf” (Infinity)." }, { "code": null, "e": 32123, "s": 32115, "text": "Syntax:" }, { "code": null, "e": 32144, "s": 32123, "text": "audioObject.duration" }, { "code": null, "e": 32239, "s": 32144, "text": "Below program illustrates the Audio duration Property:Example: Getting the length of an audio." }, { "code": "<!DOCTYPE html><html> <head> <title> Audio duration Property </title></head> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact\"> Audio duration Property </h2> <br> <audio id=\"Test_Audio\" controls> <source src=\"sample1.ogg\" type=\"audio/ogg\"> <source src=\"sample1.mp3\" type=\"audio/mpeg\"> </audio> <p>To get the exact length of the audio, double click the \"Return Audio Length\" button. </p> <br> <button ondblclick=\"My_Audio()\"> Return Audio Length </button> <p id=\"test\"></p> <script> var a = document.getElementById(\"Test_Audio\"); function My_Audio() { var a = document.getElementById( \"Test_Audio\").duration; document.getElementById(\"test\").innerHTML = a; } </script> </body> </html>", "e": 33180, "s": 32239, "text": null }, { "code": null, "e": 33188, "s": 33180, "text": "Output:" }, { "code": null, "e": 33216, "s": 33188, "text": "Before clicking the button:" }, { "code": null, "e": 33243, "s": 33216, "text": "After clicking the button:" }, { "code": null, "e": 33341, "s": 33243, "text": "Supported Browsers: The browser supported by HTML | DOM Audio duration Property are listed below:" }, { "code": null, "e": 33355, "s": 33341, "text": "Google Chrome" }, { "code": null, "e": 33373, "s": 33355, "text": "Internet Explorer" }, { "code": null, "e": 33381, "s": 33373, "text": "Firefox" }, { "code": null, "e": 33387, "s": 33381, "text": "Opera" }, { "code": null, "e": 33400, "s": 33387, "text": "Apple Safari" }, { "code": null, "e": 33537, "s": 33400, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33551, "s": 33537, "text": "ManasChhabra2" }, { "code": null, "e": 33560, "s": 33551, "text": "HTML-DOM" }, { "code": null, "e": 33565, "s": 33560, "text": "HTML" }, { "code": null, "e": 33582, "s": 33565, "text": "Web Technologies" }, { "code": null, "e": 33587, "s": 33582, "text": "HTML" }, { "code": null, "e": 33685, "s": 33587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33735, "s": 33685, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33797, "s": 33735, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33845, "s": 33797, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33905, "s": 33845, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33958, "s": 33905, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33998, "s": 33958, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34031, "s": 33998, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34076, "s": 34031, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34119, "s": 34076, "text": "How to fetch data from an API in ReactJS ?" } ]
Matplotlib.pyplot.acorr() in Python - GeeksforGeeks
12 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The acorr() function in pyplot module of matplotlib library is used to plot the autocorrelation of x (array-like). Syntax: matplotlib.pyplot.acorr(x, *, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is a sequence of scalar. detrend: This parameter is an optional parameter. Its default value is mlab.detrend_none normed: This parameter is also an optional parameter and contains the bool value. Its default value is True usevlines: This parameter is also an optional parameter and contains the bool value. Its default value is True maxlags: This parameter is also an optional parameter and contains the integer value. Its default value is 10 linestyle: This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False. marker: This parameter is also an optional parameter and contains the string. Its default value is ‘o’ Returns: This method returns the following: lags:This method returns the lag vector c:This method returns the auto correlation vector. line : Added LineCollection if usevlines is True, otherwise add Line2D. b: This method returns the horizontal line at 0 if usevlines is True, otherwise None. The resultant is (lags, c, line, b). Below examples illustrate the matplotlib.pyplot.acorr() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib.pyplot.acorr()# function import matplotlib.pyplot as pltimport numpy as np # Time series datageeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) # Plot autocorrelationplt.acorr(geeks, maxlags = 9) # Add labels to autocorrelation plotplt.title("Autocorrelation of Geeksforgeeks' Users data")plt.xlabel('X-axis')plt.ylabel('Y-axis') # Display the autocorrelation plotplt.show() Output: Example #2: # Implementation of matplotlib.pyplot.acorr() # function import matplotlib.pyplot as pltimport numpy as np # Fixing random state for reproducibilitynp.random.seed(10**7) geeks = np.random.randn(51 ) plt.title("Autocorrelation Example")plt.acorr(geeks, usevlines = True, normed = True, maxlags = 50, lw = 2) plt.grid(True)plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python
[ { "code": null, "e": 26027, "s": 25999, "text": "\n12 Apr, 2020" }, { "code": null, "e": 26222, "s": 26027, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 26337, "s": 26222, "text": "The acorr() function in pyplot module of matplotlib library is used to plot the autocorrelation of x (array-like)." }, { "code": null, "e": 26396, "s": 26337, "text": "Syntax: matplotlib.pyplot.acorr(x, *, data=None, **kwargs)" }, { "code": null, "e": 26478, "s": 26396, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26521, "s": 26478, "text": "x: This parameter is a sequence of scalar." }, { "code": null, "e": 26610, "s": 26521, "text": "detrend: This parameter is an optional parameter. Its default value is mlab.detrend_none" }, { "code": null, "e": 26718, "s": 26610, "text": "normed: This parameter is also an optional parameter and contains the bool value. Its default value is True" }, { "code": null, "e": 26829, "s": 26718, "text": "usevlines: This parameter is also an optional parameter and contains the bool value. Its default value is True" }, { "code": null, "e": 26939, "s": 26829, "text": "maxlags: This parameter is also an optional parameter and contains the integer value. Its default value is 10" }, { "code": null, "e": 27064, "s": 26939, "text": "linestyle: This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False." }, { "code": null, "e": 27167, "s": 27064, "text": "marker: This parameter is also an optional parameter and contains the string. Its default value is ‘o’" }, { "code": null, "e": 27211, "s": 27167, "text": "Returns: This method returns the following:" }, { "code": null, "e": 27251, "s": 27211, "text": "lags:This method returns the lag vector" }, { "code": null, "e": 27302, "s": 27251, "text": "c:This method returns the auto correlation vector." }, { "code": null, "e": 27374, "s": 27302, "text": "line : Added LineCollection if usevlines is True, otherwise add Line2D." }, { "code": null, "e": 27460, "s": 27374, "text": "b: This method returns the horizontal line at 0 if usevlines is True, otherwise None." }, { "code": null, "e": 27497, "s": 27460, "text": "The resultant is (lags, c, line, b)." }, { "code": null, "e": 27584, "s": 27497, "text": "Below examples illustrate the matplotlib.pyplot.acorr() function in matplotlib.pyplot:" }, { "code": null, "e": 27596, "s": 27584, "text": "Example #1:" }, { "code": "# Implementation of matplotlib.pyplot.acorr()# function import matplotlib.pyplot as pltimport numpy as np # Time series datageeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) # Plot autocorrelationplt.acorr(geeks, maxlags = 9) # Add labels to autocorrelation plotplt.title(\"Autocorrelation of Geeksforgeeks' Users data\")plt.xlabel('X-axis')plt.ylabel('Y-axis') # Display the autocorrelation plotplt.show()", "e": 28080, "s": 27596, "text": null }, { "code": null, "e": 28088, "s": 28080, "text": "Output:" }, { "code": null, "e": 28100, "s": 28088, "text": "Example #2:" }, { "code": "# Implementation of matplotlib.pyplot.acorr() # function import matplotlib.pyplot as pltimport numpy as np # Fixing random state for reproducibilitynp.random.seed(10**7) geeks = np.random.randn(51 ) plt.title(\"Autocorrelation Example\")plt.acorr(geeks, usevlines = True, normed = True, maxlags = 50, lw = 2) plt.grid(True)plt.show()", "e": 28459, "s": 28100, "text": null }, { "code": null, "e": 28467, "s": 28459, "text": "Output:" }, { "code": null, "e": 28485, "s": 28467, "text": "Python-matplotlib" }, { "code": null, "e": 28492, "s": 28485, "text": "Python" }, { "code": null, "e": 28590, "s": 28492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28608, "s": 28590, "text": "Python Dictionary" }, { "code": null, "e": 28643, "s": 28608, "text": "Read a file line by line in Python" }, { "code": null, "e": 28675, "s": 28643, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28697, "s": 28675, "text": "Enumerate() in Python" }, { "code": null, "e": 28739, "s": 28697, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28769, "s": 28739, "text": "Iterate over a list in Python" }, { "code": null, "e": 28795, "s": 28769, "text": "Python String | replace()" }, { "code": null, "e": 28824, "s": 28795, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28868, "s": 28824, "text": "Reading and Writing to text files in Python" } ]
Find top k (or most frequent) numbers in a stream - GeeksforGeeks
14 Mar, 2022 Given an array of n numbers. Your task is to read numbers from the array and keep at-most K numbers at the top (According to their decreasing frequency) every time a new number is read. We basically need to print top k numbers sorted by frequency when input stream has included k distinct elements, else need to print all distinct elements sorted by frequency.Examples: Input : arr[] = {5, 2, 1, 3, 2} k = 4 Output : 5 2 5 1 2 5 1 2 3 5 2 1 3 5 Explanation: After reading 5, there is only one element 5 whose frequency is max till now. so print 5.After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5.After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5.Similarly after reading 3, print 1 2 3 5After reading last element 2 since 2 has already occurred so we have now a frequency of 2 as 2. So we keep 2 at the top and then rest of the element with the same frequency in sorted order. So print, 2 1 3 5. After reading 5, there is only one element 5 whose frequency is max till now. so print 5. After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5. After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5. Similarly after reading 3, print 1 2 3 5 After reading last element 2 since 2 has already occurred so we have now a frequency of 2 as 2. So we keep 2 at the top and then rest of the element with the same frequency in sorted order. So print, 2 1 3 5. Input : arr[] = {5, 2, 1, 3, 4} k = 4 Output : 5 2 5 1 2 5 1 2 3 5 1 2 3 4 Explanation: After reading 5, there is only one element 5 whose frequency is max till now. so print 5.After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5.After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5. Similarly after reading 3, print 1 2 3 5After reading last element 4, All the elements have same frequency So print, 1 2 3 4. After reading 5, there is only one element 5 whose frequency is max till now. so print 5. After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5. After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5. Similarly after reading 3, print 1 2 3 5 After reading last element 4, All the elements have same frequency So print, 1 2 3 4. Approach: The idea is to store the top k elements with maximum frequency. To store them a vector or an array can be used. To keep the track of frequencies of elements creates a HashMap to store element-frequency pairs. Given a stream of numbers, when a new element appears in the stream update the frequency of that element in HashMap and put that element at the end of the list of K numbers (total k+1 elements) now compare adjacent elements of the list and swap if higher frequency element is stored next to it.Algorithm: Create a Hashmap hm, and an array of k + 1 length.Traverse the input array from start to end.Insert the element at k+1 th position of the array, update the frequency of that element in HashMap.Now, traverse the temp array from start to end – 1For very element, compare the frequency and swap if higher frequency element is stored next to it, if the frequency is same then swap is the next element is greater.print the top k element in each traversal of original array. Create a Hashmap hm, and an array of k + 1 length. Traverse the input array from start to end. Insert the element at k+1 th position of the array, update the frequency of that element in HashMap. Now, traverse the temp array from start to end – 1 For very element, compare the frequency and swap if higher frequency element is stored next to it, if the frequency is same then swap is the next element is greater. print the top k element in each traversal of original array. Implementation: C++ Java Python3 C# Javascript // C++ program to find top k elements in a stream#include <bits/stdc++.h>using namespace std; // Function to print top k numbersvoid kTop(int a[], int n, int k){ // vector of size k+1 to store elements vector<int> top(k + 1); // array to keep track of frequency unordered_map<int, int> freq; // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency freq[a[m]]++; // store that element in top vector top[k] = a[m]; // search in top vector for same element auto it = find(top.begin(), top.end() - 1, a[m]); // iterate from the position of element to zero for (int i = distance(top.begin(), it) - 1; i >= 0; --i) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) swap(top[i], top[i + 1]); // if frequency is same compare the elements // and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) && (top[i] > top[i + 1])) swap(top[i], top[i + 1]); else break; } // print top k elements for (int i = 0; i < k && top[i] != 0; ++i) cout << top[i] << ' '; } cout << endl;} // Driver program to test above functionint main(){ int k = 4; int arr[] = { 5, 2, 1, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); kTop(arr, n, k); return 0;} import java.io.*;import java.util.*;class GFG { // function to search in top vector for element static int find(int[] arr, int ele) { for (int i = 0; i < arr.length; i++) if (arr[i] == ele) return i; return -1; } // Function to print top k numbers static void kTop(int[] a, int n, int k) { // vector of size k+1 to store elements int[] top = new int[k + 1]; // array to keep track of frequency HashMap<Integer, Integer> freq = new HashMap<>(); for (int i = 0; i < k + 1; i++) freq.put(i, 0); // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency if (freq.containsKey(a[m])) freq.put(a[m], freq.get(a[m]) + 1); else freq.put(a[m], 1); // store that element in top vector top[k] = a[m]; // search in top vector for same element int i = find(top, a[m]); i -= 1; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq.get(top[i]) < freq.get(top[i + 1])) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if ((freq.get(top[i]) == freq.get(top[i + 1])) && (top[i] > top[i + 1])) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i -= 1; } // print top k elements for (int j = 0; j < k && top[j] != 0; ++j) System.out.print(top[j] + " "); } System.out.println(); } // Driver program to test above function public static void main(String args[]) { int k = 4; int[] arr = { 5, 2, 1, 3, 2 }; int n = arr.length; kTop(arr, n, k); }} // This code is contributed by rachana soma # Python program to find top k elements in a stream # Function to print top k numbersdef kTop(a, n, k): # list of size k + 1 to store elements top = [0 for i in range(k + 1)] # dictionary to keep track of frequency freq = {i:0 for i in range(k + 1)} # iterate till the end of stream for m in range(n): # increase the frequency if a[m] in freq.keys(): freq[a[m]] += 1 else: freq[a[m]] = 1 # store that element in top vector top[k] = a[m] i = top.index(a[m]) i -= 1 while i >= 0: # compare the frequency and swap if higher # frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]): t = top[i] top[i] = top[i + 1] top[i + 1] = t # if frequency is same compare the elements # and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])): t = top[i] top[i] = top[i + 1] top[i + 1] = t else: break i -= 1 # print top k elements i = 0 while i < k and top[i] != 0: print(top[i],end=" ") i += 1 print() # Driver program to test above functionk = 4arr = [ 5, 2, 1, 3, 2 ]n = len(arr)kTop(arr, n, k) # This code is contributed by Sachin Bisht // C# program to find top k elements in a streamusing System;using System.Collections.Generic; class GFG { // function to search in top vector for element static int find(int[] arr, int ele) { for (int i = 0; i < arr.Length; i++) if (arr[i] == ele) return i; return -1; } // Function to print top k numbers static void kTop(int[] a, int n, int k) { // vector of size k+1 to store elements int[] top = new int[k + 1]; // array to keep track of frequency Dictionary<int, int> freq = new Dictionary<int, int>(); for (int i = 0; i < k + 1; i++) freq.Add(i, 0); // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency if (freq.ContainsKey(a[m])) freq[a[m]]++; else freq.Add(a[m], 1); // store that element in top vector top[k] = a[m]; // search in top vector for same element int i = find(top, a[m]); i--; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if (freq[top[i]] == freq[top[i + 1]] && top[i] > top[i + 1]) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i--; } // print top k elements for (int j = 0; j < k && top[j] != 0; ++j) Console.Write(top[j] + " "); } Console.WriteLine(); } // Driver Code public static void Main(String[] args) { int k = 4; int[] arr = { 5, 2, 1, 3, 2 }; int n = arr.Length; kTop(arr, n, k); }} // This code is contributed by// sanjeev2552 <script> // JavaScript program to find top k elements in a stream // function to search in top vector for element function find(arr, ele) { for (var i = 0; i < arr.length; i++) if (arr[i] === ele) return i; return -1; } // Function to print top k numbers function kTop(a, n, k) { // vector of size k+1 to store elements var top = new Array(k + 1).fill(0); // array to keep track of frequency var freq = {}; for (var i = 0; i < k + 1; i++) freq[i] = 0; // iterate till the end of stream for (var m = 0; m < n; m++) { // increase the frequency if (freq.hasOwnProperty(a[m])) freq[a[m]]++; else freq[a[m]] = 1; // store that element in top vector top[k] = a[m]; // search in top vector for same element var i = find(top, a[m]); i--; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) { var temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if (freq[top[i]] === freq[top[i + 1]] && top[i] > top[i + 1]) { var temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i--; } // print top k elements for (var j = 0; j < k && top[j] !== 0; ++j) document.write(top[j] + " "); } document.write("<br>"); } // Driver Code var k = 4; var arr = [5, 2, 1, 3, 2]; var n = arr.length; kTop(arr, n, k); </script> 5 2 5 1 2 5 1 2 3 5 2 1 3 5 Complexity Analysis: Time Complexity: O( n * k ). In each traversal the temp array of size k is traversed, So the time Complexity is O( n * k ). Space Complexity:O(n). To store the elements in HashMap O(n) space is required. This 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rachana soma sanjeev2552 andrew1234 rdtank amartyaghoshgfg simmytarika5 Accolite Amazon array-stream cpp-unordered_map Order-Statistics Arrays Hash Accolite Amazon Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews 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) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26809, "s": 26781, "text": "\n14 Mar, 2022" }, { "code": null, "e": 27181, "s": 26809, "text": "Given an array of n numbers. Your task is to read numbers from the array and keep at-most K numbers at the top (According to their decreasing frequency) every time a new number is read. We basically need to print top k numbers sorted by frequency when input stream has included k distinct elements, else need to print all distinct elements sorted by frequency.Examples: " }, { "code": null, "e": 27271, "s": 27181, "text": "Input : arr[] = {5, 2, 1, 3, 2} k = 4 Output : 5 2 5 1 2 5 1 2 3 5 2 1 3 5 Explanation: " }, { "code": null, "e": 27854, "s": 27271, "text": "After reading 5, there is only one element 5 whose frequency is max till now. so print 5.After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5.After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5.Similarly after reading 3, print 1 2 3 5After reading last element 2 since 2 has already occurred so we have now a frequency of 2 as 2. So we keep 2 at the top and then rest of the element with the same frequency in sorted order. So print, 2 1 3 5." }, { "code": null, "e": 27944, "s": 27854, "text": "After reading 5, there is only one element 5 whose frequency is max till now. so print 5." }, { "code": null, "e": 28098, "s": 27944, "text": "After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5." }, { "code": null, "e": 28191, "s": 28098, "text": "After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5." }, { "code": null, "e": 28232, "s": 28191, "text": "Similarly after reading 3, print 1 2 3 5" }, { "code": null, "e": 28441, "s": 28232, "text": "After reading last element 2 since 2 has already occurred so we have now a frequency of 2 as 2. So we keep 2 at the top and then rest of the element with the same frequency in sorted order. So print, 2 1 3 5." }, { "code": null, "e": 28529, "s": 28441, "text": "Input : arr[] = {5, 2, 1, 3, 4} k = 4 Output : 5 2 5 1 2 5 1 2 3 5 1 2 3 4 Explanation:" }, { "code": null, "e": 28990, "s": 28529, "text": "After reading 5, there is only one element 5 whose frequency is max till now. so print 5.After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5.After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5. Similarly after reading 3, print 1 2 3 5After reading last element 4, All the elements have same frequency So print, 1 2 3 4." }, { "code": null, "e": 29080, "s": 28990, "text": "After reading 5, there is only one element 5 whose frequency is max till now. so print 5." }, { "code": null, "e": 29234, "s": 29080, "text": "After reading 2, we will have two elements 2 and 5 with the same frequency. As 2, is smaller than 5 but their frequency is the same so we will print 2 5." }, { "code": null, "e": 29368, "s": 29234, "text": "After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency, so print 1 2 5. Similarly after reading 3, print 1 2 3 5" }, { "code": null, "e": 29454, "s": 29368, "text": "After reading last element 4, All the elements have same frequency So print, 1 2 3 4." }, { "code": null, "e": 29984, "s": 29458, "text": "Approach: The idea is to store the top k elements with maximum frequency. To store them a vector or an array can be used. To keep the track of frequencies of elements creates a HashMap to store element-frequency pairs. Given a stream of numbers, when a new element appears in the stream update the frequency of that element in HashMap and put that element at the end of the list of K numbers (total k+1 elements) now compare adjacent elements of the list and swap if higher frequency element is stored next to it.Algorithm: " }, { "code": null, "e": 30453, "s": 29984, "text": "Create a Hashmap hm, and an array of k + 1 length.Traverse the input array from start to end.Insert the element at k+1 th position of the array, update the frequency of that element in HashMap.Now, traverse the temp array from start to end – 1For very element, compare the frequency and swap if higher frequency element is stored next to it, if the frequency is same then swap is the next element is greater.print the top k element in each traversal of original array." }, { "code": null, "e": 30504, "s": 30453, "text": "Create a Hashmap hm, and an array of k + 1 length." }, { "code": null, "e": 30548, "s": 30504, "text": "Traverse the input array from start to end." }, { "code": null, "e": 30649, "s": 30548, "text": "Insert the element at k+1 th position of the array, update the frequency of that element in HashMap." }, { "code": null, "e": 30700, "s": 30649, "text": "Now, traverse the temp array from start to end – 1" }, { "code": null, "e": 30866, "s": 30700, "text": "For very element, compare the frequency and swap if higher frequency element is stored next to it, if the frequency is same then swap is the next element is greater." }, { "code": null, "e": 30927, "s": 30866, "text": "print the top k element in each traversal of original array." }, { "code": null, "e": 30945, "s": 30927, "text": "Implementation: " }, { "code": null, "e": 30949, "s": 30945, "text": "C++" }, { "code": null, "e": 30954, "s": 30949, "text": "Java" }, { "code": null, "e": 30962, "s": 30954, "text": "Python3" }, { "code": null, "e": 30965, "s": 30962, "text": "C#" }, { "code": null, "e": 30976, "s": 30965, "text": "Javascript" }, { "code": "// C++ program to find top k elements in a stream#include <bits/stdc++.h>using namespace std; // Function to print top k numbersvoid kTop(int a[], int n, int k){ // vector of size k+1 to store elements vector<int> top(k + 1); // array to keep track of frequency unordered_map<int, int> freq; // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency freq[a[m]]++; // store that element in top vector top[k] = a[m]; // search in top vector for same element auto it = find(top.begin(), top.end() - 1, a[m]); // iterate from the position of element to zero for (int i = distance(top.begin(), it) - 1; i >= 0; --i) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) swap(top[i], top[i + 1]); // if frequency is same compare the elements // and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) && (top[i] > top[i + 1])) swap(top[i], top[i + 1]); else break; } // print top k elements for (int i = 0; i < k && top[i] != 0; ++i) cout << top[i] << ' '; } cout << endl;} // Driver program to test above functionint main(){ int k = 4; int arr[] = { 5, 2, 1, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); kTop(arr, n, k); return 0;}", "e": 32504, "s": 30976, "text": null }, { "code": "import java.io.*;import java.util.*;class GFG { // function to search in top vector for element static int find(int[] arr, int ele) { for (int i = 0; i < arr.length; i++) if (arr[i] == ele) return i; return -1; } // Function to print top k numbers static void kTop(int[] a, int n, int k) { // vector of size k+1 to store elements int[] top = new int[k + 1]; // array to keep track of frequency HashMap<Integer, Integer> freq = new HashMap<>(); for (int i = 0; i < k + 1; i++) freq.put(i, 0); // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency if (freq.containsKey(a[m])) freq.put(a[m], freq.get(a[m]) + 1); else freq.put(a[m], 1); // store that element in top vector top[k] = a[m]; // search in top vector for same element int i = find(top, a[m]); i -= 1; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq.get(top[i]) < freq.get(top[i + 1])) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if ((freq.get(top[i]) == freq.get(top[i + 1])) && (top[i] > top[i + 1])) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i -= 1; } // print top k elements for (int j = 0; j < k && top[j] != 0; ++j) System.out.print(top[j] + \" \"); } System.out.println(); } // Driver program to test above function public static void main(String args[]) { int k = 4; int[] arr = { 5, 2, 1, 3, 2 }; int n = arr.length; kTop(arr, n, k); }} // This code is contributed by rachana soma", "e": 34795, "s": 32504, "text": null }, { "code": "# Python program to find top k elements in a stream # Function to print top k numbersdef kTop(a, n, k): # list of size k + 1 to store elements top = [0 for i in range(k + 1)] # dictionary to keep track of frequency freq = {i:0 for i in range(k + 1)} # iterate till the end of stream for m in range(n): # increase the frequency if a[m] in freq.keys(): freq[a[m]] += 1 else: freq[a[m]] = 1 # store that element in top vector top[k] = a[m] i = top.index(a[m]) i -= 1 while i >= 0: # compare the frequency and swap if higher # frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]): t = top[i] top[i] = top[i + 1] top[i + 1] = t # if frequency is same compare the elements # and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])): t = top[i] top[i] = top[i + 1] top[i + 1] = t else: break i -= 1 # print top k elements i = 0 while i < k and top[i] != 0: print(top[i],end=\" \") i += 1 print() # Driver program to test above functionk = 4arr = [ 5, 2, 1, 3, 2 ]n = len(arr)kTop(arr, n, k) # This code is contributed by Sachin Bisht", "e": 36266, "s": 34795, "text": null }, { "code": "// C# program to find top k elements in a streamusing System;using System.Collections.Generic; class GFG { // function to search in top vector for element static int find(int[] arr, int ele) { for (int i = 0; i < arr.Length; i++) if (arr[i] == ele) return i; return -1; } // Function to print top k numbers static void kTop(int[] a, int n, int k) { // vector of size k+1 to store elements int[] top = new int[k + 1]; // array to keep track of frequency Dictionary<int, int> freq = new Dictionary<int, int>(); for (int i = 0; i < k + 1; i++) freq.Add(i, 0); // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency if (freq.ContainsKey(a[m])) freq[a[m]]++; else freq.Add(a[m], 1); // store that element in top vector top[k] = a[m]; // search in top vector for same element int i = find(top, a[m]); i--; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if (freq[top[i]] == freq[top[i + 1]] && top[i] > top[i + 1]) { int temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i--; } // print top k elements for (int j = 0; j < k && top[j] != 0; ++j) Console.Write(top[j] + \" \"); } Console.WriteLine(); } // Driver Code public static void Main(String[] args) { int k = 4; int[] arr = { 5, 2, 1, 3, 2 }; int n = arr.Length; kTop(arr, n, k); }} // This code is contributed by// sanjeev2552", "e": 38606, "s": 36266, "text": null }, { "code": "<script> // JavaScript program to find top k elements in a stream // function to search in top vector for element function find(arr, ele) { for (var i = 0; i < arr.length; i++) if (arr[i] === ele) return i; return -1; } // Function to print top k numbers function kTop(a, n, k) { // vector of size k+1 to store elements var top = new Array(k + 1).fill(0); // array to keep track of frequency var freq = {}; for (var i = 0; i < k + 1; i++) freq[i] = 0; // iterate till the end of stream for (var m = 0; m < n; m++) { // increase the frequency if (freq.hasOwnProperty(a[m])) freq[a[m]]++; else freq[a[m]] = 1; // store that element in top vector top[k] = a[m]; // search in top vector for same element var i = find(top, a[m]); i--; // iterate from the position of element to zero while (i >= 0) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) { var temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } // if frequency is same compare the elements // and swap if next element is high else if (freq[top[i]] === freq[top[i + 1]] && top[i] > top[i + 1]) { var temp = top[i]; top[i] = top[i + 1]; top[i + 1] = temp; } else break; i--; } // print top k elements for (var j = 0; j < k && top[j] !== 0; ++j) document.write(top[j] + \" \"); } document.write(\"<br>\"); } // Driver Code var k = 4; var arr = [5, 2, 1, 3, 2]; var n = arr.length; kTop(arr, n, k); </script>", "e": 40532, "s": 38606, "text": null }, { "code": null, "e": 40560, "s": 40532, "text": "5 2 5 1 2 5 1 2 3 5 2 1 3 5" }, { "code": null, "e": 40585, "s": 40562, "text": "Complexity Analysis: " }, { "code": null, "e": 40709, "s": 40585, "text": "Time Complexity: O( n * k ). In each traversal the temp array of size k is traversed, So the time Complexity is O( n * k )." }, { "code": null, "e": 40789, "s": 40709, "text": "Space Complexity:O(n). To store the elements in HashMap O(n) space is required." }, { "code": null, "e": 41210, "s": 40789, "text": "This 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41223, "s": 41210, "text": "rachana soma" }, { "code": null, "e": 41235, "s": 41223, "text": "sanjeev2552" }, { "code": null, "e": 41246, "s": 41235, "text": "andrew1234" }, { "code": null, "e": 41253, "s": 41246, "text": "rdtank" }, { "code": null, "e": 41269, "s": 41253, "text": "amartyaghoshgfg" }, { "code": null, "e": 41282, "s": 41269, "text": "simmytarika5" }, { "code": null, "e": 41291, "s": 41282, "text": "Accolite" }, { "code": null, "e": 41298, "s": 41291, "text": "Amazon" }, { "code": null, "e": 41311, "s": 41298, "text": "array-stream" }, { "code": null, "e": 41329, "s": 41311, "text": "cpp-unordered_map" }, { "code": null, "e": 41346, "s": 41329, "text": "Order-Statistics" }, { "code": null, "e": 41353, "s": 41346, "text": "Arrays" }, { "code": null, "e": 41358, "s": 41353, "text": "Hash" }, { "code": null, "e": 41367, "s": 41358, "text": "Accolite" }, { "code": null, "e": 41374, "s": 41367, "text": "Amazon" }, { "code": null, "e": 41381, "s": 41374, "text": "Arrays" }, { "code": null, "e": 41386, "s": 41381, "text": "Hash" }, { "code": null, "e": 41484, "s": 41386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41528, "s": 41484, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 41551, "s": 41528, "text": "Introduction to Arrays" }, { "code": null, "e": 41583, "s": 41551, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41597, "s": 41583, "text": "Linear Search" }, { "code": null, "e": 41618, "s": 41597, "text": "Linked List vs Array" }, { "code": null, "e": 41703, "s": 41618, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 41739, "s": 41703, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 41766, "s": 41739, "text": "Count pairs with given sum" }, { "code": null, "e": 41797, "s": 41766, "text": "Hashing | Set 1 (Introduction)" } ]
GATE | GATE CS 2019 | Question 17 - GeeksforGeeks
14 Feb, 2019 Let G be an arbitrary group. Consider the following relations on G: R1: ∀a, b ∈ G, aR1b if and only if ∃g ∈ G such that a = g−1bg R2: ∀a, b ∈ G, aR2b if and only if a = b−1 Which of the above is/are equivalence relation/relations?(A) R1 and R2(B) R1 only(C) R2 only(D) Neither R1 nor R2Answer: (B)Explanation: Given R1 is a equivalence relation, because it satisfied reflexive, symmetric, and transitive conditions: Reflexive: a = g–1ag can be satisfied by putting g = e, identity “e” always exists in a group. Symmetric:aRb ⇒ a = g–1bg for some g ⇒ b = gag–1 = (g–1)–1ag–1 g–1 always exists for every g ∈ G. aRb ⇒ a = g–1bg for some g ⇒ b = gag–1 = (g–1)–1ag–1 g–1 always exists for every g ∈ G. Transitive:aRb and bRc ⇒ a = g1–1bg1 and b = g2–1 cg2 for some g1g2 ∈ G. Now a = g1–1 g2–1 cg2g1 = (g2g1)–1 cg2g1 g1 ∈ G and g2 ∈ G ⇒ g2g1 ∈ G since group is closed so aRb and aRb ⇒ aRc aRb and bRc ⇒ a = g1–1bg1 and b = g2–1 cg2 for some g1g2 ∈ G. Now a = g1–1 g2–1 cg2g1 = (g2g1)–1 cg2g1 g1 ∈ G and g2 ∈ G ⇒ g2g1 ∈ G since group is closed so aRb and aRb ⇒ aRc aR2a ⇒ a = a–1 ∀a which not be true in a group. So, option (B) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25607, "s": 25579, "text": "\n14 Feb, 2019" }, { "code": null, "e": 25675, "s": 25607, "text": "Let G be an arbitrary group. Consider the following relations on G:" }, { "code": null, "e": 25737, "s": 25675, "text": "R1: ∀a, b ∈ G, aR1b if and only if ∃g ∈ G such that a = g−1bg" }, { "code": null, "e": 25780, "s": 25737, "text": "R2: ∀a, b ∈ G, aR2b if and only if a = b−1" }, { "code": null, "e": 26023, "s": 25780, "text": "Which of the above is/are equivalence relation/relations?(A) R1 and R2(B) R1 only(C) R2 only(D) Neither R1 nor R2Answer: (B)Explanation: Given R1 is a equivalence relation, because it satisfied reflexive, symmetric, and transitive conditions:" }, { "code": null, "e": 26118, "s": 26023, "text": "Reflexive: a = g–1ag can be satisfied by putting g = e, identity “e” always exists in a group." }, { "code": null, "e": 26217, "s": 26118, "text": "Symmetric:aRb ⇒ a = g–1bg for some g\n⇒ b = gag–1 = (g–1)–1ag–1\ng–1 always exists for every g ∈ G. " }, { "code": null, "e": 26306, "s": 26217, "text": "aRb ⇒ a = g–1bg for some g\n⇒ b = gag–1 = (g–1)–1ag–1\ng–1 always exists for every g ∈ G. " }, { "code": null, "e": 26497, "s": 26306, "text": "Transitive:aRb and bRc ⇒ a = g1–1bg1 \nand b = g2–1 cg2 for some g1g2 ∈ G.\nNow a = g1–1 g2–1 cg2g1 = (g2g1)–1 cg2g1\ng1 ∈ G and g2 ∈ G ⇒ g2g1 ∈ G \nsince group is closed so aRb and aRb ⇒ aRc\n\n\n" }, { "code": null, "e": 26677, "s": 26497, "text": "aRb and bRc ⇒ a = g1–1bg1 \nand b = g2–1 cg2 for some g1g2 ∈ G.\nNow a = g1–1 g2–1 cg2g1 = (g2g1)–1 cg2g1\ng1 ∈ G and g2 ∈ G ⇒ g2g1 ∈ G \nsince group is closed so aRb and aRb ⇒ aRc\n\n\n" }, { "code": null, "e": 26726, "s": 26677, "text": "aR2a ⇒ a = a–1 ∀a which not be true in a group. " }, { "code": null, "e": 26774, "s": 26726, "text": "So, option (B) is correct.Quiz of this Question" }, { "code": null, "e": 26779, "s": 26774, "text": "GATE" }, { "code": null, "e": 26877, "s": 26779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26911, "s": 26877, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26945, "s": 26911, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26979, "s": 26945, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27012, "s": 26979, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27048, "s": 27012, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27082, "s": 27048, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27118, "s": 27082, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27152, "s": 27118, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27186, "s": 27152, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Shell Script to Validate Integer Input - GeeksforGeeks
09 Apr, 2021 Here we are going to see a shell script which validates an integer. We are going to display whether the input entered is an integer or an invalid input. Approach: Take input from the user.Store the input of any variableNow we are going to trim the input in such a way that all the -(minus) or +(plus) signs before the input are trimmed down.Now we are going to apply a regular expression to check if the input pattern has multiple occurrences of digits 0-9.If the input pattern contains only digits, this means that the input entered is a valid integer and in all other cases, invalid integer input is shown. Take input from the user. Store the input of any variable Now we are going to trim the input in such a way that all the -(minus) or +(plus) signs before the input are trimmed down. Now we are going to apply a regular expression to check if the input pattern has multiple occurrences of digits 0-9. If the input pattern contains only digits, this means that the input entered is a valid integer and in all other cases, invalid integer input is shown. The Shell Script is given below: # Asking the user to enter an input echo "Enter an input" # reading and storing input read variable # Applying the approach given above case ${variable#[-+]} in *[!0-9]* | '') echo "Not an integer" ;; * ) echo "Valid integer number" ;; esac Output: Output of the above code snippet Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n09 Apr, 2021" }, { "code": null, "e": 25831, "s": 25677, "text": "Here we are going to see a shell script which validates an integer. We are going to display whether the input entered is an integer or an invalid input. " }, { "code": null, "e": 25842, "s": 25831, "text": "Approach: " }, { "code": null, "e": 26288, "s": 25842, "text": "Take input from the user.Store the input of any variableNow we are going to trim the input in such a way that all the -(minus) or +(plus) signs before the input are trimmed down.Now we are going to apply a regular expression to check if the input pattern has multiple occurrences of digits 0-9.If the input pattern contains only digits, this means that the input entered is a valid integer and in all other cases, invalid integer input is shown." }, { "code": null, "e": 26314, "s": 26288, "text": "Take input from the user." }, { "code": null, "e": 26346, "s": 26314, "text": "Store the input of any variable" }, { "code": null, "e": 26469, "s": 26346, "text": "Now we are going to trim the input in such a way that all the -(minus) or +(plus) signs before the input are trimmed down." }, { "code": null, "e": 26586, "s": 26469, "text": "Now we are going to apply a regular expression to check if the input pattern has multiple occurrences of digits 0-9." }, { "code": null, "e": 26738, "s": 26586, "text": "If the input pattern contains only digits, this means that the input entered is a valid integer and in all other cases, invalid integer input is shown." }, { "code": null, "e": 26771, "s": 26738, "text": "The Shell Script is given below:" }, { "code": null, "e": 27019, "s": 26771, "text": "# Asking the user to enter an input\necho \"Enter an input\"\n\n# reading and storing input\nread variable\n\n# Applying the approach given above\n\ncase ${variable#[-+]} in\n *[!0-9]* | '') echo \"Not an integer\" ;;\n * ) echo \"Valid integer number\" ;;\nesac" }, { "code": null, "e": 27027, "s": 27019, "text": "Output:" }, { "code": null, "e": 27060, "s": 27027, "text": "Output of the above code snippet" }, { "code": null, "e": 27067, "s": 27060, "text": "Picked" }, { "code": null, "e": 27080, "s": 27067, "text": "Shell Script" }, { "code": null, "e": 27091, "s": 27080, "text": "Linux-Unix" }, { "code": null, "e": 27189, "s": 27091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27224, "s": 27189, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27258, "s": 27224, "text": "mv command in Linux with examples" }, { "code": null, "e": 27284, "s": 27258, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27313, "s": 27284, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27350, "s": 27313, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27387, "s": 27350, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27429, "s": 27387, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27455, "s": 27429, "text": "Thread functions in C/C++" }, { "code": null, "e": 27491, "s": 27455, "text": "uniq Command in LINUX with examples" } ]
How to set/insert null values to in to a column of a row using JDBC program?
You can insert null values into a table in SQL in two ways: Directly inserting the value NULL into the desired column as: Directly inserting the value NULL into the desired column as: Insert into SampleTable values (NULL); Using ‘ ’ as null Using ‘ ’ as null Insert into SampleTable values (NULL); While inserting data into a table using prepared statement object you can set null values to a column using the setNull() method of the PreparedStatement interface. pstmt.setNull(parameterIndex, sqlType); Assume we have a table named cricketers_data in the database with the following contents: +------------+------------+---------------+----------------+-------------+ | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country | +------------+------------+---------------+----------------+-------------+ | Shikhar | Dhawan | 1981-12-05 | Delhi | India | | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica | | Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka | | Virat | Kohli | 1987-04-30 | Delhi | India | | Rohit | Sharma | 1987-04-30 | Nagpur | India | +------------+------------+---------------+----------------+-------------+ Following JDBC program connects to database and inserts a new row into it with place of birth value as NULL. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.Types; public class InsertingNull { public static void main(String args[])throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Inserting values to a table String query = "INSERT INTO cricketers_data VALUES (?, ?, ?, ?, ?)"; //Creating a Prepared Statement object PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Ravindra"); pstmt.setString(2, "Jadeja"); pstmt.setDate(3, new Date(597396086000L)); //Setting null value to a column pstmt.setNull(4, Types.NULL); pstmt.setString(5, "India"); pstmt.execute(); System.out.println("Record inserted"); } } Connection established...... Record inserted...... If you retrieve the contents of the cricketers_data table you can observe the newly inserted record with null value. mysql> select * from cricketers_data; +------------+------------+---------------+----------------+-------------+ | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country | +------------+------------+---------------+----------------+-------------+ | Shikhar | Dhawan | 1981-12-05 | Delhi | India | | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica | | Lumara | Sangakkara | 1977-10-27 | Matale | Srilanka | | Virat | Kohli | 1987-04-30 | Delhi | India | | Rohit | Sharma | 1987-04-30 | Nagpur | India | | Ravindra | Jadeja | 1988-12-06 | NULL | India | +------------+------------+---------------+----------------+-------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1122, "s": 1062, "text": "You can insert null values into a table in SQL in two ways:" }, { "code": null, "e": 1184, "s": 1122, "text": "Directly inserting the value NULL into the desired column as:" }, { "code": null, "e": 1246, "s": 1184, "text": "Directly inserting the value NULL into the desired column as:" }, { "code": null, "e": 1285, "s": 1246, "text": "Insert into SampleTable values (NULL);" }, { "code": null, "e": 1303, "s": 1285, "text": "Using ‘ ’ as null" }, { "code": null, "e": 1321, "s": 1303, "text": "Using ‘ ’ as null" }, { "code": null, "e": 1360, "s": 1321, "text": "Insert into SampleTable values (NULL);" }, { "code": null, "e": 1525, "s": 1360, "text": "While inserting data into a table using prepared statement object you can set null values to a column using the setNull() method of the PreparedStatement interface." }, { "code": null, "e": 1565, "s": 1525, "text": "pstmt.setNull(parameterIndex, sqlType);" }, { "code": null, "e": 1655, "s": 1565, "text": "Assume we have a table named cricketers_data in the database with the following contents:" }, { "code": null, "e": 2330, "s": 1655, "text": "+------------+------------+---------------+----------------+-------------+\n| First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |\n+------------+------------+---------------+----------------+-------------+\n| Shikhar | Dhawan | 1981-12-05 | Delhi | India |\n| Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |\n| Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka |\n| Virat | Kohli | 1987-04-30 | Delhi | India |\n| Rohit | Sharma | 1987-04-30 | Nagpur | India |\n+------------+------------+---------------+----------------+-------------+" }, { "code": null, "e": 2439, "s": 2330, "text": "Following JDBC program connects to database and inserts a new row into it with place of birth value as NULL." }, { "code": null, "e": 3629, "s": 2439, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.Statement;\nimport java.sql.Types;\npublic class InsertingNull {\n public static void main(String args[])throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Inserting values to a table\n String query = \"INSERT INTO cricketers_data VALUES (?, ?, ?, ?, ?)\";\n //Creating a Prepared Statement object\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Ravindra\");\n pstmt.setString(2, \"Jadeja\");\n pstmt.setDate(3, new Date(597396086000L));\n //Setting null value to a column\n pstmt.setNull(4, Types.NULL);\n pstmt.setString(5, \"India\");\n pstmt.execute();\n System.out.println(\"Record inserted\");\n }\n}" }, { "code": null, "e": 3680, "s": 3629, "text": "Connection established......\nRecord inserted......" }, { "code": null, "e": 3797, "s": 3680, "text": "If you retrieve the contents of the cricketers_data table you can observe the newly inserted record with null value." }, { "code": null, "e": 4611, "s": 3797, "text": "mysql> select * from cricketers_data;\n\n+------------+------------+---------------+----------------+-------------+\n| First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |\n+------------+------------+---------------+----------------+-------------+\n| Shikhar | Dhawan | 1981-12-05 | Delhi | India |\n| Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |\n| Lumara | Sangakkara | 1977-10-27 | Matale | Srilanka |\n| Virat | Kohli | 1987-04-30 | Delhi | India |\n| Rohit | Sharma | 1987-04-30 | Nagpur | India |\n| Ravindra | Jadeja | 1988-12-06 | NULL | India |\n+------------+------------+---------------+----------------+-------------+\n6 rows in set (0.00 sec)" } ]
Modify a bit at a given position - GeeksforGeeks
25 Apr, 2022 Given a number n, a position p and a binary value b, we need to change the bit at position p in n to value b. Examples : Input : n = 7, p = 2, b = 0 Output : 3 7 is 00000111 after clearing bit at 2nd position, it becomes 0000011. Input : n = 7, p = 3, b = 1 Output : 15 7 is 00000111 after setting bit at 3rd position it becomes 00001111. We first create a mask that has set bit only at given position using bit wise shift. mask = 1 << position Then to change value of bit to b, we first make it 0 using below operation value & ~mask After changing it 0, we change it to b by doing or of above expression with following (b << p) & mask, i.e., we return ((n & ~mask) | (b << p)) Below is the implementation of above steps : C++ Java Python3 C# PHP Javascript // CPP program to modify a bit at position// p in n to b.#include <bits/stdc++.h>using namespace std; // Returns modified n.int modifyBit(int n, int p, int b){ int mask = 1 << p; return ((n & ~mask) | (b << p));} // Driver codeint main(){ cout << modifyBit(6, 2, 0) << endl; cout << modifyBit(6, 5, 1) << endl; return 0;} // Java program to modify a bit// at position p in n to b.import java.io.*; class GFG{ // Returns modified n.public static int modifyBit(int n, int p, int b){ int mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver Code public static void main (String[] args) { System.out.println(modifyBit(6, 2, 0)); System.out.println (modifyBit(6, 5, 1)); }} // This code is contributed by m_kit # Python3 program to modify a bit at position# p in n to b. # Returns modified n.def modifyBit( n, p, b): mask = 1 << p return (n & ~mask) | ((b << p) & mask) # Driver codedef main(): print(modifyBit(6, 2, 0)) print(modifyBit(6, 5, 1)) if __name__ == '__main__': main()# This code is contributed by PrinciRaj1992 // C# program to modify a bit// at position p in n to b.using System; class GFG{// Returns modified n.public static int modifyBit(int n, int p, int b){ int mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver Code static public void Main () { Console.WriteLine(modifyBit(6, 2, 0)); Console.WriteLine(modifyBit(6, 5, 1)); }} // This code is contributed by ajit <?php// PHP program to modify a bit// at position p in n to b. // Returns modified n.function modifyBit($n, $p, $b){ $mask = 1 << $p; return ($n & ~$mask) | (($b << $p) & $mask);} // Driver code echo modifyBit(6, 2, 0),"\n"; echo modifyBit(6, 5, 1) ,"\n"; // This code is contributed by ajit?> <script> // Javascript program to modify a bit// at position p in n to b. // Returns modified n.function modifyBit(n, p, b){ let mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver codedocument.write(modifyBit(6, 2, 0) + "<br/>");document.write(modifyBit(6, 5, 1)); // This code is contributed by susmitakundugoaldanga </script> Output : 2 38 Time Complexity :O(1) This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t princiraj1992 gfg_sal_gfg ajaykr00kj susmitakundugoaldanga xdvxkhbllpisbwovid Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Hamming code Implementation in C/C++ Program to find parity Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Implementation of Bit Stuffing and Bit Destuffing Builtin functions of GCC compiler Swap bits in a given number Check for Integer Overflow Bit Tricks for Competitive Programming
[ { "code": null, "e": 25012, "s": 24984, "text": "\n25 Apr, 2022" }, { "code": null, "e": 25122, "s": 25012, "text": "Given a number n, a position p and a binary value b, we need to change the bit at position p in n to value b." }, { "code": null, "e": 25134, "s": 25122, "text": "Examples : " }, { "code": null, "e": 25355, "s": 25134, "text": "Input : n = 7, p = 2, b = 0\nOutput : 3\n7 is 00000111 after clearing bit at \n2nd position, it becomes 0000011.\n\nInput : n = 7, p = 3, b = 1\nOutput : 15\n7 is 00000111 after setting bit at \n3rd position it becomes 00001111." }, { "code": null, "e": 25715, "s": 25355, "text": "We first create a mask that has set bit only \nat given position using bit wise shift.\n mask = 1 << position\n\nThen to change value of bit to b, we first\nmake it 0 using below operation\n value & ~mask\n\nAfter changing it 0, we change it to b by\ndoing or of above expression with following\n(b << p) & mask, i.e., we return\n ((n & ~mask) | (b << p))" }, { "code": null, "e": 25762, "s": 25715, "text": "Below is the implementation of above steps : " }, { "code": null, "e": 25766, "s": 25762, "text": "C++" }, { "code": null, "e": 25771, "s": 25766, "text": "Java" }, { "code": null, "e": 25779, "s": 25771, "text": "Python3" }, { "code": null, "e": 25782, "s": 25779, "text": "C#" }, { "code": null, "e": 25786, "s": 25782, "text": "PHP" }, { "code": null, "e": 25797, "s": 25786, "text": "Javascript" }, { "code": "// CPP program to modify a bit at position// p in n to b.#include <bits/stdc++.h>using namespace std; // Returns modified n.int modifyBit(int n, int p, int b){ int mask = 1 << p; return ((n & ~mask) | (b << p));} // Driver codeint main(){ cout << modifyBit(6, 2, 0) << endl; cout << modifyBit(6, 5, 1) << endl; return 0;}", "e": 26134, "s": 25797, "text": null }, { "code": "// Java program to modify a bit// at position p in n to b.import java.io.*; class GFG{ // Returns modified n.public static int modifyBit(int n, int p, int b){ int mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver Code public static void main (String[] args) { System.out.println(modifyBit(6, 2, 0)); System.out.println (modifyBit(6, 5, 1)); }} // This code is contributed by m_kit", "e": 26631, "s": 26134, "text": null }, { "code": "# Python3 program to modify a bit at position# p in n to b. # Returns modified n.def modifyBit( n, p, b): mask = 1 << p return (n & ~mask) | ((b << p) & mask) # Driver codedef main(): print(modifyBit(6, 2, 0)) print(modifyBit(6, 5, 1)) if __name__ == '__main__': main()# This code is contributed by PrinciRaj1992", "e": 26966, "s": 26631, "text": null }, { "code": "// C# program to modify a bit// at position p in n to b.using System; class GFG{// Returns modified n.public static int modifyBit(int n, int p, int b){ int mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver Code static public void Main () { Console.WriteLine(modifyBit(6, 2, 0)); Console.WriteLine(modifyBit(6, 5, 1)); }} // This code is contributed by ajit", "e": 27441, "s": 26966, "text": null }, { "code": "<?php// PHP program to modify a bit// at position p in n to b. // Returns modified n.function modifyBit($n, $p, $b){ $mask = 1 << $p; return ($n & ~$mask) | (($b << $p) & $mask);} // Driver code echo modifyBit(6, 2, 0),\"\\n\"; echo modifyBit(6, 5, 1) ,\"\\n\"; // This code is contributed by ajit?>", "e": 27765, "s": 27441, "text": null }, { "code": "<script> // Javascript program to modify a bit// at position p in n to b. // Returns modified n.function modifyBit(n, p, b){ let mask = 1 << p; return (n & ~mask) | ((b << p) & mask);} // Driver codedocument.write(modifyBit(6, 2, 0) + \"<br/>\");document.write(modifyBit(6, 5, 1)); // This code is contributed by susmitakundugoaldanga </script>", "e": 28124, "s": 27765, "text": null }, { "code": null, "e": 28134, "s": 28124, "text": "Output : " }, { "code": null, "e": 28141, "s": 28134, "text": " 2\n 38" }, { "code": null, "e": 28163, "s": 28141, "text": "Time Complexity :O(1)" }, { "code": null, "e": 28588, "s": 28163, "text": "This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28594, "s": 28588, "text": "jit_t" }, { "code": null, "e": 28608, "s": 28594, "text": "princiraj1992" }, { "code": null, "e": 28620, "s": 28608, "text": "gfg_sal_gfg" }, { "code": null, "e": 28631, "s": 28620, "text": "ajaykr00kj" }, { "code": null, "e": 28653, "s": 28631, "text": "susmitakundugoaldanga" }, { "code": null, "e": 28672, "s": 28653, "text": "xdvxkhbllpisbwovid" }, { "code": null, "e": 28682, "s": 28672, "text": "Bit Magic" }, { "code": null, "e": 28692, "s": 28682, "text": "Bit Magic" }, { "code": null, "e": 28790, "s": 28692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28841, "s": 28790, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 28878, "s": 28841, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 28901, "s": 28878, "text": "Program to find parity" }, { "code": null, "e": 28938, "s": 28901, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 29002, "s": 28938, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 29052, "s": 29002, "text": "Implementation of Bit Stuffing and Bit Destuffing" }, { "code": null, "e": 29086, "s": 29052, "text": "Builtin functions of GCC compiler" }, { "code": null, "e": 29114, "s": 29086, "text": "Swap bits in a given number" }, { "code": null, "e": 29141, "s": 29114, "text": "Check for Integer Overflow" } ]
Next Permutation | Practice | GeeksforGeeks
Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N. Example 1: Input: N = 6 arr = {1, 2, 3, 6, 5, 4} Output: {1, 2, 4, 3, 5, 6} Explaination: The next permutation of the given array is {1, 2, 4, 3, 5, 6}. Example 2: Input: N = 3 arr = {3, 2, 1} Output: {1, 2, 3} Explaination: As arr[] is the last permutation. So, the next permutation is the lowest one. Your Task: You do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 10000 0 antaryamisingh2521 day ago vector<int> nextPermutation(int N, vector<int> arr){ int i =0; for(i = N-1; i>0; i--) { if(arr[i-1] < arr[i]){ sort(arr.begin()+i, arr.end()); for(int j=i; j<N; j++){ if(arr[i-1] < arr[j]){ swap(arr[i-1], arr[j]); break; } } break; } } if(i==0){ sort(arr.begin(), arr.end()); } return arr; } 0 hasnainansari97576 days ago class Solution{ public: vector<int> nextPermutation(int N, vector<int> arr){ // code here vector<int> ans; int idx = -1; for(int i=N-1;i>0;i--){ if(arr[i] > arr[i-1]){ idx = i; break; } } if(idx == -1){ reverse(arr.begin(), arr.end()); } else{ int prev = idx; for(int i=idx+1;i<N;i++){ if(arr[i] > arr[idx-1] && arr[i] <= arr[prev]){ prev = i; } } swap(arr[idx-1], arr[prev]); reverse(arr.begin()+idx, arr.end()); } for(int i=0;i<N;i++){ ans.push_back(arr[i]); } return ans; } }; 0 vermaanshu20051 week ago Java 0.17/1.14 class Solution{ static List<Integer> nextPermutation(int n, int arr[]){ List<Integer> list = new ArrayList<>(); int i = n-2; int ind1 = -1; while(i >= 0) { if(arr[i] < arr[i+1]) { ind1 = i; break; } i--; } if(ind1 == -1) { reverse(arr, 0); makeList(list, arr); return list; } i = n-1; int ind2 = -1; while(i >= 0) { if(arr[i] > arr[ind1]) { ind2 = i; break; } i--; } swap(arr, ind1, ind2); reverse(arr, ind1 + 1); makeList(list, arr); return list; } static void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void reverse(int arr[], int index) { int i = index; int j = arr.length - 1; while(i < j) { swap(arr, i, j); i++; j--; } } static void makeList(List<Integer> list, int arr[]) { for(int i=0;i<arr.length;i++) { list.add(arr[i]); } } } +1 sparshtanejaa1 week ago best solution you will find so far 0.01ms time vector<int> nextPermutation(int N, vector<int> s){ // code here next_permutation(s.begin(),s.end()); return s; } -1 hoodninja3 weeks ago int i,j; i = n-2; while(arr[i] >= arr[i+1] && i>=0) { i--; } if(i==-1) { reverse(arr.begin(),arr.end()); return arr; } j = n-1; while(arr[j]<arr[i]) { j--; } swap(arr[i],arr[j]); reverse(arr.begin() + i + 1,arr.end()); return arr; 0 abhitheagrawal3 weeks ago vector<int> nextPermutation(int N, vector<int> arr){ bool val = next_permutation(arr.begin(),arr.end()); if(val==false) { sort(arr.begin(),arr.end()); return arr;; } return arr; // code here } 0 ritikyadavr113 weeks ago class Solution{public: vector<int> nextPermutation(int N, vector<int> arr){ // find pivote element or largest non increasing suffix int l,r; for(l=N-2; l>=0; l--) { if(arr[l] < arr[l+1]) break; } if(l < 0) reverse(arr.begin(),arr.end()); else{ //find right most successor to pivote in suffix for(r=N-1; r>l; r--) { if(arr[r]>arr[l]) break; } //swap l,r swap(arr[l],arr[r]); //reverse l+1 to end reverse(arr.begin()+l+1,arr.end()); } return arr; }}; +1 amishasahu3283 weeks ago class Solution{ public: vector<int> nextPermutation(int N, vector<int> arr){ // code here int x = -1, y = -1; for(int i = 0; i < N-1; i++) if(arr[i] < arr[i+1]) x = i; if(x == -1) { sort(arr.begin(), arr.end()); return arr; } for(int i = x+1; i < N; i++) { if(arr[x] < arr[i]) y = i; } swap(arr[x], arr[y]); reverse(arr.begin()+x+1, arr.end()); return arr; } }; 0 rs263 weeks ago JAVA Sol. Time -: 0.2/1.1 sec class Solution{ static List<Integer> nextPermutation(int N, int arr[]){ // code here ArrayList<Integer> a1=new ArrayList<>(); ArrayList<Integer> a2=new ArrayList<>(); int max_ind=Integer.MIN_VALUE; int c=0; for(int i=0;i<N-1;i++) { if(arr[i]<arr[i+1] && max_ind<i) max_ind=i; } if(max_ind<0) { Arrays.sort(arr); for(int i=0;i<N;i++) a1.add(arr[i]); } else { int max=-1; for(int i=max_ind+1;i<N;i++) { if(arr[max_ind]<arr[i] && max<i) max=i; } int temp=arr[max_ind]; arr[max_ind]=arr[max]; arr[max]=temp; for(int i=0;i<=max_ind;i++) { a1.add(arr[i]); } for(int i=N-1;i>max_ind;i--) { a2.add(arr[i]); } a1.addAll(a2); } return a1; } } +1 bhargabnath6913 weeks ago Time Taken: 0.0/1.1 Approach: Find the first dip element from end of the array. If there is no such dip element, it simply means that the given array is in descending order, hence reverse the array and return it. Otherwise, look for the first element which is greater than the dip, and then swap the dip and peak element. Till this point we have observed the dip and peak element from the end of the array and we also swapped them between themselves, thus earlier dip is now peak and earlier peak is now dip. But the twist here is that, between these 2 elements, the elements should also be in ascending order, so we have got to reverse the array right from the next element to the index of the earlier dip(or new peak) element. That will be the final array for us. For example: [2, 4, 1, 5, 3] First dip element from the end of the array: 1 (NOTE: we keep track of dip element's index here, not the dip element itself , similarly for peak element also) So, dip = 2(index of the dip element) Then, first peak element from the end of the array which is greater than dip element = 3 So, peak = 4 (index of the peak element) swap(nums[dip], nums[peak]) = swap(nums[2], nums[4]) = swap(1, 3) The array now is: [2, 4, 3, 5, 1], But it's not our final answer, since we can easily observe from here, that, [2, 4, 3, 1, 5] is an array which is lexicographically smaller than [2, 4, 3, 5, 1] So, we need to have the elements after dip(index, not to forget, which is 2 here) in ascending order, therefore, reverse the array from the dip + 1 to end index and that is the final output array for us. So, reverse(arr.begin() + dip + 1, arr.end()) = reverse(0+2+1, 4) = reverse(3, 4) Thus, [2,4,3,1,5] = final answer, return it. vector<int> nextPermutation(int N, vector<int> arr){ // code here int peak; int dip; for(dip=N-2; dip>=0; dip--){ if(arr[dip] < arr[dip+1]) break; } if(dip < 0) reverse(arr.begin(), arr.end()); else { for(peak=N-1; peak>dip; peak--){ if(arr[peak] > arr[dip]) break; } swap(arr[peak], arr[dip]); reverse(arr.begin() + dip + 1, arr.end()); } return arr; } 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": 549, "s": 238, "text": "Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N." }, { "code": null, "e": 560, "s": 549, "text": "Example 1:" }, { "code": null, "e": 703, "s": 560, "text": "Input: N = 6\narr = {1, 2, 3, 6, 5, 4}\nOutput: {1, 2, 4, 3, 5, 6}\nExplaination: The next permutation of the \ngiven array is {1, 2, 4, 3, 5, 6}." }, { "code": null, "e": 714, "s": 703, "text": "Example 2:" }, { "code": null, "e": 855, "s": 714, "text": "Input: N = 3\narr = {3, 2, 1}\nOutput: {1, 2, 3}\nExplaination: As arr[] is the last \npermutation. So, the next permutation \nis the lowest one." }, { "code": null, "e": 1079, "s": 855, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation." }, { "code": null, "e": 1141, "s": 1079, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1168, "s": 1141, "text": "Constraints:\n1 ≤ N ≤ 10000" }, { "code": null, "e": 1170, "s": 1168, "text": "0" }, { "code": null, "e": 1197, "s": 1170, "text": "antaryamisingh2521 day ago" }, { "code": null, "e": 1620, "s": 1197, "text": "vector<int> nextPermutation(int N, vector<int> arr){ int i =0; for(i = N-1; i>0; i--) { if(arr[i-1] < arr[i]){ sort(arr.begin()+i, arr.end()); for(int j=i; j<N; j++){ if(arr[i-1] < arr[j]){ swap(arr[i-1], arr[j]); break; } } break; } } if(i==0){ sort(arr.begin(), arr.end()); } return arr; }" }, { "code": null, "e": 1622, "s": 1620, "text": "0" }, { "code": null, "e": 1650, "s": 1622, "text": "hasnainansari97576 days ago" }, { "code": null, "e": 1666, "s": 1650, "text": "class Solution{" }, { "code": null, "e": 1674, "s": 1666, "text": "public:" }, { "code": null, "e": 1731, "s": 1674, "text": " vector<int> nextPermutation(int N, vector<int> arr){" }, { "code": null, "e": 1752, "s": 1731, "text": " // code here" }, { "code": null, "e": 1777, "s": 1752, "text": " vector<int> ans;" }, { "code": null, "e": 1799, "s": 1777, "text": " int idx = -1;" }, { "code": null, "e": 1831, "s": 1799, "text": " for(int i=N-1;i>0;i--){" }, { "code": null, "e": 1867, "s": 1831, "text": " if(arr[i] > arr[i-1]){ " }, { "code": null, "e": 1893, "s": 1867, "text": " idx = i; " }, { "code": null, "e": 1916, "s": 1893, "text": " break;" }, { "code": null, "e": 1930, "s": 1916, "text": " }" }, { "code": null, "e": 1940, "s": 1930, "text": " }" }, { "code": null, "e": 1972, "s": 1948, "text": " if(idx == -1){ " }, { "code": null, "e": 2017, "s": 1972, "text": " reverse(arr.begin(), arr.end());" }, { "code": null, "e": 2027, "s": 2017, "text": " }" }, { "code": null, "e": 2041, "s": 2027, "text": " else{" }, { "code": null, "e": 2069, "s": 2041, "text": " int prev = idx;" }, { "code": null, "e": 2108, "s": 2069, "text": " for(int i=idx+1;i<N;i++){ " }, { "code": null, "e": 2172, "s": 2108, "text": " if(arr[i] > arr[idx-1] && arr[i] <= arr[prev]){" }, { "code": null, "e": 2202, "s": 2172, "text": " prev = i;" }, { "code": null, "e": 2220, "s": 2202, "text": " }" }, { "code": null, "e": 2234, "s": 2220, "text": " }" }, { "code": null, "e": 2275, "s": 2234, "text": " swap(arr[idx-1], arr[prev]);" }, { "code": null, "e": 2324, "s": 2275, "text": " reverse(arr.begin()+idx, arr.end());" }, { "code": null, "e": 2358, "s": 2348, "text": " }" }, { "code": null, "e": 2396, "s": 2366, "text": " for(int i=0;i<N;i++){" }, { "code": null, "e": 2431, "s": 2396, "text": " ans.push_back(arr[i]);" }, { "code": null, "e": 2441, "s": 2431, "text": " }" }, { "code": null, "e": 2461, "s": 2441, "text": " return ans;" }, { "code": null, "e": 2483, "s": 2477, "text": " }" }, { "code": null, "e": 2486, "s": 2483, "text": "};" }, { "code": null, "e": 2488, "s": 2486, "text": "0" }, { "code": null, "e": 2513, "s": 2488, "text": "vermaanshu20051 week ago" }, { "code": null, "e": 3882, "s": 2513, "text": "Java 0.17/1.14\n\n\n\n\nclass Solution{\n static List<Integer> nextPermutation(int n, int arr[]){\n List<Integer> list = new ArrayList<>();\n int i = n-2;\n int ind1 = -1;\n while(i >= 0)\n {\n if(arr[i] < arr[i+1])\n {\n ind1 = i;\n break;\n }\n i--;\n }\n \n if(ind1 == -1)\n {\n reverse(arr, 0);\n makeList(list, arr);\n return list; \n }\n i = n-1;\n int ind2 = -1;\n while(i >= 0)\n {\n if(arr[i] > arr[ind1])\n {\n ind2 = i;\n break;\n }\n i--;\n }\n \n swap(arr, ind1, ind2);\n \n reverse(arr, ind1 + 1);\n makeList(list, arr);\n return list; \n }\n \n static void swap(int arr[], int i, int j)\n {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n \n static void reverse(int arr[], int index)\n {\n int i = index;\n int j = arr.length - 1;\n while(i < j)\n {\n swap(arr, i, j);\n i++;\n j--;\n }\n }\n \n static void makeList(List<Integer> list, int arr[])\n {\n for(int i=0;i<arr.length;i++)\n {\n list.add(arr[i]);\n }\n }\n}" }, { "code": null, "e": 3885, "s": 3882, "text": "+1" }, { "code": null, "e": 3909, "s": 3885, "text": "sparshtanejaa1 week ago" }, { "code": null, "e": 3956, "s": 3909, "text": "best solution you will find so far 0.01ms time" }, { "code": null, "e": 4096, "s": 3958, "text": " vector<int> nextPermutation(int N, vector<int> s){ // code here next_permutation(s.begin(),s.end()); return s; }" }, { "code": null, "e": 4099, "s": 4096, "text": "-1" }, { "code": null, "e": 4120, "s": 4099, "text": "hoodninja3 weeks ago" }, { "code": null, "e": 4554, "s": 4120, "text": " int i,j;\n i = n-2;\n \n \n while(arr[i] >= arr[i+1] && i>=0)\n {\n i--;\n }\n \n if(i==-1)\n {\n reverse(arr.begin(),arr.end());\n return arr;\n }\n j = n-1;\n while(arr[j]<arr[i])\n {\n j--;\n }\n swap(arr[i],arr[j]);\n \n reverse(arr.begin() + i + 1,arr.end());\n return arr;" }, { "code": null, "e": 4556, "s": 4554, "text": "0" }, { "code": null, "e": 4582, "s": 4556, "text": "abhitheagrawal3 weeks ago" }, { "code": null, "e": 4839, "s": 4582, "text": "vector<int> nextPermutation(int N, vector<int> arr){ bool val = next_permutation(arr.begin(),arr.end()); if(val==false) { sort(arr.begin(),arr.end()); return arr;; } return arr; // code here }" }, { "code": null, "e": 4841, "s": 4839, "text": "0" }, { "code": null, "e": 4866, "s": 4841, "text": "ritikyadavr113 weeks ago" }, { "code": null, "e": 5462, "s": 4866, "text": "class Solution{public: vector<int> nextPermutation(int N, vector<int> arr){ // find pivote element or largest non increasing suffix int l,r; for(l=N-2; l>=0; l--) { if(arr[l] < arr[l+1]) break; } if(l < 0) reverse(arr.begin(),arr.end()); else{ //find right most successor to pivote in suffix for(r=N-1; r>l; r--) { if(arr[r]>arr[l]) break; } //swap l,r swap(arr[l],arr[r]); //reverse l+1 to end reverse(arr.begin()+l+1,arr.end()); } return arr; }}; " }, { "code": null, "e": 5465, "s": 5462, "text": "+1" }, { "code": null, "e": 5490, "s": 5465, "text": "amishasahu3283 weeks ago" }, { "code": null, "e": 6072, "s": 5490, "text": "class Solution{\npublic:\n vector<int> nextPermutation(int N, vector<int> arr){\n // code here\n int x = -1, y = -1;\n for(int i = 0; i < N-1; i++)\n if(arr[i] < arr[i+1])\n x = i;\n \n if(x == -1)\n {\n sort(arr.begin(), arr.end());\n return arr;\n }\n \n for(int i = x+1; i < N; i++)\n {\n if(arr[x] < arr[i])\n y = i;\n }\n \n swap(arr[x], arr[y]);\n \n reverse(arr.begin()+x+1, arr.end());\n return arr;\n }\n};" }, { "code": null, "e": 6074, "s": 6072, "text": "0" }, { "code": null, "e": 6090, "s": 6074, "text": "rs263 weeks ago" }, { "code": null, "e": 6100, "s": 6090, "text": "JAVA Sol." }, { "code": null, "e": 6120, "s": 6100, "text": "Time -: 0.2/1.1 sec" }, { "code": null, "e": 7177, "s": 6120, "text": "class Solution{\n static List<Integer> nextPermutation(int N, int arr[]){\n // code here\n ArrayList<Integer> a1=new ArrayList<>();\n ArrayList<Integer> a2=new ArrayList<>();\n int max_ind=Integer.MIN_VALUE;\n int c=0;\n for(int i=0;i<N-1;i++)\n {\n if(arr[i]<arr[i+1] && max_ind<i) \n max_ind=i;\n }\n if(max_ind<0)\n {\n Arrays.sort(arr);\n for(int i=0;i<N;i++)\n a1.add(arr[i]);\n }\n else\n {\n int max=-1;\n for(int i=max_ind+1;i<N;i++)\n {\n if(arr[max_ind]<arr[i] && max<i)\n max=i;\n }\n int temp=arr[max_ind];\n arr[max_ind]=arr[max];\n arr[max]=temp;\n \n for(int i=0;i<=max_ind;i++)\n {\n a1.add(arr[i]);\n }\n for(int i=N-1;i>max_ind;i--)\n {\n a2.add(arr[i]);\n }\n a1.addAll(a2);\n }\n return a1;\n }\n}" }, { "code": null, "e": 7180, "s": 7177, "text": "+1" }, { "code": null, "e": 7206, "s": 7180, "text": "bhargabnath6913 weeks ago" }, { "code": null, "e": 7226, "s": 7206, "text": "Time Taken: 0.0/1.1" }, { "code": null, "e": 7286, "s": 7226, "text": "Approach: Find the first dip element from end of the array." }, { "code": null, "e": 7419, "s": 7286, "text": "If there is no such dip element, it simply means that the given array is in descending order, hence reverse the array and return it." }, { "code": null, "e": 7974, "s": 7419, "text": "Otherwise, look for the first element which is greater than the dip, and then swap the dip and peak element. Till this point we have observed the dip and peak element from the end of the array and we also swapped them between themselves, thus earlier dip is now peak and earlier peak is now dip. But the twist here is that, between these 2 elements, the elements should also be in ascending order, so we have got to reverse the array right from the next element to the index of the earlier dip(or new peak) element. That will be the final array for us." }, { "code": null, "e": 8005, "s": 7976, "text": "For example: [2, 4, 1, 5, 3]" }, { "code": null, "e": 8164, "s": 8005, "text": "First dip element from the end of the array: 1 (NOTE: we keep track of dip element's index here, not the dip element itself , similarly for peak element also)" }, { "code": null, "e": 8202, "s": 8164, "text": "So, dip = 2(index of the dip element)" }, { "code": null, "e": 8293, "s": 8204, "text": "Then, first peak element from the end of the array which is greater than dip element = 3" }, { "code": null, "e": 8335, "s": 8293, "text": "So, peak = 4 (index of the peak element)" }, { "code": null, "e": 8403, "s": 8337, "text": "swap(nums[dip], nums[peak]) = swap(nums[2], nums[4]) = swap(1, 3)" }, { "code": null, "e": 8438, "s": 8403, "text": "The array now is: [2, 4, 3, 5, 1]," }, { "code": null, "e": 8598, "s": 8438, "text": "But it's not our final answer, since we can easily observe from here, that, [2, 4, 3, 1, 5] is an array which is lexicographically smaller than [2, 4, 3, 5, 1]" }, { "code": null, "e": 8802, "s": 8598, "text": "So, we need to have the elements after dip(index, not to forget, which is 2 here) in ascending order, therefore, reverse the array from the dip + 1 to end index and that is the final output array for us." }, { "code": null, "e": 8884, "s": 8802, "text": "So, reverse(arr.begin() + dip + 1, arr.end()) = reverse(0+2+1, 4) = reverse(3, 4)" }, { "code": null, "e": 8929, "s": 8884, "text": "Thus, [2,4,3,1,5] = final answer, return it." }, { "code": null, "e": 9438, "s": 8931, "text": "\tvector<int> nextPermutation(int N, vector<int> arr){\n // code here\n int peak;\n int dip;\n for(dip=N-2; dip>=0; dip--){\n if(arr[dip] < arr[dip+1]) break;\n }\n if(dip < 0) reverse(arr.begin(), arr.end());\n else {\n for(peak=N-1; peak>dip; peak--){\n if(arr[peak] > arr[dip]) break;\n }\n swap(arr[peak], arr[dip]);\n reverse(arr.begin() + dip + 1, arr.end());\n }\n return arr;\n }" }, { "code": null, "e": 9584, "s": 9438, "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": 9620, "s": 9584, "text": " Login to access your submissions. " }, { "code": null, "e": 9630, "s": 9620, "text": "\nProblem\n" }, { "code": null, "e": 9640, "s": 9630, "text": "\nContest\n" }, { "code": null, "e": 9703, "s": 9640, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9851, "s": 9703, "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": 10059, "s": 9851, "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": 10165, "s": 10059, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Extracting a substring as an array of characters in Java
To extract a substring as an array of characters in Java, use the getChars() method. Let’s say the following is our string and character array. String str = "World is not enough!"; char[] chArr = new char[10]; Now, use the getChars() method to extract a substring. str.getChars(13, 19, chArr, 0); The above substring is an array of characters which can be displayed as shown in the complete example below − Live Demo public class Demo { public static void main(String[] args) { String str = "World is not enough!"; char[] chArr = new char[10]; str.getChars(13, 19, chArr, 0); for(char res: chArr) { System.out.println(res); } } } e n o u g h
[ { "code": null, "e": 1147, "s": 1062, "text": "To extract a substring as an array of characters in Java, use the getChars() method." }, { "code": null, "e": 1206, "s": 1147, "text": "Let’s say the following is our string and character array." }, { "code": null, "e": 1272, "s": 1206, "text": "String str = \"World is not enough!\";\nchar[] chArr = new char[10];" }, { "code": null, "e": 1327, "s": 1272, "text": "Now, use the getChars() method to extract a substring." }, { "code": null, "e": 1359, "s": 1327, "text": "str.getChars(13, 19, chArr, 0);" }, { "code": null, "e": 1469, "s": 1359, "text": "The above substring is an array of characters which can be displayed as shown in the complete example below −" }, { "code": null, "e": 1480, "s": 1469, "text": " Live Demo" }, { "code": null, "e": 1738, "s": 1480, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"World is not enough!\";\n char[] chArr = new char[10];\n str.getChars(13, 19, chArr, 0);\n for(char res: chArr) {\n System.out.println(res);\n }\n }\n}" }, { "code": null, "e": 1750, "s": 1738, "text": "e\nn\no\nu\ng\nh" } ]
How to Easily Make Beautiful Wordclouds in Python | by Frank Andrade | Towards Data Science
A wordcloud lets us easily identify the keywords in a text where the size of the words represents their frequency. With this, we’ll get a good idea of what a text is about before even reading it. Although there are many free tools to make wordclouds online, we can use our Python skills to customize wordclouds even more. In this article, we’re going to use the stylecloud library to make beautiful wordclouds with a few lines of code, the wordcloud library to add our own image to use it as a mask of our wordcloud and stop_words to customize the stopwords lists offered by default. The text we’re going to use to make a wordcloud is part of Steve Job’s speech at Standford. You can find the .txt file on my Github or use any text to make your own wordcloud. To easily make beautiful wordclouds, the first thing we have to do is to install stylecloud. You can install it via pip pip3 install stylecloud. Once you installed stylecloud, you have to import it. import stylecloud Now to create a basic wordcloud we need to use the .gen_stylecloud() method and add the path of the .txt file and the icon we’re going to use to give form to this wordcloud. On this website, you can find a list of icons that you can use with stylecloud. Just search the icon you want and copy the HTML code of the icon (in this example, I chose an apple as an icon) stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name= "fas fa-apple-alt") The result is the wordcloud below (the file is created in the same path where your Python script is located) But we can do even more! We can customize the wordcloud further to obtain a better-looking wordcloud. We can control the background color, the color of the words, the name of the output file, and also omit collocations of two words in the wordcloud. To do so, we’ll use the code below. stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name='fas fa-apple-alt', colors='white', background_color='black', output_name='apple.png', collocations=False) We can even write HTML code of colors instead of using standard colors like “white.” On this website, you can pick any color you want and get its HTML code that you can include in the colors parameter of stylecloud. Stylecloud has by default a list of stopwords in the English language, but in case you want to remove or add new stopwords you have to include a new list in the custom_stopwords parameter. To customize a list of stopwords, we have to use the stop_words library. To do so, first, install it (pip install stop_words) Then we use get_stop_words to get a list of stop words in a specific language. from stop_words import get_stop_wordsstop_words = get_stop_words('english') Once you defined the list, you can add or remove elements with the .append and .remove methods respectively. stop_words.append('my_new_stop_word')stop_words.remove('my_new_stop_word') Now, we only have to add the new stop_words list. I'm also going to use a palette instead of colors to give the wordcloud a different look. stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name='fas fa-apple-alt', palette='cartocolors.qualitative.Pastel_3', background_color='black', output_name='apple.png', collocations=False, custom_stopwords=stop_words) On this website, you can find a list of color palettes for Python that you can use with the stylecloud library (as you can see in the code above, the names separated by dots represent the content of the palettes module) There are hundreds of free icons available to use with stylecloud but sometimes we might want to use our own image to give form to the wordcloud we want to create. If that’s the case, we have to use the wordcloud library to make a wordcloud, PIL to upload an image, matplotlib to plot the wordcloud and numpy to use the image uploaded as a mask of our wordcloud. First, we install all of the 4 libraries mentioned before. Once we have all of them, we import them and start creating a wordcloud with the desired mask. from wordcloud import WordCloud, ImageColorGenerator from PIL import Imageimport matplotlib.pyplot as pltimport numpy as np# create a mask based on the image we wish to includemy_mask = np.array(Image.open('batman-logo.png'))# create a wordcloud wc = WordCloud(background_color='white', mask=my_mask, collocations=False, width=600, height=300, contour_width=3, contour_color='black', stopwords=stop_words) As you can see, the code used is similar to stylecloud with a few variations. We use mask to specify the image we want to use for the wordcloud (in this case, I’m using the batman logo). Also, we included the contour width and color to make the shape of the image more visible. Note: Make sure that the image you will use as a mask has a well-defined shape with clear boundaries otherwise the wordcloud will not look good. Now we have to read the text file and generate the wordcloud with the following code. with open('SJ-Speech.txt', 'r') as txt_file: texto = txt_file.read()wc.generate(texto) In case we want to use the original image’s color, we write the following code (if not the wordcloud will have random colors just like the first apple image shown in this article) image_colors = ImageColorGenerator(my_mask)wc.recolor(color_func=image_colors) Finally to plot the wordcloud we use matplotlib. plt.figure(figsize=(20, 10))plt.imshow(wc, interpolation='bilinear')plt.axis('off')wc.to_file('wordcloud.png')plt.show() I also remove the axis to only have the wordcloud in the plot and save the wordcloud withwc.to_file() That’s it! Now you’re ready to make your own wordcloud with Python! I created some wordclouds using Simpsons characters in the article below. towardsdatascience.com Here is a list of books I read to learn Python. betterprogramming.pub Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) Thanks for reading this article! In the articles below, you can find other guides I made to create beautiful visualization in Python.
[ { "code": null, "e": 494, "s": 172, "text": "A wordcloud lets us easily identify the keywords in a text where the size of the words represents their frequency. With this, we’ll get a good idea of what a text is about before even reading it. Although there are many free tools to make wordclouds online, we can use our Python skills to customize wordclouds even more." }, { "code": null, "e": 756, "s": 494, "text": "In this article, we’re going to use the stylecloud library to make beautiful wordclouds with a few lines of code, the wordcloud library to add our own image to use it as a mask of our wordcloud and stop_words to customize the stopwords lists offered by default." }, { "code": null, "e": 932, "s": 756, "text": "The text we’re going to use to make a wordcloud is part of Steve Job’s speech at Standford. You can find the .txt file on my Github or use any text to make your own wordcloud." }, { "code": null, "e": 1077, "s": 932, "text": "To easily make beautiful wordclouds, the first thing we have to do is to install stylecloud. You can install it via pip pip3 install stylecloud." }, { "code": null, "e": 1131, "s": 1077, "text": "Once you installed stylecloud, you have to import it." }, { "code": null, "e": 1149, "s": 1131, "text": "import stylecloud" }, { "code": null, "e": 1515, "s": 1149, "text": "Now to create a basic wordcloud we need to use the .gen_stylecloud() method and add the path of the .txt file and the icon we’re going to use to give form to this wordcloud. On this website, you can find a list of icons that you can use with stylecloud. Just search the icon you want and copy the HTML code of the icon (in this example, I chose an apple as an icon)" }, { "code": null, "e": 1624, "s": 1515, "text": "stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name= \"fas fa-apple-alt\")" }, { "code": null, "e": 1733, "s": 1624, "text": "The result is the wordcloud below (the file is created in the same path where your Python script is located)" }, { "code": null, "e": 1835, "s": 1733, "text": "But we can do even more! We can customize the wordcloud further to obtain a better-looking wordcloud." }, { "code": null, "e": 2019, "s": 1835, "text": "We can control the background color, the color of the words, the name of the output file, and also omit collocations of two words in the wordcloud. To do so, we’ll use the code below." }, { "code": null, "e": 2314, "s": 2019, "text": "stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name='fas fa-apple-alt', colors='white', background_color='black', output_name='apple.png', collocations=False)" }, { "code": null, "e": 2530, "s": 2314, "text": "We can even write HTML code of colors instead of using standard colors like “white.” On this website, you can pick any color you want and get its HTML code that you can include in the colors parameter of stylecloud." }, { "code": null, "e": 2719, "s": 2530, "text": "Stylecloud has by default a list of stopwords in the English language, but in case you want to remove or add new stopwords you have to include a new list in the custom_stopwords parameter." }, { "code": null, "e": 2924, "s": 2719, "text": "To customize a list of stopwords, we have to use the stop_words library. To do so, first, install it (pip install stop_words) Then we use get_stop_words to get a list of stop words in a specific language." }, { "code": null, "e": 3000, "s": 2924, "text": "from stop_words import get_stop_wordsstop_words = get_stop_words('english')" }, { "code": null, "e": 3109, "s": 3000, "text": "Once you defined the list, you can add or remove elements with the .append and .remove methods respectively." }, { "code": null, "e": 3184, "s": 3109, "text": "stop_words.append('my_new_stop_word')stop_words.remove('my_new_stop_word')" }, { "code": null, "e": 3324, "s": 3184, "text": "Now, we only have to add the new stop_words list. I'm also going to use a palette instead of colors to give the wordcloud a different look." }, { "code": null, "e": 3700, "s": 3324, "text": "stylecloud.gen_stylecloud(file_path='SJ-Speech.txt', icon_name='fas fa-apple-alt', palette='cartocolors.qualitative.Pastel_3', background_color='black', output_name='apple.png', collocations=False, custom_stopwords=stop_words)" }, { "code": null, "e": 3920, "s": 3700, "text": "On this website, you can find a list of color palettes for Python that you can use with the stylecloud library (as you can see in the code above, the names separated by dots represent the content of the palettes module)" }, { "code": null, "e": 4283, "s": 3920, "text": "There are hundreds of free icons available to use with stylecloud but sometimes we might want to use our own image to give form to the wordcloud we want to create. If that’s the case, we have to use the wordcloud library to make a wordcloud, PIL to upload an image, matplotlib to plot the wordcloud and numpy to use the image uploaded as a mask of our wordcloud." }, { "code": null, "e": 4437, "s": 4283, "text": "First, we install all of the 4 libraries mentioned before. Once we have all of them, we import them and start creating a wordcloud with the desired mask." }, { "code": null, "e": 4941, "s": 4437, "text": "from wordcloud import WordCloud, ImageColorGenerator from PIL import Imageimport matplotlib.pyplot as pltimport numpy as np# create a mask based on the image we wish to includemy_mask = np.array(Image.open('batman-logo.png'))# create a wordcloud wc = WordCloud(background_color='white', mask=my_mask, collocations=False, width=600, height=300, contour_width=3, contour_color='black', stopwords=stop_words)" }, { "code": null, "e": 5219, "s": 4941, "text": "As you can see, the code used is similar to stylecloud with a few variations. We use mask to specify the image we want to use for the wordcloud (in this case, I’m using the batman logo). Also, we included the contour width and color to make the shape of the image more visible." }, { "code": null, "e": 5364, "s": 5219, "text": "Note: Make sure that the image you will use as a mask has a well-defined shape with clear boundaries otherwise the wordcloud will not look good." }, { "code": null, "e": 5450, "s": 5364, "text": "Now we have to read the text file and generate the wordcloud with the following code." }, { "code": null, "e": 5540, "s": 5450, "text": "with open('SJ-Speech.txt', 'r') as txt_file: texto = txt_file.read()wc.generate(texto)" }, { "code": null, "e": 5720, "s": 5540, "text": "In case we want to use the original image’s color, we write the following code (if not the wordcloud will have random colors just like the first apple image shown in this article)" }, { "code": null, "e": 5799, "s": 5720, "text": "image_colors = ImageColorGenerator(my_mask)wc.recolor(color_func=image_colors)" }, { "code": null, "e": 5848, "s": 5799, "text": "Finally to plot the wordcloud we use matplotlib." }, { "code": null, "e": 5969, "s": 5848, "text": "plt.figure(figsize=(20, 10))plt.imshow(wc, interpolation='bilinear')plt.axis('off')wc.to_file('wordcloud.png')plt.show()" }, { "code": null, "e": 6071, "s": 5969, "text": "I also remove the axis to only have the wordcloud in the plot and save the wordcloud withwc.to_file()" }, { "code": null, "e": 6213, "s": 6071, "text": "That’s it! Now you’re ready to make your own wordcloud with Python! I created some wordclouds using Simpsons characters in the article below." }, { "code": null, "e": 6236, "s": 6213, "text": "towardsdatascience.com" }, { "code": null, "e": 6284, "s": 6236, "text": "Here is a list of books I read to learn Python." }, { "code": null, "e": 6306, "s": 6284, "text": "betterprogramming.pub" }, { "code": null, "e": 6424, "s": 6306, "text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
How to get single array from multiple arrays in JavaScript
Suppose, we have an array of arrays like this − const arr = [ [ {"c": 1},{"d": 2} ], [ {"c": 2},{"d": 3} ] ]; We are required to write a JavaScript function that takes in one such array as the first and the only argument. The function should then convert the array (creating a new array) into array of objects removing nested arrays. Therefore, the final output should look like this − const output = [{"c": 1},{"d": 2},{"c": 2},{"d": 3}]; const arr = [ [ {"c": 1},{"d": 2} ], [ {"c": 2},{"d": 3} ] ]; const simplifyArray = (arr = []) => { const res = []; arr.forEach(element => { element.forEach(el => { res.push(el); }); }); return res; }; console.log(simplifyArray(arr)); And the output in the console will be − [ { c: 1 }, { d: 2 }, { c: 2 }, { d: 3 } ]
[ { "code": null, "e": 1110, "s": 1062, "text": "Suppose, we have an array of arrays like this −" }, { "code": null, "e": 1178, "s": 1110, "text": "const arr = [\n [ {\"c\": 1},{\"d\": 2} ],\n [ {\"c\": 2},{\"d\": 3} ]\n];" }, { "code": null, "e": 1290, "s": 1178, "text": "We are required to write a JavaScript function that takes in one such array as the first and the only argument." }, { "code": null, "e": 1402, "s": 1290, "text": "The function should then convert the array (creating a new array) into array of objects removing nested arrays." }, { "code": null, "e": 1454, "s": 1402, "text": "Therefore, the final output should look like this −" }, { "code": null, "e": 1508, "s": 1454, "text": "const output = [{\"c\": 1},{\"d\": 2},{\"c\": 2},{\"d\": 3}];" }, { "code": null, "e": 1782, "s": 1508, "text": "const arr = [\n [ {\"c\": 1},{\"d\": 2} ],\n [ {\"c\": 2},{\"d\": 3} ]\n];\nconst simplifyArray = (arr = []) => {\n const res = [];\n arr.forEach(element => {\n element.forEach(el => {\n res.push(el);\n });\n });\n return res;\n};\nconsole.log(simplifyArray(arr));" }, { "code": null, "e": 1822, "s": 1782, "text": "And the output in the console will be −" }, { "code": null, "e": 1865, "s": 1822, "text": "[ { c: 1 }, { d: 2 }, { c: 2 }, { d: 3 } ]" } ]
C++ Input / Output | Practice | GeeksforGeeks
Given two integers A and B. Your task is to return their product. Example 1: Input: A = 1, B = 2 Output: 2 Explanation: Multiplication of 1 and 2 is 2. Example 2: Input: A = 8, B = 7 Output: 56 Explanation: Multiplication of 8 and 7 is 56. Your Task: You don't need to read input or print anything. Your task is to complete the function multiplication() which takes two integers a and b and returns their product. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 0<=a,b<=10000 0 aniketkalawat883 weeks ago class Solution{ public: int multiplication(int A, int B){ // code here int c = A * B; return c; }}; 0 aniketkalawat88 This comment was deleted. +1 nallalasumanthreddy3 weeks ago UPVOTE PYTHON SOLUTION class Solution: def multiplication (ob,A,B): # code here return A*B 0 attemptceremony95102 months ago // { Driver Code Starts#include<bits/stdc++.h> using namespace std; // } Driver Code Endsclass Solution{ public: int multiplication(int A, int B){ int mul; mul=A*B; return mul; }}; // { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.multiplication(A,B) << endl; } return 0; } // } Driver Code Ends 0 attemptceremony95102 months ago // { Driver Code Starts#include<bits/stdc++.h> using namespace std; // } Driver Code Endsclass Solution{ public: int multiplication(int A, int B){ int mul; mul=A*B; return mul; }}; // { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.multiplication(A,B) << endl; } return 0; } // } Driver Code Ends 0 sakshamraj2292 months ago class Solution { public: int sumOfMatrix(int N, int M, vector<vector<int>> Grid) { int sum=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ sum+=Grid[i][j]; } } return sum; } }; 0 samkapadia373 months ago your compiler is not working Properly 0 b5210143 months ago #include<stdio.h> int main() { int a= -10,b= 800, c; c=a*b; printf("a x b = %d", c); return 0; } 0 aanjalitewari20023 months ago #include<iostream> #include<conio.h> using namespace std; int main() { int a,b,c; cout<<"\n enter the value of a and b; cin>>>>b; c=a*b; cout<<"multiplication of"<<a<<"and"<<b<<"is"<<c<<endl; return 0; 0 umerkhayam36433 months ago . 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": 304, "s": 238, "text": "Given two integers A and B. Your task is to return their product." }, { "code": null, "e": 317, "s": 306, "text": "Example 1:" }, { "code": null, "e": 393, "s": 317, "text": "Input:\nA = 1, B = 2\nOutput:\n2\nExplanation:\nMultiplication of 1 and 2 is 2.\n" }, { "code": null, "e": 406, "s": 395, "text": "Example 2:" }, { "code": null, "e": 483, "s": 406, "text": "Input:\nA = 8, B = 7\nOutput:\n56\nExplanation:\nMultiplication of 8 and 7 is 56." }, { "code": null, "e": 496, "s": 485, "text": "Your Task:" }, { "code": null, "e": 659, "s": 496, "text": "You don't need to read input or print anything. Your task is to complete the function multiplication() which takes two integers a and b and returns their product." }, { "code": null, "e": 723, "s": 661, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 752, "s": 725, "text": "Constraints:\n0<=a,b<=10000" }, { "code": null, "e": 754, "s": 752, "text": "0" }, { "code": null, "e": 781, "s": 754, "text": "aniketkalawat883 weeks ago" }, { "code": null, "e": 910, "s": 781, "text": "class Solution{ public: int multiplication(int A, int B){ // code here int c = A * B; return c; }};" }, { "code": null, "e": 912, "s": 910, "text": "0" }, { "code": null, "e": 928, "s": 912, "text": "aniketkalawat88" }, { "code": null, "e": 954, "s": 928, "text": "This comment was deleted." }, { "code": null, "e": 957, "s": 954, "text": "+1" }, { "code": null, "e": 988, "s": 957, "text": "nallalasumanthreddy3 weeks ago" }, { "code": null, "e": 1011, "s": 988, "text": "UPVOTE PYTHON SOLUTION" }, { "code": null, "e": 1100, "s": 1011, "text": "class Solution:\n def multiplication (ob,A,B):\n # code here \n return A*B" }, { "code": null, "e": 1102, "s": 1100, "text": "0" }, { "code": null, "e": 1134, "s": 1102, "text": "attemptceremony95102 months ago" }, { "code": null, "e": 1202, "s": 1134, "text": "// { Driver Code Starts#include<bits/stdc++.h> using namespace std;" }, { "code": null, "e": 1327, "s": 1202, "text": "// } Driver Code Endsclass Solution{ public: int multiplication(int A, int B){ int mul; mul=A*B; return mul; }};" }, { "code": null, "e": 1544, "s": 1327, "text": "// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.multiplication(A,B) << endl; } return 0; } // } Driver Code Ends" }, { "code": null, "e": 1546, "s": 1544, "text": "0" }, { "code": null, "e": 1578, "s": 1546, "text": "attemptceremony95102 months ago" }, { "code": null, "e": 1646, "s": 1578, "text": "// { Driver Code Starts#include<bits/stdc++.h> using namespace std;" }, { "code": null, "e": 1771, "s": 1646, "text": "// } Driver Code Endsclass Solution{ public: int multiplication(int A, int B){ int mul; mul=A*B; return mul; }};" }, { "code": null, "e": 1988, "s": 1771, "text": "// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.multiplication(A,B) << endl; } return 0; } // } Driver Code Ends" }, { "code": null, "e": 1990, "s": 1988, "text": "0" }, { "code": null, "e": 2016, "s": 1990, "text": "sakshamraj2292 months ago" }, { "code": null, "e": 2274, "s": 2016, "text": "class Solution {\n public:\n int sumOfMatrix(int N, int M, vector<vector<int>> Grid) {\n int sum=0;\n for(int i=0;i<N;i++){\n for(int j=0;j<M;j++){\n sum+=Grid[i][j];\n }\n }\n return sum;\n }\n};" }, { "code": null, "e": 2276, "s": 2274, "text": "0" }, { "code": null, "e": 2301, "s": 2276, "text": "samkapadia373 months ago" }, { "code": null, "e": 2340, "s": 2301, "text": "your compiler is not working Properly " }, { "code": null, "e": 2342, "s": 2340, "text": "0" }, { "code": null, "e": 2362, "s": 2342, "text": "b5210143 months ago" }, { "code": null, "e": 2380, "s": 2362, "text": "#include<stdio.h>" }, { "code": null, "e": 2391, "s": 2380, "text": "int main()" }, { "code": null, "e": 2393, "s": 2391, "text": "{" }, { "code": null, "e": 2415, "s": 2393, "text": "int a= -10,b= 800, c;" }, { "code": null, "e": 2422, "s": 2415, "text": "c=a*b;" }, { "code": null, "e": 2447, "s": 2422, "text": "printf(\"a x b = %d\", c);" }, { "code": null, "e": 2457, "s": 2447, "text": "return 0;" }, { "code": null, "e": 2459, "s": 2457, "text": "}" }, { "code": null, "e": 2466, "s": 2464, "text": "0" }, { "code": null, "e": 2496, "s": 2466, "text": "aanjalitewari20023 months ago" }, { "code": null, "e": 2711, "s": 2496, "text": "#include<iostream>\n#include<conio.h>\nusing namespace std;\nint main()\n{\n int a,b,c;\n cout<<\"\\n enter the value of a and b;\n cin>>>>b;\n c=a*b;\n cout<<\"multiplication of\"<<a<<\"and\"<<b<<\"is\"<<c<<endl;\n return 0;" }, { "code": null, "e": 2713, "s": 2711, "text": "0" }, { "code": null, "e": 2740, "s": 2713, "text": "umerkhayam36433 months ago" }, { "code": null, "e": 2742, "s": 2740, "text": "." }, { "code": null, "e": 2888, "s": 2742, "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": 2924, "s": 2888, "text": " Login to access your submissions. " }, { "code": null, "e": 2934, "s": 2924, "text": "\nProblem\n" }, { "code": null, "e": 2944, "s": 2934, "text": "\nContest\n" }, { "code": null, "e": 3007, "s": 2944, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3155, "s": 3007, "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": 3363, "s": 3155, "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": 3469, "s": 3363, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Fabric.js | Rect borderColor Property - GeeksforGeeks
20 May, 2020 In this article, we are going to see how to change the border color of the canvas rectangle using FabricJS. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width. Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and change the border color of the canvas rectangle using borderColor property and render the Rect on the Canvas as given in the example below. Syntax: fabric.Rect({ width: number, height: number, borderColor: string }); Parameters: This function accepts three parameters as mentioned above and described below: width: It specifies the width of rectangle. height: It specifies the height of rectangle. borderColor: It specifies the border color. Example: This example uses FabricJS to change the border color of the canvas rectangle as given below. Note that you have to click on the rectangle to see the border. <!DOCTYPE html> <html> <head> <title> Fabric.js | Rect borderColor Property </title> <!-- Adding the FabricJS library --> <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script> </head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Initiate a Rect instance var rectangle = new fabric.Rect({ width: 200, height: 100, fill: '', stroke: 'green', strokeWidth: 3, borderColor: 'red' }); // Render the Rect in canvas canvas.add(rectangle); canvas.centerObject(rectangle); </script> </body> </html> Output: Fabric.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24970, "s": 24942, "text": "\n20 May, 2020" }, { "code": null, "e": 25297, "s": 24970, "text": "In this article, we are going to see how to change the border color of the canvas rectangle using FabricJS. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width." }, { "code": null, "e": 25720, "s": 25297, "text": "Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and change the border color of the canvas rectangle using borderColor property and render the Rect on the Canvas as given in the example below." }, { "code": null, "e": 25728, "s": 25720, "text": "Syntax:" }, { "code": null, "e": 25810, "s": 25728, "text": "fabric.Rect({\n width: number,\n height: number,\n borderColor: string\n}); " }, { "code": null, "e": 25901, "s": 25810, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 25945, "s": 25901, "text": "width: It specifies the width of rectangle." }, { "code": null, "e": 25991, "s": 25945, "text": "height: It specifies the height of rectangle." }, { "code": null, "e": 26035, "s": 25991, "text": "borderColor: It specifies the border color." }, { "code": null, "e": 26202, "s": 26035, "text": "Example: This example uses FabricJS to change the border color of the canvas rectangle as given below. Note that you have to click on the rectangle to see the border." }, { "code": "<!DOCTYPE html> <html> <head> <title> Fabric.js | Rect borderColor Property </title> <!-- Adding the FabricJS library --> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script> </head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Initiate a Rect instance var rectangle = new fabric.Rect({ width: 200, height: 100, fill: '', stroke: 'green', strokeWidth: 3, borderColor: 'red' }); // Render the Rect in canvas canvas.add(rectangle); canvas.centerObject(rectangle); </script> </body> </html>", "e": 27074, "s": 26202, "text": null }, { "code": null, "e": 27082, "s": 27074, "text": "Output:" }, { "code": null, "e": 27092, "s": 27082, "text": "Fabric.js" }, { "code": null, "e": 27103, "s": 27092, "text": "JavaScript" }, { "code": null, "e": 27120, "s": 27103, "text": "Web Technologies" }, { "code": null, "e": 27218, "s": 27120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27227, "s": 27218, "text": "Comments" }, { "code": null, "e": 27240, "s": 27227, "text": "Old Comments" }, { "code": null, "e": 27285, "s": 27240, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27346, "s": 27285, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27418, "s": 27346, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27464, "s": 27418, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27505, "s": 27464, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27547, "s": 27505, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27590, "s": 27547, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27652, "s": 27590, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27702, "s": 27652, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
AngularJS | Events - GeeksforGeeks
22 Apr, 2020 Events in AngularJS can be added using the Directives mentioned below: ng-mousemove: Movement of mouse leads to the execution of event. ng-mouseup: Movement of mouse upwards leads to the execution of event. ng-mousedown: Movement of mouse downwards leads to the execution of event. ng-mouseenter: Click of the mouse button leads to the execution of event. ng-mouseover: Hovering of the mouse leads to the execution of event. ng-cut: Cut operation leads to the execution of the event. ng-copy: Copy operation leads to the execution of the event. ng-keypress: Press of key leads to the execution of the event. ng-keyup: Press of upward arrow key leads to the execution of the event. ng-keydown: Press of downward arrow key leads to the execution of the event. ng-click: Single click leads to the execution of the event. ng-dblclick: Double click leads to the execution of the event. Example 1: Showing action on the occurrence of any Mouse Movement Event. This includes events of dragging the mouse to cause movement of the cursor on the screen. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <p> Move the mouse over GeeksforGeeks to increase the Total Count. </p> <div ng-app="App1" ng-controller="Ctrl1"> <h1 ng-mousemove="count = count + 1"> Geeks for Geeks </h1> <h2>Total Count:</h2> <h2>{{ count }}</h2> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.count = 0; }); </script></body> </html> Output: Example 2: This example showing the $event obj for calling the function on Mouse Movement Event. Here, $event object enables the occurrence of a mouse movement event. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <p> Mouse over Geeks for Geeks to display the value of clientX and clientY. </p> <div ng-app="App1" ng-controller="Ctrl1"> <h1 ng-mousemove="myFunc($event)"> Geeks for Geeks </h1> <h4>Coordinates: {{x + ', ' + y}}</h4> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.myFunc = function (gfg) { $scope.x = gfg.clientX; $scope.y = gfg.clientY; } }); </script></body> </html> Output: Example 3: This example shows the action being performed forOn Click Event. Here, the click of the mouse button leads to the performance of some action. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <p> Click on GeeksforGeeks to increase the Total Count. </p> <div ng-app="App1" ng-controller="Ctrl1"> <button ng-click="count = count + 1"> Geeks for Geeks </button> <h2>Total Count:</h2> <h2>{{ count }}</h2> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.count = 0; }); </script></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. AngularJS-Basics HTML-Misc Picked AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular File Upload Auth Guards in Angular 9/10/11 Angular | keyup event What is AOT and JIT Compiler in Angular ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 28271, "s": 28243, "text": "\n22 Apr, 2020" }, { "code": null, "e": 28342, "s": 28271, "text": "Events in AngularJS can be added using the Directives mentioned below:" }, { "code": null, "e": 28407, "s": 28342, "text": "ng-mousemove: Movement of mouse leads to the execution of event." }, { "code": null, "e": 28478, "s": 28407, "text": "ng-mouseup: Movement of mouse upwards leads to the execution of event." }, { "code": null, "e": 28553, "s": 28478, "text": "ng-mousedown: Movement of mouse downwards leads to the execution of event." }, { "code": null, "e": 28627, "s": 28553, "text": "ng-mouseenter: Click of the mouse button leads to the execution of event." }, { "code": null, "e": 28696, "s": 28627, "text": "ng-mouseover: Hovering of the mouse leads to the execution of event." }, { "code": null, "e": 28755, "s": 28696, "text": "ng-cut: Cut operation leads to the execution of the event." }, { "code": null, "e": 28816, "s": 28755, "text": "ng-copy: Copy operation leads to the execution of the event." }, { "code": null, "e": 28879, "s": 28816, "text": "ng-keypress: Press of key leads to the execution of the event." }, { "code": null, "e": 28952, "s": 28879, "text": "ng-keyup: Press of upward arrow key leads to the execution of the event." }, { "code": null, "e": 29029, "s": 28952, "text": "ng-keydown: Press of downward arrow key leads to the execution of the event." }, { "code": null, "e": 29089, "s": 29029, "text": "ng-click: Single click leads to the execution of the event." }, { "code": null, "e": 29152, "s": 29089, "text": "ng-dblclick: Double click leads to the execution of the event." }, { "code": null, "e": 29315, "s": 29152, "text": "Example 1: Showing action on the occurrence of any Mouse Movement Event. This includes events of dragging the mouse to cause movement of the cursor on the screen." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <p> Move the mouse over GeeksforGeeks to increase the Total Count. </p> <div ng-app=\"App1\" ng-controller=\"Ctrl1\"> <h1 ng-mousemove=\"count = count + 1\"> Geeks for Geeks </h1> <h2>Total Count:</h2> <h2>{{ count }}</h2> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.count = 0; }); </script></body> </html>", "e": 29934, "s": 29315, "text": null }, { "code": null, "e": 29942, "s": 29934, "text": "Output:" }, { "code": null, "e": 30109, "s": 29942, "text": "Example 2: This example showing the $event obj for calling the function on Mouse Movement Event. Here, $event object enables the occurrence of a mouse movement event." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <p> Mouse over Geeks for Geeks to display the value of clientX and clientY. </p> <div ng-app=\"App1\" ng-controller=\"Ctrl1\"> <h1 ng-mousemove=\"myFunc($event)\"> Geeks for Geeks </h1> <h4>Coordinates: {{x + ', ' + y}}</h4> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.myFunc = function (gfg) { $scope.x = gfg.clientX; $scope.y = gfg.clientY; } }); </script></body> </html>", "e": 30827, "s": 30109, "text": null }, { "code": null, "e": 30835, "s": 30827, "text": "Output:" }, { "code": null, "e": 30988, "s": 30835, "text": "Example 3: This example shows the action being performed forOn Click Event. Here, the click of the mouse button leads to the performance of some action." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <p> Click on GeeksforGeeks to increase the Total Count. </p> <div ng-app=\"App1\" ng-controller=\"Ctrl1\"> <button ng-click=\"count = count + 1\"> Geeks for Geeks </button> <h2>Total Count:</h2> <h2>{{ count }}</h2> </div> <script> var app = angular.module('App1', []); app.controller('Ctrl1', function ($scope) { $scope.count = 0; }); </script></body> </html>", "e": 31608, "s": 30988, "text": null }, { "code": null, "e": 31616, "s": 31608, "text": "Output:" }, { "code": null, "e": 31753, "s": 31616, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31770, "s": 31753, "text": "AngularJS-Basics" }, { "code": null, "e": 31780, "s": 31770, "text": "HTML-Misc" }, { "code": null, "e": 31787, "s": 31780, "text": "Picked" }, { "code": null, "e": 31797, "s": 31787, "text": "AngularJS" }, { "code": null, "e": 31802, "s": 31797, "text": "HTML" }, { "code": null, "e": 31819, "s": 31802, "text": "Web Technologies" }, { "code": null, "e": 31824, "s": 31819, "text": "HTML" }, { "code": null, "e": 31922, "s": 31824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31966, "s": 31922, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31986, "s": 31966, "text": "Angular File Upload" }, { "code": null, "e": 32017, "s": 31986, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 32039, "s": 32017, "text": "Angular | keyup event" }, { "code": null, "e": 32081, "s": 32039, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 32131, "s": 32081, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32193, "s": 32131, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32241, "s": 32193, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32301, "s": 32241, "text": "How to set the default value for an HTML <select> element ?" } ]
Hibernate Restrictions Example | Restrictions in Hibernate
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 tutorials, we are going to learn about Hibernate Restrictions with Example. In the previous tutorial we had a detailed discussion about Hibernate Projections and how to use them. Coming to the Hibernate Restrictions, if we want to apply a condition in criteria query, then we can use Restrictions. If we want to apply a condition to criteria query, we need Criterion object. Criterion is an interface, it is an object-oriented representation of a query criterion that may be used as a restriction in a Criteria query. We can obtain the Criterion type objects, by calling static methods of Restrictions class. Restrictions is a normal Java class, which doesn’t implement any Criterion interface. Criterion interface and Restrictions class, both are coming from org.hibernate.criterion package. If we want to read employees, who are working in department 101, then a condition can be added like the following: Criteria criteria = session.createCriteria(Employee.class); Criterion criterion = Restrictions.eq("departmentId", 101); criteria.add(criterion); On the above example, we are trying to get the employees who are working in department 101. This is exactly like select * from emp where deptno=101 in SQL. If we want to add, 2 or more conditions using Hibernate Restrictions, both conditions are added like below: Criteria criteria = session.createCriteria(Employee.class); Criterion criterion = Restrictions.eq("departmentId", 101); Criterion criterion2 = Restrictions.gt("salary", 4000); Criterion criterion3 = Restrictions.and(criterion,criterion2); criteria.add(criterion3); In the above example, we are trying to get the employees information, who are working in department id = 101 and salary > 4000. This is exactly like select * from emp where deptid=101 and salary > 4000 in SQL. Restrictions class has and() method to apply the ‘and condition’ in a query. We can add variable number of conditions in and() method like and(criterion,criterion-2,criterion-3,.....,criterion-n); between(String propertyName, Object lo, Object hi) Apply a “between” constraint to the named property eq(String propertyName, Object value) Apply an “equal” constraint to the named property ge(String propertyName, Object value) Apply a “greater than or equal” constraint to the named property gt(String propertyName, Object value) Apply a “greater than” constraint to the named property ilike(String propertyName, Object value) A case-insensitive “like”, similar to Postgres ilike operator in(String propertyName, Object[] values) Apply an “in” constraint to the named property le(String propertyName, Object value) Apply a “less than or equal” constraint to the named property like(String propertyName, Object value) Apply a “like” constraint to the named property lt(String propertyName, Object value) Apply a “less than” constraint to the named property ne(String propertyName, Object value) Apply a “not equal” constraint to the named property or(Criterion lhs, Criterion rhs) Return the disjuction of two expressions Employee.java package com.otp.hibernate.pojo; public class Employee { private int employeeId; private String employeeName; private int departmentId; private int salary; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", departmentId=" + departmentId + ", salary=" + salary + "]"; } } employee.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.otp.hibernate.pojo.Employee" table="employee" schema="onlinetutorialspoint"> <id name="employeeId" column="id"> <generator class="increment" /> </id> <property name="employeeName" column="ename" /> <property name="departmentId" column="deptNo" /> <property name="salary" column="salary" /> </class> </hibernate-mapping> Main.java import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Projection; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import com.otp.hibernate.pojo.Employee; public class Main { public static void main(String[] args) { Configuration configuration = new Configuration() .configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder .build()); Session session = factory.openSession(); System.out.println("Reading Complete Entity with Condition"); Criteria criteria = session.createCriteria(Employee.class); Criterion criterion = Restrictions.eq("departmentId", 101); Criterion criterion2 = Restrictions.gt("salary", 4000); Criterion criterion3 = Restrictions.and(criterion,criterion2); criteria.add(criterion3); List list = criteria.list(); Iterator it = list.iterator(); while (it.hasNext()) { Employee emp = (Employee) it.next(); System.out.println("Employee : " + emp.toString()); } session.close(); } } Output : Reading Complete Entity with Condition Employee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000] Employee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000] Complete example is available for download. Happy Learning 🙂 Hibernate-Restrictions-Example File size: 13 KB Downloads: 725 Hibernate Projection with Example Hibernate Criteria API with Example Hibernate Filters Example Annotation Calling Stored Procedures in Hibernate Hibernate Query Language (HQL) Select Operation @Formula Annotation in Hibernate Example Dependency Injection (IoC) in spring with Example Hibernate Right Join Example BeanFactory Example in Spring hibernate update query example hbm2ddl.auto Example in Hibernate XML Config Hibernate sql dialect list What is Association in Java Hibernate Native SQL Query Example Hibernate groupby criteria HQL query Example Hibernate Projection with Example Hibernate Criteria API with Example Hibernate Filters Example Annotation Calling Stored Procedures in Hibernate Hibernate Query Language (HQL) Select Operation @Formula Annotation in Hibernate Example Dependency Injection (IoC) in spring with Example Hibernate Right Join Example BeanFactory Example in Spring hibernate update query example hbm2ddl.auto Example in Hibernate XML Config Hibernate sql dialect list What is Association in Java Hibernate Native SQL Query Example Hibernate groupby criteria HQL query Example Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "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": 704, "s": 398, "text": "In this tutorials, we are going to learn about Hibernate Restrictions with Example. In the previous tutorial we had a detailed discussion about Hibernate Projections and how to use them. Coming to the Hibernate Restrictions, if we want to apply a condition in criteria query, then we can use Restrictions." }, { "code": null, "e": 781, "s": 704, "text": "If we want to apply a condition to criteria query, we need Criterion object." }, { "code": null, "e": 924, "s": 781, "text": "Criterion is an interface, it is an object-oriented representation of a query criterion that may be used as a restriction in a Criteria query." }, { "code": null, "e": 1015, "s": 924, "text": "We can obtain the Criterion type objects, by calling static methods of Restrictions class." }, { "code": null, "e": 1101, "s": 1015, "text": "Restrictions is a normal Java class, which doesn’t implement any Criterion interface." }, { "code": null, "e": 1199, "s": 1101, "text": "Criterion interface and Restrictions class, both are coming from org.hibernate.criterion package." }, { "code": null, "e": 1314, "s": 1199, "text": "If we want to read employees, who are working in department 101, then a condition can be added like the following:" }, { "code": null, "e": 1459, "s": 1314, "text": "Criteria criteria = session.createCriteria(Employee.class);\nCriterion criterion = Restrictions.eq(\"departmentId\", 101);\ncriteria.add(criterion);" }, { "code": null, "e": 1615, "s": 1459, "text": "On the above example, we are trying to get the employees who are working in department 101. This is exactly like select * from emp where deptno=101 in SQL." }, { "code": null, "e": 1723, "s": 1615, "text": "If we want to add, 2 or more conditions using Hibernate Restrictions, both conditions are added like below:" }, { "code": null, "e": 1988, "s": 1723, "text": "Criteria criteria = session.createCriteria(Employee.class);\nCriterion criterion = Restrictions.eq(\"departmentId\", 101);\nCriterion criterion2 = Restrictions.gt(\"salary\", 4000);\nCriterion criterion3 = Restrictions.and(criterion,criterion2);\ncriteria.add(criterion3);" }, { "code": null, "e": 2395, "s": 1988, "text": "In the above example, we are trying to get the employees information, who are working in department id = 101 and salary > 4000. This is exactly like select * from emp where deptid=101 and salary > 4000 in SQL. Restrictions class has and() method to apply the ‘and condition’ in a query. We can add variable number of conditions in and() method like and(criterion,criterion-2,criterion-3,.....,criterion-n);" }, { "code": null, "e": 2497, "s": 2395, "text": "between(String propertyName, Object lo, Object hi)\nApply a “between” constraint to the named property" }, { "code": null, "e": 2585, "s": 2497, "text": "eq(String propertyName, Object value)\nApply an “equal” constraint to the named property" }, { "code": null, "e": 2688, "s": 2585, "text": "ge(String propertyName, Object value)\nApply a “greater than or equal” constraint to the named property" }, { "code": null, "e": 2782, "s": 2688, "text": "gt(String propertyName, Object value)\nApply a “greater than” constraint to the named property" }, { "code": null, "e": 2885, "s": 2782, "text": "ilike(String propertyName, Object value)\nA case-insensitive “like”, similar to Postgres ilike operator" }, { "code": null, "e": 2973, "s": 2885, "text": "in(String propertyName, Object[] values)\nApply an “in” constraint to the named property" }, { "code": null, "e": 3073, "s": 2973, "text": "le(String propertyName, Object value)\nApply a “less than or equal” constraint to the named property" }, { "code": null, "e": 3161, "s": 3073, "text": "like(String propertyName, Object value)\nApply a “like” constraint to the named property" }, { "code": null, "e": 3252, "s": 3161, "text": "lt(String propertyName, Object value)\nApply a “less than” constraint to the named property" }, { "code": null, "e": 3343, "s": 3252, "text": "ne(String propertyName, Object value)\nApply a “not equal” constraint to the named property" }, { "code": null, "e": 3417, "s": 3343, "text": "or(Criterion lhs, Criterion rhs)\nReturn the disjuction of two expressions" }, { "code": null, "e": 3431, "s": 3417, "text": "Employee.java" }, { "code": null, "e": 4488, "s": 3431, "text": "package com.otp.hibernate.pojo;\n\npublic class Employee {\n private int employeeId;\n private String employeeName;\n private int departmentId;\n private int salary;\n\n public int getEmployeeId() {\n return employeeId;\n }\n\n public void setEmployeeId(int employeeId) {\n this.employeeId = employeeId;\n }\n\n public String getEmployeeName() {\n return employeeName;\n }\n\n public void setEmployeeName(String employeeName) {\n this.employeeName = employeeName;\n }\n\n public int getDepartmentId() {\n return departmentId;\n }\n\n public void setDepartmentId(int departmentId) {\n this.departmentId = departmentId;\n }\n\n public int getSalary() {\n return salary;\n }\n\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n @Override\n public String toString() {\n return \"Employee [employeeId=\" + employeeId + \", employeeName=\"\n + employeeName + \", departmentId=\" + departmentId + \", salary=\"\n + salary + \"]\";\n }\n}\n" }, { "code": null, "e": 4505, "s": 4488, "text": "employee.hbm.xml" }, { "code": null, "e": 5103, "s": 4505, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.otp.hibernate.pojo.Employee\" table=\"employee\"\nschema=\"onlinetutorialspoint\">\n <id name=\"employeeId\" column=\"id\">\n <generator class=\"increment\" />\n </id>\n <property name=\"employeeName\" column=\"ename\" />\n <property name=\"departmentId\" column=\"deptNo\" />\n <property name=\"salary\" column=\"salary\" />\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 5113, "s": 5103, "text": "Main.java" }, { "code": null, "e": 6759, "s": 5113, "text": "import java.util.Iterator;\nimport java.util.List;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.criterion.Criterion;\nimport org.hibernate.criterion.Projection;\nimport org.hibernate.criterion.ProjectionList;\nimport org.hibernate.criterion.Projections;\nimport org.hibernate.criterion.Restrictions;\n\nimport com.otp.hibernate.pojo.Employee;\n\npublic class Main {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration()\n .configure(\"hibernate.cfg.xml\");\n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()\n .applySettings(configuration.getProperties());\n SessionFactory factory = configuration.buildSessionFactory(builder\n .build());\n\n Session session = factory.openSession();\n\n System.out.println(\"Reading Complete Entity with Condition\");\n\n Criteria criteria = session.createCriteria(Employee.class);\n Criterion criterion = Restrictions.eq(\"departmentId\", 101);\n Criterion criterion2 = Restrictions.gt(\"salary\", 4000);\n Criterion criterion3 = Restrictions.and(criterion,criterion2);\n\n criteria.add(criterion3);\n \n List list = criteria.list();\n Iterator it = list.iterator();\n\n while (it.hasNext()) {\n Employee emp = (Employee) it.next();\n System.out.println(\"Employee : \" + emp.toString());\n }\n\n session.close();\n }\n\n}" }, { "code": null, "e": 6768, "s": 6759, "text": "Output :" }, { "code": null, "e": 6983, "s": 6768, "text": "Reading Complete Entity with Condition\nEmployee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000]\nEmployee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000]" }, { "code": null, "e": 7027, "s": 6983, "text": "Complete example is available for download." }, { "code": null, "e": 7044, "s": 7027, "text": "Happy Learning 🙂" }, { "code": null, "e": 7111, "s": 7044, "text": "\n\nHibernate-Restrictions-Example\n\nFile size: 13 KB\nDownloads: 725\n" }, { "code": null, "e": 7668, "s": 7111, "text": "\nHibernate Projection with Example\nHibernate Criteria API with Example\nHibernate Filters Example Annotation\nCalling Stored Procedures in Hibernate\nHibernate Query Language (HQL) Select Operation\n@Formula Annotation in Hibernate Example\nDependency Injection (IoC) in spring with Example\nHibernate Right Join Example\nBeanFactory Example in Spring\nhibernate update query example\nhbm2ddl.auto Example in Hibernate XML Config\nHibernate sql dialect list\nWhat is Association in Java\nHibernate Native SQL Query Example\nHibernate groupby criteria HQL query Example\n" }, { "code": null, "e": 7702, "s": 7668, "text": "Hibernate Projection with Example" }, { "code": null, "e": 7738, "s": 7702, "text": "Hibernate Criteria API with Example" }, { "code": null, "e": 7775, "s": 7738, "text": "Hibernate Filters Example Annotation" }, { "code": null, "e": 7814, "s": 7775, "text": "Calling Stored Procedures in Hibernate" }, { "code": null, "e": 7862, "s": 7814, "text": "Hibernate Query Language (HQL) Select Operation" }, { "code": null, "e": 7903, "s": 7862, "text": "@Formula Annotation in Hibernate Example" }, { "code": null, "e": 7953, "s": 7903, "text": "Dependency Injection (IoC) in spring with Example" }, { "code": null, "e": 7982, "s": 7953, "text": "Hibernate Right Join Example" }, { "code": null, "e": 8012, "s": 7982, "text": "BeanFactory Example in Spring" }, { "code": null, "e": 8043, "s": 8012, "text": "hibernate update query example" }, { "code": null, "e": 8088, "s": 8043, "text": "hbm2ddl.auto Example in Hibernate XML Config" }, { "code": null, "e": 8115, "s": 8088, "text": "Hibernate sql dialect list" }, { "code": null, "e": 8143, "s": 8115, "text": "What is Association in Java" }, { "code": null, "e": 8178, "s": 8143, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 8223, "s": 8178, "text": "Hibernate groupby criteria HQL query Example" }, { "code": null, "e": 8229, "s": 8227, "text": "Δ" }, { "code": null, "e": 8255, "s": 8229, "text": " Hibernate – Introduction" }, { "code": null, "e": 8279, "s": 8255, "text": " Hibernate – Advantages" }, { "code": null, "e": 8311, "s": 8279, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 8341, "s": 8311, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 8371, "s": 8341, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 8409, "s": 8371, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 8436, "s": 8409, "text": " Hibernate – Object States" }, { "code": null, "e": 8474, "s": 8436, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 8512, "s": 8474, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 8562, "s": 8512, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 8592, "s": 8562, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 8631, "s": 8592, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 8671, "s": 8631, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 8702, "s": 8671, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 8737, "s": 8702, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 8762, "s": 8737, "text": " Hibernate – Named Query" }, { "code": null, "e": 8792, "s": 8762, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 8821, "s": 8792, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 8858, "s": 8821, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 8884, "s": 8858, "text": " Hibernate – Restrictions" }, { "code": null, "e": 8908, "s": 8884, "text": " Hibernate – Projection" }, { "code": null, "e": 8942, "s": 8908, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 8976, "s": 8942, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 9006, "s": 8976, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 9039, "s": 9006, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 9071, "s": 9039, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 9097, "s": 9071, "text": " Hibernate – Update Query" }, { "code": null, "e": 9126, "s": 9097, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 9150, "s": 9126, "text": " Hibernate – Right Join" }, { "code": null, "e": 9173, "s": 9150, "text": " Hibernate – Left Join" }, { "code": null, "e": 9197, "s": 9173, "text": " Hibernate – Pagination" }, { "code": null, "e": 9228, "s": 9197, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 9258, "s": 9228, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 9292, "s": 9258, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 9321, "s": 9292, "text": " Hibernate – Table per Class" }, { "code": null, "e": 9354, "s": 9321, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 9392, "s": 9354, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 9434, "s": 9392, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 9465, "s": 9434, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 9498, "s": 9465, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 9536, "s": 9498, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 9561, "s": 9536, "text": " Hibernate – Interceptor" }, { "code": null, "e": 9607, "s": 9561, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
Java sql.Time setTime() method with example
The setTime() method of the java.util.Time class accepts a variable of long type, representing the number of milliseconds from the epoch time (January 1, 1970 00:00:00.000 GMT) to the required time, and sets the specified time value to the current Time object //Setting time time.setTime(time_value_in_long); Let us create a table with name dispatches in MySQL database using CREATE statement as follows − CREATE TABLE dispatches( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255)); Now, we will insert 5 records in dispatches table using INSERT statements − insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following JDBC example inserts a new record into the dispatches table by passing the required values. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; public class Time_setTime { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Instantiating the Time class Time time = new Time(0L); //Setting time time.setTime(new java.util.Date().getTime()); //Date object Date date = new Date(time.getTime()); //Creating a Prepared Statement String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Watch"); pstmt.setString(2, "Rajan"); pstmt.setDate(3, date); pstmt.setTime(4, time); pstmt.setInt(5, 4000); pstmt.setString(6, "Chennai"); pstmt.execute(); System.out.println("Rows inserted ...."); //Retrieving values Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatches"); while(rs.next()) { System.out.println("Product Name: "+rs.getString("ProductName")); System.out.println("Customer Name: "+rs.getString("CustomerName")); System.out.println("Date Of Dispatch: "+rs.getDate("DispatchDate")); System.out.println("Delivery Time: "+rs.getTime("DeliveryTime")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } } Here, in this program we have instantiated a Time class by passing 0L to its constructor (epoch time:1970-01-01 05:30:00.0) and changed the time to current time using the setTime() method. And we have created a Date object by passing the time value of the Time object created above and inserted these time and date values as values of the new record. Connection established...... Rows inserted .... Product Name: Key-Board Customer Name: Raja Date of Dispatch: 1970-01-19 Delivery Time: 08:51:36 Location: Hyderabad Product Name: Earphones Customer Name: Roja Date of Dispatch: 1970-01-19 Delivery Time: 05:54:28 Location: Vishakhapatnam Product Name: Mouse Customer Name: Puja Date of Dispatch: 1970-01-19 Delivery Time: 04:26:38 Location: Vijayawada Product Name: Mobile Customer Name: Vanaja Date of Dispatch: 1970-01-19 Delivery Time: 04:26:35 Location: Chennai Product Name: Headset Customer Name: Jalaja Date of Dispatch: 1970-01-19 Delivery Time: 05:19:16 Location: Delhi Product Name: Watch Customer Name: Rajan Date Of Dispatch: 2019-03-28 Delivery Time: 13:08:04 Location: Chennai
[ { "code": null, "e": 1322, "s": 1062, "text": "The setTime() method of the java.util.Time class accepts a variable of long type, representing the number of milliseconds from the epoch time (January 1, 1970 00:00:00.000 GMT) to the required time, and sets the specified time value to the current Time object" }, { "code": null, "e": 1371, "s": 1322, "text": "//Setting time\ntime.setTime(time_value_in_long);" }, { "code": null, "e": 1468, "s": 1371, "text": "Let us create a table with name dispatches in MySQL database using CREATE statement as follows −" }, { "code": null, "e": 1637, "s": 1468, "text": "CREATE TABLE dispatches(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255));" }, { "code": null, "e": 1713, "s": 1637, "text": "Now, we will insert 5 records in dispatches table using INSERT statements −" }, { "code": null, "e": 2251, "s": 1713, "text": "insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 2353, "s": 2251, "text": "Following JDBC example inserts a new record into the dispatches table by passing the required values." }, { "code": null, "e": 4224, "s": 2353, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Time;\npublic class Time_setTime {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Instantiating the Time class\n Time time = new Time(0L);\n //Setting time\n time.setTime(new java.util.Date().getTime());\n //Date object\n Date date = new Date(time.getTime());\n //Creating a Prepared Statement\n String query = \"INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Watch\");\n pstmt.setString(2, \"Rajan\");\n pstmt.setDate(3, date);\n pstmt.setTime(4, time);\n pstmt.setInt(5, 4000);\n pstmt.setString(6, \"Chennai\");\n pstmt.execute();\n System.out.println(\"Rows inserted ....\");\n //Retrieving values\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatches\");\n while(rs.next()) {\n System.out.println(\"Product Name: \"+rs.getString(\"ProductName\"));\n System.out.println(\"Customer Name: \"+rs.getString(\"CustomerName\"));\n System.out.println(\"Date Of Dispatch: \"+rs.getDate(\"DispatchDate\"));\n System.out.println(\"Delivery Time: \"+rs.getTime(\"DeliveryTime\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 4413, "s": 4224, "text": "Here, in this program we have instantiated a Time class by passing 0L to its constructor (epoch time:1970-01-01 05:30:00.0) and changed the time to current time using the setTime() method." }, { "code": null, "e": 4575, "s": 4413, "text": "And we have created a Date object by passing the time value of the Time object created above and inserted these time and date values as values of the new record." }, { "code": null, "e": 5315, "s": 4575, "text": "Connection established......\nRows inserted ....\nProduct Name: Key-Board\nCustomer Name: Raja\nDate of Dispatch: 1970-01-19\nDelivery Time: 08:51:36\nLocation: Hyderabad\nProduct Name: Earphones\nCustomer Name: Roja\nDate of Dispatch: 1970-01-19\nDelivery Time: 05:54:28\nLocation: Vishakhapatnam\nProduct Name: Mouse\nCustomer Name: Puja\nDate of Dispatch: 1970-01-19\nDelivery Time: 04:26:38\nLocation: Vijayawada\nProduct Name: Mobile\nCustomer Name: Vanaja\nDate of Dispatch: 1970-01-19\nDelivery Time: 04:26:35\nLocation: Chennai\nProduct Name: Headset\nCustomer Name: Jalaja\nDate of Dispatch: 1970-01-19\nDelivery Time: 05:19:16\nLocation: Delhi\nProduct Name: Watch\nCustomer Name: Rajan\nDate Of Dispatch: 2019-03-28\nDelivery Time: 13:08:04\nLocation: Chennai" } ]
A Data Science Case Study with Python: Mercari Price Prediction | by Geoffrey Lobo | Towards Data Science
The most effective way to learn data science is by solving data science related problems. Reading, listening and taking notes is valuable, but once you work through a problem, concepts solidify from abstractions into tools you feel confident using. Generally a full cycle data science project includes the following stages: Data Gathering & WranglingData Analysis & ModelingCommunication & Deployment Data Gathering & Wrangling Data Analysis & Modeling Communication & Deployment In this case study, we will walk through the Analysis, Modelling and Communication part of the workflow. The general steps involved for solving a data science problem are as follows: Understand the problem and dataData exploration / data cleaningFeature engineering / feature selectionEstablishing a performance metricModel evaluation and selectionModel optimizationDraw conclusions and document work Understand the problem and data Data exploration / data cleaning Feature engineering / feature selection Establishing a performance metric Model evaluation and selection Model optimization Draw conclusions and document work Those of you who are not familiar with the field of Data Science and Python programming language can still follow through the article as it will give an high level overview about how these kind of problems are approached and solved. While some code snippets are included within the blog, for the full code you can check out this Jupyter Notebook. Mercari is Japan’s biggest community powered shopping app where people can sell and buy a variety of brand new and used products of different brands, from sweaters to smartphones. Now Mercari would like to suggest the correct prices to the sellers but this is tough because their sellers are enabled to put just about anything, or any bundle of things on Mercari’s marketplace. So our objective is to build a model that automatically suggests the right product prices to the sellers. We are provided with the following information for each product: train_id — the id of the product name — the title of the product item_condition_id — the condition of the product provided by the sellers category_name — category of the product brand_name — the product’s brand name shipping — 1 if shipping fee is paid by seller and 0 if shipping fee is paid by buyer item_description — the full description of the product price — the price that the product was sold for (This is the target variable that we will predict) This type of problem lies under the category of Supervised Regression Machine Learning: Supervised: We have access to both the features and the target and our goal is to train a model that can learn a mapping between the two. Regression: The target variable, price, is a continuous variable. EDA is an open-ended process where we calculate statistics and make figures to find trends, anomalies, patterns, or relationships within the data. In short, the goal of EDA is to learn what our data can tell us. It generally starts out with a high level overview, then narrows in to specific areas as we find interesting parts of the data. The findings may be interesting in their own right, or they can be used to inform our modeling choices, such as by helping us decide which features to use. In a hurry to get to the machine learning stage, some data scientists either entirely skip the exploratory process or do a very perfunctory job but in reality EDA is one of the most crucial steps in solving a data science related problem. The data set can be downloaded from Kaggle. To validate the result, we only need the ‘train.tsv’ data file. So let’s get started! import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_split We will split the data into train and test sets in the proportion of 80% and 20% respectively. As a common practice, we will conduct EDA on the train data set only. In:data = pd.read_csv('train.tsv', sep='\t')train, test = train_test_split(data, test_size=0.2)print(train.shape, test.shape)Out:(1186028, 8) (296507, 8) There are around 1.18 million data points/rows in the train data and 0.296 million data points/rows in the test data. 8 is the number of columns/features in both the sets. Features and variables mean the same thing here, so they might be used interchangeably within the blog. #this command displays first few rows of the data settrain.head() A common problem when dealing with real-world data is missing values. These can arise for many reasons and have to be either filled in or removed before we train a machine learning model. First, let’s get a sense of how many missing values are in each column. The ‘brand_name’ feature has 42% missing values. Some of the approaches that are usually considered while dealing with missing values are: Remove the records with the missing values.Remove the feature itself if the number of missing values is higher than some threshold, say 50%.Consider ‘missing values’ as another category of that respective feature itself. Remove the records with the missing values. Remove the feature itself if the number of missing values is higher than some threshold, say 50%. Consider ‘missing values’ as another category of that respective feature itself. In this project, we will go forward with the third approach. Now we will start analyzing the features one by one. We will first go through the target variable, Price, and then start analyzing the predictor variables individually and also see how it interacts with the Price variable. Let’s check the distribution of the Price variable and go through some basic statistics. train['price'].plot.hist(bins=50, figsize=(10,5), edgecolor='white',range=[0,500])plt.xlabel('Price', fontsize=15)plt.ylabel('Frequency', fontsize=15)plt.tick_params(labelsize=15)plt.title('Price Distribution - Training Set', fontsize=17)plt.show() train['price'].describe() The distribution of the Price variable aligns with the above statistics, i.e. the distribution is right skewed. The median price of the items is $17. 75% of the items have price below $29. The maximum price of an item from the data is $2009. In:train['shipping'].value_counts(normalize=True)*100Out:0 55.2676671 44.732333 Name: shipping, dtype: float64 The shipping fee for 55.26% of the items are paid by the buyers. Let’s see how the shipping feature relates with price. The median price of the products is $14.0 if seller pays for the shipping while the median price of the products is $20.0 if buyer pays for the shipping. Normally when we buy products online, we need to pay for shipping or delivery of products which are below a certain price. But here the trend is kind of opposite since the median price of items for which the seller pays the shipping fees is lower than the median price of the items for which the buyer pays the shipping fees. The ‘item_condition_id’ has five unique values ranging from 1 to 5. Lower the number, better the condition of the item. In:train['item_condition_id'].value_counts(normalize=True, sort=False)*100Out:1 43.194511 2 25.323264 3 29.166934 4 2.153153 5 0.162138 Name: item_condition_id, dtype: float64 43% of the items have item condition ID as 1 while only 0.16% of the items have item condition ID has 5. Let’s see how this feature relates with Price. For comparing and visualizing the relation between a categorical variable and a numerical variable, Box-Plots are very helpful. The code below is used for plotting Box-Plots. #for easier visualization, we are considering the prices from range of 0-100price_100 = train[train['price']<100]fig, ax = plt.subplots(figsize=(20,7.5))sns.boxplot(x='item_condition_id', y='price', data=price_100, ax=ax)plt.xlabel('Item Condition', fontsize=15)plt.ylabel('Price', fontsize=15)plt.xticks(fontsize=15)plt.yticks(fontsize=15)plt.show() Though the proportion is low, items with item condition ID as 5 have higher median price when compared with items having better condition. After going through some of the data in which the item condition ID is given as 5, most of the products with this condition, especially electronic products are being sold for their parts which itself can prove to be valuable. This pretty much explains the higher median price. There are 1268 unique categories in the ‘category_name’ (train['category_name'].value_counts(normalize=True)*100).head(6)Out:Women/Athletic Apparel/Pants, Tights, Leggings 4.060365Women/Tops & Blouses/T-Shirts 3.134841 Beauty/Makeup/Face 2.321684 Beauty/Makeup/Lips 2.025398 Electronics/Video Games & Consoles/Games 1.798039 Beauty/Makeup/Eyes 1.720390 Name: category_name, dtype: float64 As we can see, for each item, there are three sets of categories separated by ‘/’. The categories are arranged from top to bottom with respect to the comprehensiveness. Therefore we can split the categories into three different columns. The three categories will signify main category, first subcategory and second subcategory. While splitting, the missing values will be filled with the string ‘Category Unknown’. As a common preprocessing practice, we will convert all the textual categorical values to lower case. The reason for doing this will be clear with the following example: Suppose there are two rows in the data and the product belonging to both the rows is an iPhone and the brand name corresponding to the first entry is ‘APPLE’ and for the second entry it is given as ‘Apple’. So when we featurise the data for applying the machine learning models, any featurisation technique that we will apply will consider ‘APPLE’ and ‘Apple’ has two different values even though they mean the same thing. So, for our model to consider these two values as the same, we will convert all the textual categorical values to lower case. Effectively, ‘APPLE’ and ‘Apple’ will become ‘apple’ and ‘apple’. After splitting the categories, we have 11 unique main categories, 114 unique first sub-categories, 863 unique second sub-categories. Let’s see which one of the main categories have the highest number of products in the data and also see how the main categories stack up according to the median price of their respective products. The maximum number of products, i.e. 44.8% of the total products belong to ‘Women’ category followed by ‘Beauty’ category products which takes up around 14% of the total products while 1.7% of the products, being the minimum, belong to the ‘Sports and Outdoor’ category. The highest median price of $21 belongs to the items from ‘Men’ category followed by ‘Women’ category having a median price of $19 while the items from ‘Handmade’ category have the lowest median price of $12. Since there are 114 unique subcategories, it will be difficult to visualize all of them. So, we will take a look at top 10 most popular subcategories and top & bottom 10 subcategories sorted according to the median prices of their respective items. The most popular subcategory is ‘Athletic Apparel’ which aligns with the previous observation that the most popular main category is ‘Women’ and ‘Athletic Apparel’ comes under both the ‘Women’ and ‘Men’ categories. 9% of the total products comes under the Athletic Apparel category. From the perspective of the median price of the items, the items from the subcategory of ‘Computers & Tablets’ have the highest median price, with the median price being $40. The items from the subcategory ‘Paper Goods’ have the lowest median price of $6. ‘Paper Goods’ come under the ‘Handmade’ category. This also validates the previous observation that the items from ‘Handmade’ category have the lowest median price out of all the main categories. There are 4535 unique brands in the data. Let’s take a look at the top 10 most popular brands. Nike and Pink are the top two most popular brands and 12.6% of the total products in the data belong to these two brands. When we had checked for missing values, ‘brand_name’ feature had 42.7% missing values. So to deal with it, we will impute the missing values with the string ‘brand unavailable’. train[’brand_name’] = train[’brand_name’].fillna(’brand_unavailable’) Since there were 42% missing values, it will be interesting to see whether the price is impacted when the brand name is given or not for that particular product. For that, we will create a new feature named ‘brand_name_given’ with the values ‘Yes’ and ‘No’ denoting whether the brand name is given or not. Let’s find out! After looking at the box plots, although there is good amount of overlap, we can say that there is a considerable difference in the prices when the brand is given and when it’s not given. The median price of the product when the brand name is given is $20 and when the brand name is not given, the median price is $14. In a nutshell, this feature will be helpful for the ML model to map some kind of pattern from it. The ‘item_description’ feature falls under the category of unstructured text data. For this type of data, the preprocessing steps will include the following operations: Convert all the words to lowercase.Remove common words like ‘or’, ‘and’, ‘is’, ‘the’, ‘was’ etc. We remove them because these kinds of words will be present within the data in high proportion and the ML models won’t be able to generate any meaningful patterns from it. These set of words are known as ‘Stopwords’.Remove special characters like ‘&’, ‘@’, ‘!’, ‘?’ etc. Convert all the words to lowercase. Remove common words like ‘or’, ‘and’, ‘is’, ‘the’, ‘was’ etc. We remove them because these kinds of words will be present within the data in high proportion and the ML models won’t be able to generate any meaningful patterns from it. These set of words are known as ‘Stopwords’. Remove special characters like ‘&’, ‘@’, ‘!’, ‘?’ etc. For visualization, one of the most effective ways to visualize text data is by plotting ‘Word Clouds’. We will see in the following word clouds about how do the words in the item description compare when the price increases. To check that, we will sort the data according to the prices from low to high and then divide the data into four equivalent parts. By doing this the first quarter will have products with the lowest prices and consequently the fourth quarter will have products with the highest prices. All the four word clouds are almost identical to each other. Words like ‘brand new’, ‘never used’, ‘good condition’, ‘size’, ‘medium’ etc. are used in a high frequency for most of the products irrespective of the price. This shows that the sellers most of the time try to put in a good word for their product in the product description section, so that they don’t have much trouble in selling off the product quickly. One interesting thing in the first word cloud are the words ‘description yet’. After a quick glance through the data, there are entries in which the description is not given but just the words ‘No description yet’ and there are 5.57% rows with such words. Just like we did with the ‘brand_name’ feature, we will verify whether the price of the product is impacted when the description is given or not. There is not much difference to be seen here unlike the ‘brand_name’ feature. The median price of the product when the description is given and when it is not given are almost the same. The 75th percentile value of the product price when the description is given is 5$ more than the 75th percentile value of the product price when the description is not given. The features that we will select for modelling are ‘brand_name’, ‘brand_name_given’, ‘item_description_id’, ‘shipping’, ‘main_category’, ‘subcategory_1’, ‘subcategory_2’ and ‘item_description’. A machine learning model can only learn from the data we provide it, so ensuring that data includes all the relevant information for our task is crucial. All the above features that we just analysed will be used for making the model. But a ML model cannot differentiate between 'Nike' and 'Samsung' brand or between ‘Makeup’ and 'Toys' category or with any categorical feature for that matter. So to solve this problem, we need to convert our categorical values to numerical values. We can do this by 'One-Hot Encoding' our categorical values. The concept of ‘One-Hot Encoding' will be clear with the following examples. Suppose we have a feature called 'Color' and this feature has three unique values: Red, Blue and Green. By applying 'One-Hot Encoding' to this Color feature, three columns will be generated with each column representing the three colors with a binary value of 1 or 0 denoting whether that color is present in that particular row/observation or not. We can implement ‘One-Hot Encoding’ to the categorical data with the help of Scikit-Learn library in Python. Also, when we apply OHE, we need to apply it to the test data with respect to the train data to avoid data leakage. For example, if there is another color in the test data, ‘Yellow’, which is not present in the train data, then to avoid data leakage, we will ignore ‘Yellow’ while applying OHE to the test data since the test data should always be treated as ‘unseen’. Now coming onto representing the ‘item_description’ feature into numerical values, we will apply the technique called ‘Bag of Words’. This technique is same as ‘One-Hot Encoding’ In this technique we will build a vocabulary of all the unique words in our dataset, and associate a unique column to each word in the vocabulary. Each sentence is then represented as a list that is as long as the number of distinct words in our vocabulary. At each column in this list, we mark how many times the given word appears in our sentence. This is called a ‘Bag of Words’ model, since it is a representation that completely ignores the order of words in our sentence. The explanation will be clear with the image given below. Generally, the Root Mean Squared Error (RMSE) metric is used for regression tasks. But as price followed a long-tailed distribution (50% of the products were under $17), in order to make errors on lower price products more relevant than for higher prices, the appropriate metric for this problem would be Root Mean Squared Logarithmic Error (RMSLE). Thus, we will apply the log transformation to the price target variable, to make this assumption available for model training. The formula for RMSLE and what each variable denotes is given in the image below. The final step to take before getting started with modeling is establishing a naive baseline. This is essentially a guess against which we can compare our results. If the machine learning models do not beat this guess, then we might have to conclude that machine learning is not acceptable for the task or we might need to try a different approach. For regression problems, a reasonable naive baseline would be; for all the examples in test set, the corresponding price prediction would be the mean value of the price variable of all the examples from the train set. This sets a relatively low bar for any model to surpass. So let’s apply log transformation to and evaluate the baseline model. #split the target variable and the predictor variablesx_train, x_test = train.drop(['price'], axis=1), test.drop(['price'], axis=1)y_train, y_test = train['price'], test['price']#log transformationy_train_log = np.log1p(y_train)y_test_log = np.log1p(y_test)#for baseline predictiony_train_mean = y_train_log.mean()from sklearn.metrics import mean_squared_errordef rmsle(y_test, y_pred): result = (np.sqrt(((y_test-y_pred)**2).mean())).round(4) return result baseline_result = rmsle(y_test_log,y_train_mean)print(baseline_result)0.7497 In order for us to say that the machine learning algorithm has performed well, the error obtained from the ML model should be less than the baseline error i.e. 0.7497. There are a ton of machine learning models to choose from and deciding where to start can be intimidating. One of the approaches would be to try out several algorithms and see which one works best! Machine learning is still a field driven primarily by experimental rather than theoretical results and it’s impossible to know ahead of time which model will do best. We will evaluate four different models covering the complexity spectrum: Linear Regression Support Vector Regression Decision Tree Regression Extreme Gradient Boosting Regression (XGBoost) For each of the above models, we can optimize it by tuning their respective hyperparameters. Model hyperparameters are best thought of as settings for a machine learning algorithm that are set by the data scientist before training. Examples would be the number of trees in a random forest or the number of neighbors used in K-nearest neighbors algorithm. Model parameters are what the model learns during training, such as weights in a linear regression. Controlling the hyperparameters affects the model performance by altering the balance between underfitting and overfitting in a model. Underfitting is when our model is not complex enough to learn the mapping from features to target. An underfit model has high bias, which we can correct by making our model more complex. Overfitting is when our model essentially memorizes the training data. An overfit model has high variance, which we can correct by limiting the complexity of the model through regularization. Both an underfit and an overfit model will not be able to generalize well to the testing data. The problem with choosing the right hyperparameters is that the optimal set will be different for every machine learning problem! Therefore, the only way to find the best settings is to try out a number of them on each new dataset. The particular hyperparameter tuning technique that we will apply is Random Search with K Fold Cross Validation : Random Search refers to the technique we will use to select hyperparameters. We define a grid and then randomly sample different combinations and perform K-fold CV, rather than grid search where we exhaustively try out every single combination. Random search performs nearly as well as Grid search with a drastic reduction in run time. K-Fold CV is where a given data set is split into a K number of sections/folds where each fold is used as a testing set at some point. Let’s take the example of 5-Fold cross validation(K=5). Here, the data set is split into 5 folds. In the first iteration, the first fold is used to test the model and the rest are used to train the model. In the second iteration, 2nd fold is used as the testing set while the rest serve as the training set. This process is repeated until each fold of the 5 folds have been used as the testing set. The test error from all the five iterations are averaged for that specific hyperparamter combination. After the Random Search CV completes, the hyperparameter combination, for which the average test error is the lowest is selected as the optimal hyperparameter combination. This combination will then be used to predict the prices for the examples in the test data. We will use the Scikit-Learn library in Python for model building. Once you know how to make one model in Scikit-Learn, you can quickly implement a diverse range of algorithms. We can illustrate one example of model creation, training (using .fit ) and testing (using .predict ) with the Decision Tree Regressor along with Random Search CV: from sklearn.tree import DecisionTreeRegressorfrom sklearn.model_selection import RandomizedSearchCV# Create the model to use for hyperparameter tuningDT = DecisionTreeRegressor(random_state=42)# Minimum number of samples to split a nodemin_samples_split = [25,50,75,100,200]# Maximum depth of each treemax_depth = [5,10,20,30,50]# Define the grid of hyperparameters to searchparams = {'max_depth':max_depth, 'min_samples_split':min_samples_split}# Set up the random search with 4-fold cross validationRS_DT = RandomizedSearchCV(DT, params, scoring='neg_mean_squared_error', cv=4, n_jobs=-1, random_state=42)# Fit on the training dataRS_DT.fit(x_train_final, y_train_log)# this will return the hyperparameters with lowest CV errorRS_DT.best_params_Out:{'max_depth':30, 'min_samples_split':50} Now we will use the above hyperparameters to evaluate the performance of the model on the test set. # Create the model with the optimal hyperparametersDT = DecisionTreeRegressor(max_depth=30, min_samples_split=50, random_state=42)# Fit the model on the training dataDT.fit(x_train_final, y_train_log)# Make predictions on the test datay_pred_dt = DT.predict(x_test_final)# Evaluate the modeldt_error = rmsle(y_test_log, y_pred_dt)print(dt_error)Out:0.582 The RMSLE for the Decision Tree model is 0.582 which is 22.3% lower than the baseline model result. Clearly, machine learning is applicable to our problem because of the significant improvement over the baseline! The same procedure is also followed for the rest of the selected ML models. Let’s see how the rest of the models have performed on the test set. The Linear Regression model gave the lowest RMSLE on the test set. This shows that simpler ML models can also get the job done and that they should not be underestimated. Also, both the linear models (Linear regression and Support Vector Regression) have performed better than both the non linear models (Decision Tree and XGBoost Regression). In this article, we’ve walked through a data science case study where we understood the problem statement, did exploratory data analysis, feature transformations and finally selected ML models, did random search along with hyperparameter tuning and evaluated them on the test set and compared the results. Machine learning is often an iterative rather than linear process. I hope this case study has at least given you an high level overview about how problems related to data science and machine learning are usually approached and solved. References that helped me write this blog: https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420https://towardsdatascience.com/a-complete-machine-learning-project-walk-through-in-python-part-two-300f1f8147e2https://towardsdatascience.com/machine-learning-for-retail-price-suggestion-with-python-64531e64186dhttps://medium.com/unstructured/how-i-lost-a-silver-medal-in-kaggles-mercari-price-suggestion-challenge-using-cnns-and-tensorflow-4013660fcded https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420 https://towardsdatascience.com/a-complete-machine-learning-project-walk-through-in-python-part-two-300f1f8147e2 https://towardsdatascience.com/machine-learning-for-retail-price-suggestion-with-python-64531e64186d https://medium.com/unstructured/how-i-lost-a-silver-medal-in-kaggles-mercari-price-suggestion-challenge-using-cnns-and-tensorflow-4013660fcded Thank you for reading!
[ { "code": null, "e": 496, "s": 172, "text": "The most effective way to learn data science is by solving data science related problems. Reading, listening and taking notes is valuable, but once you work through a problem, concepts solidify from abstractions into tools you feel confident using. Generally a full cycle data science project includes the following stages:" }, { "code": null, "e": 573, "s": 496, "text": "Data Gathering & WranglingData Analysis & ModelingCommunication & Deployment" }, { "code": null, "e": 600, "s": 573, "text": "Data Gathering & Wrangling" }, { "code": null, "e": 625, "s": 600, "text": "Data Analysis & Modeling" }, { "code": null, "e": 652, "s": 625, "text": "Communication & Deployment" }, { "code": null, "e": 835, "s": 652, "text": "In this case study, we will walk through the Analysis, Modelling and Communication part of the workflow. The general steps involved for solving a data science problem are as follows:" }, { "code": null, "e": 1053, "s": 835, "text": "Understand the problem and dataData exploration / data cleaningFeature engineering / feature selectionEstablishing a performance metricModel evaluation and selectionModel optimizationDraw conclusions and document work" }, { "code": null, "e": 1085, "s": 1053, "text": "Understand the problem and data" }, { "code": null, "e": 1118, "s": 1085, "text": "Data exploration / data cleaning" }, { "code": null, "e": 1158, "s": 1118, "text": "Feature engineering / feature selection" }, { "code": null, "e": 1192, "s": 1158, "text": "Establishing a performance metric" }, { "code": null, "e": 1223, "s": 1192, "text": "Model evaluation and selection" }, { "code": null, "e": 1242, "s": 1223, "text": "Model optimization" }, { "code": null, "e": 1277, "s": 1242, "text": "Draw conclusions and document work" }, { "code": null, "e": 1510, "s": 1277, "text": "Those of you who are not familiar with the field of Data Science and Python programming language can still follow through the article as it will give an high level overview about how these kind of problems are approached and solved." }, { "code": null, "e": 1624, "s": 1510, "text": "While some code snippets are included within the blog, for the full code you can check out this Jupyter Notebook." }, { "code": null, "e": 2002, "s": 1624, "text": "Mercari is Japan’s biggest community powered shopping app where people can sell and buy a variety of brand new and used products of different brands, from sweaters to smartphones. Now Mercari would like to suggest the correct prices to the sellers but this is tough because their sellers are enabled to put just about anything, or any bundle of things on Mercari’s marketplace." }, { "code": null, "e": 2173, "s": 2002, "text": "So our objective is to build a model that automatically suggests the right product prices to the sellers. We are provided with the following information for each product:" }, { "code": null, "e": 2206, "s": 2173, "text": "train_id — the id of the product" }, { "code": null, "e": 2238, "s": 2206, "text": "name — the title of the product" }, { "code": null, "e": 2311, "s": 2238, "text": "item_condition_id — the condition of the product provided by the sellers" }, { "code": null, "e": 2351, "s": 2311, "text": "category_name — category of the product" }, { "code": null, "e": 2389, "s": 2351, "text": "brand_name — the product’s brand name" }, { "code": null, "e": 2475, "s": 2389, "text": "shipping — 1 if shipping fee is paid by seller and 0 if shipping fee is paid by buyer" }, { "code": null, "e": 2530, "s": 2475, "text": "item_description — the full description of the product" }, { "code": null, "e": 2629, "s": 2530, "text": "price — the price that the product was sold for (This is the target variable that we will predict)" }, { "code": null, "e": 2717, "s": 2629, "text": "This type of problem lies under the category of Supervised Regression Machine Learning:" }, { "code": null, "e": 2855, "s": 2717, "text": "Supervised: We have access to both the features and the target and our goal is to train a model that can learn a mapping between the two." }, { "code": null, "e": 2921, "s": 2855, "text": "Regression: The target variable, price, is a continuous variable." }, { "code": null, "e": 3656, "s": 2921, "text": "EDA is an open-ended process where we calculate statistics and make figures to find trends, anomalies, patterns, or relationships within the data. In short, the goal of EDA is to learn what our data can tell us. It generally starts out with a high level overview, then narrows in to specific areas as we find interesting parts of the data. The findings may be interesting in their own right, or they can be used to inform our modeling choices, such as by helping us decide which features to use. In a hurry to get to the machine learning stage, some data scientists either entirely skip the exploratory process or do a very perfunctory job but in reality EDA is one of the most crucial steps in solving a data science related problem." }, { "code": null, "e": 3786, "s": 3656, "text": "The data set can be downloaded from Kaggle. To validate the result, we only need the ‘train.tsv’ data file. So let’s get started!" }, { "code": null, "e": 3928, "s": 3786, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 4093, "s": 3928, "text": "We will split the data into train and test sets in the proportion of 80% and 20% respectively. As a common practice, we will conduct EDA on the train data set only." }, { "code": null, "e": 4247, "s": 4093, "text": "In:data = pd.read_csv('train.tsv', sep='\\t')train, test = train_test_split(data, test_size=0.2)print(train.shape, test.shape)Out:(1186028, 8) (296507, 8)" }, { "code": null, "e": 4523, "s": 4247, "text": "There are around 1.18 million data points/rows in the train data and 0.296 million data points/rows in the test data. 8 is the number of columns/features in both the sets. Features and variables mean the same thing here, so they might be used interchangeably within the blog." }, { "code": null, "e": 4589, "s": 4523, "text": "#this command displays first few rows of the data settrain.head()" }, { "code": null, "e": 4849, "s": 4589, "text": "A common problem when dealing with real-world data is missing values. These can arise for many reasons and have to be either filled in or removed before we train a machine learning model. First, let’s get a sense of how many missing values are in each column." }, { "code": null, "e": 4988, "s": 4849, "text": "The ‘brand_name’ feature has 42% missing values. Some of the approaches that are usually considered while dealing with missing values are:" }, { "code": null, "e": 5209, "s": 4988, "text": "Remove the records with the missing values.Remove the feature itself if the number of missing values is higher than some threshold, say 50%.Consider ‘missing values’ as another category of that respective feature itself." }, { "code": null, "e": 5253, "s": 5209, "text": "Remove the records with the missing values." }, { "code": null, "e": 5351, "s": 5253, "text": "Remove the feature itself if the number of missing values is higher than some threshold, say 50%." }, { "code": null, "e": 5432, "s": 5351, "text": "Consider ‘missing values’ as another category of that respective feature itself." }, { "code": null, "e": 5493, "s": 5432, "text": "In this project, we will go forward with the third approach." }, { "code": null, "e": 5716, "s": 5493, "text": "Now we will start analyzing the features one by one. We will first go through the target variable, Price, and then start analyzing the predictor variables individually and also see how it interacts with the Price variable." }, { "code": null, "e": 5805, "s": 5716, "text": "Let’s check the distribution of the Price variable and go through some basic statistics." }, { "code": null, "e": 6054, "s": 5805, "text": "train['price'].plot.hist(bins=50, figsize=(10,5), edgecolor='white',range=[0,500])plt.xlabel('Price', fontsize=15)plt.ylabel('Frequency', fontsize=15)plt.tick_params(labelsize=15)plt.title('Price Distribution - Training Set', fontsize=17)plt.show()" }, { "code": null, "e": 6080, "s": 6054, "text": "train['price'].describe()" }, { "code": null, "e": 6192, "s": 6080, "text": "The distribution of the Price variable aligns with the above statistics, i.e. the distribution is right skewed." }, { "code": null, "e": 6230, "s": 6192, "text": "The median price of the items is $17." }, { "code": null, "e": 6269, "s": 6230, "text": "75% of the items have price below $29." }, { "code": null, "e": 6322, "s": 6269, "text": "The maximum price of an item from the data is $2009." }, { "code": null, "e": 6439, "s": 6322, "text": "In:train['shipping'].value_counts(normalize=True)*100Out:0 55.2676671 44.732333 Name: shipping, dtype: float64" }, { "code": null, "e": 6559, "s": 6439, "text": "The shipping fee for 55.26% of the items are paid by the buyers. Let’s see how the shipping feature relates with price." }, { "code": null, "e": 6713, "s": 6559, "text": "The median price of the products is $14.0 if seller pays for the shipping while the median price of the products is $20.0 if buyer pays for the shipping." }, { "code": null, "e": 7039, "s": 6713, "text": "Normally when we buy products online, we need to pay for shipping or delivery of products which are below a certain price. But here the trend is kind of opposite since the median price of items for which the seller pays the shipping fees is lower than the median price of the items for which the buyer pays the shipping fees." }, { "code": null, "e": 7159, "s": 7039, "text": "The ‘item_condition_id’ has five unique values ranging from 1 to 5. Lower the number, better the condition of the item." }, { "code": null, "e": 7352, "s": 7159, "text": "In:train['item_condition_id'].value_counts(normalize=True, sort=False)*100Out:1 43.194511 2 25.323264 3 29.166934 4 2.153153 5 0.162138 Name: item_condition_id, dtype: float64" }, { "code": null, "e": 7679, "s": 7352, "text": "43% of the items have item condition ID as 1 while only 0.16% of the items have item condition ID has 5. Let’s see how this feature relates with Price. For comparing and visualizing the relation between a categorical variable and a numerical variable, Box-Plots are very helpful. The code below is used for plotting Box-Plots." }, { "code": null, "e": 8030, "s": 7679, "text": "#for easier visualization, we are considering the prices from range of 0-100price_100 = train[train['price']<100]fig, ax = plt.subplots(figsize=(20,7.5))sns.boxplot(x='item_condition_id', y='price', data=price_100, ax=ax)plt.xlabel('Item Condition', fontsize=15)plt.ylabel('Price', fontsize=15)plt.xticks(fontsize=15)plt.yticks(fontsize=15)plt.show()" }, { "code": null, "e": 8169, "s": 8030, "text": "Though the proportion is low, items with item condition ID as 5 have higher median price when compared with items having better condition." }, { "code": null, "e": 8446, "s": 8169, "text": "After going through some of the data in which the item condition ID is given as 5, most of the products with this condition, especially electronic products are being sold for their parts which itself can prove to be valuable. This pretty much explains the higher median price." }, { "code": null, "e": 8502, "s": 8446, "text": "There are 1268 unique categories in the ‘category_name’" }, { "code": null, "e": 9020, "s": 8502, "text": "(train['category_name'].value_counts(normalize=True)*100).head(6)Out:Women/Athletic Apparel/Pants, Tights, Leggings 4.060365Women/Tops & Blouses/T-Shirts 3.134841 Beauty/Makeup/Face 2.321684 Beauty/Makeup/Lips 2.025398 Electronics/Video Games & Consoles/Games 1.798039 Beauty/Makeup/Eyes 1.720390 Name: category_name, dtype: float64" }, { "code": null, "e": 9435, "s": 9020, "text": "As we can see, for each item, there are three sets of categories separated by ‘/’. The categories are arranged from top to bottom with respect to the comprehensiveness. Therefore we can split the categories into three different columns. The three categories will signify main category, first subcategory and second subcategory. While splitting, the missing values will be filled with the string ‘Category Unknown’." }, { "code": null, "e": 9605, "s": 9435, "text": "As a common preprocessing practice, we will convert all the textual categorical values to lower case. The reason for doing this will be clear with the following example:" }, { "code": null, "e": 10220, "s": 9605, "text": "Suppose there are two rows in the data and the product belonging to both the rows is an iPhone and the brand name corresponding to the first entry is ‘APPLE’ and for the second entry it is given as ‘Apple’. So when we featurise the data for applying the machine learning models, any featurisation technique that we will apply will consider ‘APPLE’ and ‘Apple’ has two different values even though they mean the same thing. So, for our model to consider these two values as the same, we will convert all the textual categorical values to lower case. Effectively, ‘APPLE’ and ‘Apple’ will become ‘apple’ and ‘apple’." }, { "code": null, "e": 10354, "s": 10220, "text": "After splitting the categories, we have 11 unique main categories, 114 unique first sub-categories, 863 unique second sub-categories." }, { "code": null, "e": 10551, "s": 10354, "text": "Let’s see which one of the main categories have the highest number of products in the data and also see how the main categories stack up according to the median price of their respective products." }, { "code": null, "e": 10822, "s": 10551, "text": "The maximum number of products, i.e. 44.8% of the total products belong to ‘Women’ category followed by ‘Beauty’ category products which takes up around 14% of the total products while 1.7% of the products, being the minimum, belong to the ‘Sports and Outdoor’ category." }, { "code": null, "e": 11031, "s": 10822, "text": "The highest median price of $21 belongs to the items from ‘Men’ category followed by ‘Women’ category having a median price of $19 while the items from ‘Handmade’ category have the lowest median price of $12." }, { "code": null, "e": 11280, "s": 11031, "text": "Since there are 114 unique subcategories, it will be difficult to visualize all of them. So, we will take a look at top 10 most popular subcategories and top & bottom 10 subcategories sorted according to the median prices of their respective items." }, { "code": null, "e": 11563, "s": 11280, "text": "The most popular subcategory is ‘Athletic Apparel’ which aligns with the previous observation that the most popular main category is ‘Women’ and ‘Athletic Apparel’ comes under both the ‘Women’ and ‘Men’ categories. 9% of the total products comes under the Athletic Apparel category." }, { "code": null, "e": 11738, "s": 11563, "text": "From the perspective of the median price of the items, the items from the subcategory of ‘Computers & Tablets’ have the highest median price, with the median price being $40." }, { "code": null, "e": 12015, "s": 11738, "text": "The items from the subcategory ‘Paper Goods’ have the lowest median price of $6. ‘Paper Goods’ come under the ‘Handmade’ category. This also validates the previous observation that the items from ‘Handmade’ category have the lowest median price out of all the main categories." }, { "code": null, "e": 12110, "s": 12015, "text": "There are 4535 unique brands in the data. Let’s take a look at the top 10 most popular brands." }, { "code": null, "e": 12232, "s": 12110, "text": "Nike and Pink are the top two most popular brands and 12.6% of the total products in the data belong to these two brands." }, { "code": null, "e": 12410, "s": 12232, "text": "When we had checked for missing values, ‘brand_name’ feature had 42.7% missing values. So to deal with it, we will impute the missing values with the string ‘brand unavailable’." }, { "code": null, "e": 12480, "s": 12410, "text": "train[’brand_name’] = train[’brand_name’].fillna(’brand_unavailable’)" }, { "code": null, "e": 12802, "s": 12480, "text": "Since there were 42% missing values, it will be interesting to see whether the price is impacted when the brand name is given or not for that particular product. For that, we will create a new feature named ‘brand_name_given’ with the values ‘Yes’ and ‘No’ denoting whether the brand name is given or not. Let’s find out!" }, { "code": null, "e": 13219, "s": 12802, "text": "After looking at the box plots, although there is good amount of overlap, we can say that there is a considerable difference in the prices when the brand is given and when it’s not given. The median price of the product when the brand name is given is $20 and when the brand name is not given, the median price is $14. In a nutshell, this feature will be helpful for the ML model to map some kind of pattern from it." }, { "code": null, "e": 13388, "s": 13219, "text": "The ‘item_description’ feature falls under the category of unstructured text data. For this type of data, the preprocessing steps will include the following operations:" }, { "code": null, "e": 13756, "s": 13388, "text": "Convert all the words to lowercase.Remove common words like ‘or’, ‘and’, ‘is’, ‘the’, ‘was’ etc. We remove them because these kinds of words will be present within the data in high proportion and the ML models won’t be able to generate any meaningful patterns from it. These set of words are known as ‘Stopwords’.Remove special characters like ‘&’, ‘@’, ‘!’, ‘?’ etc." }, { "code": null, "e": 13792, "s": 13756, "text": "Convert all the words to lowercase." }, { "code": null, "e": 14071, "s": 13792, "text": "Remove common words like ‘or’, ‘and’, ‘is’, ‘the’, ‘was’ etc. We remove them because these kinds of words will be present within the data in high proportion and the ML models won’t be able to generate any meaningful patterns from it. These set of words are known as ‘Stopwords’." }, { "code": null, "e": 14126, "s": 14071, "text": "Remove special characters like ‘&’, ‘@’, ‘!’, ‘?’ etc." }, { "code": null, "e": 14636, "s": 14126, "text": "For visualization, one of the most effective ways to visualize text data is by plotting ‘Word Clouds’. We will see in the following word clouds about how do the words in the item description compare when the price increases. To check that, we will sort the data according to the prices from low to high and then divide the data into four equivalent parts. By doing this the first quarter will have products with the lowest prices and consequently the fourth quarter will have products with the highest prices." }, { "code": null, "e": 15054, "s": 14636, "text": "All the four word clouds are almost identical to each other. Words like ‘brand new’, ‘never used’, ‘good condition’, ‘size’, ‘medium’ etc. are used in a high frequency for most of the products irrespective of the price. This shows that the sellers most of the time try to put in a good word for their product in the product description section, so that they don’t have much trouble in selling off the product quickly." }, { "code": null, "e": 15456, "s": 15054, "text": "One interesting thing in the first word cloud are the words ‘description yet’. After a quick glance through the data, there are entries in which the description is not given but just the words ‘No description yet’ and there are 5.57% rows with such words. Just like we did with the ‘brand_name’ feature, we will verify whether the price of the product is impacted when the description is given or not." }, { "code": null, "e": 15817, "s": 15456, "text": "There is not much difference to be seen here unlike the ‘brand_name’ feature. The median price of the product when the description is given and when it is not given are almost the same. The 75th percentile value of the product price when the description is given is 5$ more than the 75th percentile value of the product price when the description is not given." }, { "code": null, "e": 16011, "s": 15817, "text": "The features that we will select for modelling are ‘brand_name’, ‘brand_name_given’, ‘item_description_id’, ‘shipping’, ‘main_category’, ‘subcategory_1’, ‘subcategory_2’ and ‘item_description’." }, { "code": null, "e": 16632, "s": 16011, "text": "A machine learning model can only learn from the data we provide it, so ensuring that data includes all the relevant information for our task is crucial. All the above features that we just analysed will be used for making the model. But a ML model cannot differentiate between 'Nike' and 'Samsung' brand or between ‘Makeup’ and 'Toys' category or with any categorical feature for that matter. So to solve this problem, we need to convert our categorical values to numerical values. We can do this by 'One-Hot Encoding' our categorical values. The concept of ‘One-Hot Encoding' will be clear with the following examples." }, { "code": null, "e": 16981, "s": 16632, "text": "Suppose we have a feature called 'Color' and this feature has three unique values: Red, Blue and Green. By applying 'One-Hot Encoding' to this Color feature, three columns will be generated with each column representing the three colors with a binary value of 1 or 0 denoting whether that color is present in that particular row/observation or not." }, { "code": null, "e": 17459, "s": 16981, "text": "We can implement ‘One-Hot Encoding’ to the categorical data with the help of Scikit-Learn library in Python. Also, when we apply OHE, we need to apply it to the test data with respect to the train data to avoid data leakage. For example, if there is another color in the test data, ‘Yellow’, which is not present in the train data, then to avoid data leakage, we will ignore ‘Yellow’ while applying OHE to the test data since the test data should always be treated as ‘unseen’." }, { "code": null, "e": 17638, "s": 17459, "text": "Now coming onto representing the ‘item_description’ feature into numerical values, we will apply the technique called ‘Bag of Words’. This technique is same as ‘One-Hot Encoding’" }, { "code": null, "e": 18174, "s": 17638, "text": "In this technique we will build a vocabulary of all the unique words in our dataset, and associate a unique column to each word in the vocabulary. Each sentence is then represented as a list that is as long as the number of distinct words in our vocabulary. At each column in this list, we mark how many times the given word appears in our sentence. This is called a ‘Bag of Words’ model, since it is a representation that completely ignores the order of words in our sentence. The explanation will be clear with the image given below." }, { "code": null, "e": 18733, "s": 18174, "text": "Generally, the Root Mean Squared Error (RMSE) metric is used for regression tasks. But as price followed a long-tailed distribution (50% of the products were under $17), in order to make errors on lower price products more relevant than for higher prices, the appropriate metric for this problem would be Root Mean Squared Logarithmic Error (RMSLE). Thus, we will apply the log transformation to the price target variable, to make this assumption available for model training. The formula for RMSLE and what each variable denotes is given in the image below." }, { "code": null, "e": 19082, "s": 18733, "text": "The final step to take before getting started with modeling is establishing a naive baseline. This is essentially a guess against which we can compare our results. If the machine learning models do not beat this guess, then we might have to conclude that machine learning is not acceptable for the task or we might need to try a different approach." }, { "code": null, "e": 19427, "s": 19082, "text": "For regression problems, a reasonable naive baseline would be; for all the examples in test set, the corresponding price prediction would be the mean value of the price variable of all the examples from the train set. This sets a relatively low bar for any model to surpass. So let’s apply log transformation to and evaluate the baseline model." }, { "code": null, "e": 19971, "s": 19427, "text": "#split the target variable and the predictor variablesx_train, x_test = train.drop(['price'], axis=1), test.drop(['price'], axis=1)y_train, y_test = train['price'], test['price']#log transformationy_train_log = np.log1p(y_train)y_test_log = np.log1p(y_test)#for baseline predictiony_train_mean = y_train_log.mean()from sklearn.metrics import mean_squared_errordef rmsle(y_test, y_pred): result = (np.sqrt(((y_test-y_pred)**2).mean())).round(4) return result baseline_result = rmsle(y_test_log,y_train_mean)print(baseline_result)0.7497" }, { "code": null, "e": 20139, "s": 19971, "text": "In order for us to say that the machine learning algorithm has performed well, the error obtained from the ML model should be less than the baseline error i.e. 0.7497." }, { "code": null, "e": 20504, "s": 20139, "text": "There are a ton of machine learning models to choose from and deciding where to start can be intimidating. One of the approaches would be to try out several algorithms and see which one works best! Machine learning is still a field driven primarily by experimental rather than theoretical results and it’s impossible to know ahead of time which model will do best." }, { "code": null, "e": 20577, "s": 20504, "text": "We will evaluate four different models covering the complexity spectrum:" }, { "code": null, "e": 20595, "s": 20577, "text": "Linear Regression" }, { "code": null, "e": 20621, "s": 20595, "text": "Support Vector Regression" }, { "code": null, "e": 20646, "s": 20621, "text": "Decision Tree Regression" }, { "code": null, "e": 20693, "s": 20646, "text": "Extreme Gradient Boosting Regression (XGBoost)" }, { "code": null, "e": 21048, "s": 20693, "text": "For each of the above models, we can optimize it by tuning their respective hyperparameters. Model hyperparameters are best thought of as settings for a machine learning algorithm that are set by the data scientist before training. Examples would be the number of trees in a random forest or the number of neighbors used in K-nearest neighbors algorithm." }, { "code": null, "e": 21148, "s": 21048, "text": "Model parameters are what the model learns during training, such as weights in a linear regression." }, { "code": null, "e": 21470, "s": 21148, "text": "Controlling the hyperparameters affects the model performance by altering the balance between underfitting and overfitting in a model. Underfitting is when our model is not complex enough to learn the mapping from features to target. An underfit model has high bias, which we can correct by making our model more complex." }, { "code": null, "e": 21757, "s": 21470, "text": "Overfitting is when our model essentially memorizes the training data. An overfit model has high variance, which we can correct by limiting the complexity of the model through regularization. Both an underfit and an overfit model will not be able to generalize well to the testing data." }, { "code": null, "e": 21989, "s": 21757, "text": "The problem with choosing the right hyperparameters is that the optimal set will be different for every machine learning problem! Therefore, the only way to find the best settings is to try out a number of them on each new dataset." }, { "code": null, "e": 22103, "s": 21989, "text": "The particular hyperparameter tuning technique that we will apply is Random Search with K Fold Cross Validation :" }, { "code": null, "e": 22439, "s": 22103, "text": "Random Search refers to the technique we will use to select hyperparameters. We define a grid and then randomly sample different combinations and perform K-fold CV, rather than grid search where we exhaustively try out every single combination. Random search performs nearly as well as Grid search with a drastic reduction in run time." }, { "code": null, "e": 23339, "s": 22439, "text": "K-Fold CV is where a given data set is split into a K number of sections/folds where each fold is used as a testing set at some point. Let’s take the example of 5-Fold cross validation(K=5). Here, the data set is split into 5 folds. In the first iteration, the first fold is used to test the model and the rest are used to train the model. In the second iteration, 2nd fold is used as the testing set while the rest serve as the training set. This process is repeated until each fold of the 5 folds have been used as the testing set. The test error from all the five iterations are averaged for that specific hyperparamter combination. After the Random Search CV completes, the hyperparameter combination, for which the average test error is the lowest is selected as the optimal hyperparameter combination. This combination will then be used to predict the prices for the examples in the test data." }, { "code": null, "e": 23680, "s": 23339, "text": "We will use the Scikit-Learn library in Python for model building. Once you know how to make one model in Scikit-Learn, you can quickly implement a diverse range of algorithms. We can illustrate one example of model creation, training (using .fit ) and testing (using .predict ) with the Decision Tree Regressor along with Random Search CV:" }, { "code": null, "e": 24473, "s": 23680, "text": "from sklearn.tree import DecisionTreeRegressorfrom sklearn.model_selection import RandomizedSearchCV# Create the model to use for hyperparameter tuningDT = DecisionTreeRegressor(random_state=42)# Minimum number of samples to split a nodemin_samples_split = [25,50,75,100,200]# Maximum depth of each treemax_depth = [5,10,20,30,50]# Define the grid of hyperparameters to searchparams = {'max_depth':max_depth, 'min_samples_split':min_samples_split}# Set up the random search with 4-fold cross validationRS_DT = RandomizedSearchCV(DT, params, scoring='neg_mean_squared_error', cv=4, n_jobs=-1, random_state=42)# Fit on the training dataRS_DT.fit(x_train_final, y_train_log)# this will return the hyperparameters with lowest CV errorRS_DT.best_params_Out:{'max_depth':30, 'min_samples_split':50}" }, { "code": null, "e": 24573, "s": 24473, "text": "Now we will use the above hyperparameters to evaluate the performance of the model on the test set." }, { "code": null, "e": 24928, "s": 24573, "text": "# Create the model with the optimal hyperparametersDT = DecisionTreeRegressor(max_depth=30, min_samples_split=50, random_state=42)# Fit the model on the training dataDT.fit(x_train_final, y_train_log)# Make predictions on the test datay_pred_dt = DT.predict(x_test_final)# Evaluate the modeldt_error = rmsle(y_test_log, y_pred_dt)print(dt_error)Out:0.582" }, { "code": null, "e": 25286, "s": 24928, "text": "The RMSLE for the Decision Tree model is 0.582 which is 22.3% lower than the baseline model result. Clearly, machine learning is applicable to our problem because of the significant improvement over the baseline! The same procedure is also followed for the rest of the selected ML models. Let’s see how the rest of the models have performed on the test set." }, { "code": null, "e": 25457, "s": 25286, "text": "The Linear Regression model gave the lowest RMSLE on the test set. This shows that simpler ML models can also get the job done and that they should not be underestimated." }, { "code": null, "e": 25630, "s": 25457, "text": "Also, both the linear models (Linear regression and Support Vector Regression) have performed better than both the non linear models (Decision Tree and XGBoost Regression)." }, { "code": null, "e": 25936, "s": 25630, "text": "In this article, we’ve walked through a data science case study where we understood the problem statement, did exploratory data analysis, feature transformations and finally selected ML models, did random search along with hyperparameter tuning and evaluated them on the test set and compared the results." }, { "code": null, "e": 26171, "s": 25936, "text": "Machine learning is often an iterative rather than linear process. I hope this case study has at least given you an high level overview about how problems related to data science and machine learning are usually approached and solved." }, { "code": null, "e": 26214, "s": 26171, "text": "References that helped me write this blog:" }, { "code": null, "e": 26671, "s": 26214, "text": "https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420https://towardsdatascience.com/a-complete-machine-learning-project-walk-through-in-python-part-two-300f1f8147e2https://towardsdatascience.com/machine-learning-for-retail-price-suggestion-with-python-64531e64186dhttps://medium.com/unstructured/how-i-lost-a-silver-medal-in-kaggles-mercari-price-suggestion-challenge-using-cnns-and-tensorflow-4013660fcded" }, { "code": null, "e": 26775, "s": 26671, "text": "https://towardsdatascience.com/a-complete-machine-learning-walk-through-in-python-part-one-c62152f39420" }, { "code": null, "e": 26887, "s": 26775, "text": "https://towardsdatascience.com/a-complete-machine-learning-project-walk-through-in-python-part-two-300f1f8147e2" }, { "code": null, "e": 26988, "s": 26887, "text": "https://towardsdatascience.com/machine-learning-for-retail-price-suggestion-with-python-64531e64186d" }, { "code": null, "e": 27131, "s": 26988, "text": "https://medium.com/unstructured/how-i-lost-a-silver-medal-in-kaggles-mercari-price-suggestion-challenge-using-cnns-and-tensorflow-4013660fcded" } ]
C++ for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop in C++ is − for ( init; condition; increment ) { statement(s); } Here is the flow of control in a for loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement can be left blank, as long as a semicolon appears after the condition. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. #include <iostream> using namespace std; int main () { // for loop execution for( int a = 10; a < 20; a = a + 1 ) { cout << "value of a: " << a << endl; } return 0; } When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2457, "s": 2318, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times." }, { "code": null, "e": 2494, "s": 2457, "text": "The syntax of a for loop in C++ is −" }, { "code": null, "e": 2551, "s": 2494, "text": "for ( init; condition; increment ) {\n statement(s);\n}\n" }, { "code": null, "e": 2595, "s": 2551, "text": "Here is the flow of control in a for loop −" }, { "code": null, "e": 2796, "s": 2595, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 2997, "s": 2796, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 3207, "s": 2997, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3417, "s": 3207, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3606, "s": 3417, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 3795, "s": 3606, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 4020, "s": 3795, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4245, "s": 4020, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4434, "s": 4245, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // for loop execution\n for( int a = 10; a < 20; a = a + 1 ) {\n cout << \"value of a: \" << a << endl;\n }\n \n return 0;\n}" }, { "code": null, "e": 4515, "s": 4434, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4666, "s": 4515, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 4703, "s": 4666, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4722, "s": 4703, "text": " Arnab Chakraborty" }, { "code": null, "e": 4754, "s": 4722, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4777, "s": 4754, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4813, "s": 4777, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4830, "s": 4813, "text": " Frahaan Hussain" }, { "code": null, "e": 4865, "s": 4830, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4882, "s": 4865, "text": " Frahaan Hussain" }, { "code": null, "e": 4917, "s": 4882, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4934, "s": 4917, "text": " Frahaan Hussain" }, { "code": null, "e": 4969, "s": 4934, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4986, "s": 4969, "text": " Frahaan Hussain" }, { "code": null, "e": 4993, "s": 4986, "text": " Print" }, { "code": null, "e": 5004, "s": 4993, "text": " Add Notes" } ]
Displaying rotatable 3D plots in IPython or Jupyter Notebook
By creating a 3D projection on the axis and iterating that axis for different angles using view_init(), we can rotate the output diagram. Create a new figure, or activate an existing figure. Create a new figure, or activate an existing figure. Add an `~.axes.Axes` to the figure as part of a subplot arrangement with nrow = 1, ncols = 1, index = 1, and projection = '3d'. Add an `~.axes.Axes` to the figure as part of a subplot arrangement with nrow = 1, ncols = 1, index = 1, and projection = '3d'. Use the method, get_test_data to return a tuple X, Y, Z with a test dataset. Use the method, get_test_data to return a tuple X, Y, Z with a test dataset. Plot a 3D wireframe with data test data x, y, and z. Plot a 3D wireframe with data test data x, y, and z. To make it rotatable, we can set the elevation and azimuth of the axes in degrees (not radians), using view_init() method. To make it rotatable, we can set the elevation and azimuth of the axes in degrees (not radians), using view_init() method. To show the figure, use plt.show() method. To show the figure, use plt.show() method. from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5) # rotate the axes and update for angle in range(0, 360): ax.view_init(30, angle) plt.show()
[ { "code": null, "e": 1200, "s": 1062, "text": "By creating a 3D projection on the axis and iterating that axis for different angles using view_init(), we can rotate the output diagram." }, { "code": null, "e": 1253, "s": 1200, "text": "Create a new figure, or activate an existing figure." }, { "code": null, "e": 1306, "s": 1253, "text": "Create a new figure, or activate an existing figure." }, { "code": null, "e": 1434, "s": 1306, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement with nrow = 1, ncols = 1, index = 1, and projection = '3d'." }, { "code": null, "e": 1562, "s": 1434, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement with nrow = 1, ncols = 1, index = 1, and projection = '3d'." }, { "code": null, "e": 1639, "s": 1562, "text": "Use the method, get_test_data to return a tuple X, Y, Z with a test dataset." }, { "code": null, "e": 1716, "s": 1639, "text": "Use the method, get_test_data to return a tuple X, Y, Z with a test dataset." }, { "code": null, "e": 1769, "s": 1716, "text": "Plot a 3D wireframe with data test data x, y, and z." }, { "code": null, "e": 1822, "s": 1769, "text": "Plot a 3D wireframe with data test data x, y, and z." }, { "code": null, "e": 1945, "s": 1822, "text": "To make it rotatable, we can set the elevation and azimuth of the axes in degrees (not radians), using view_init() method." }, { "code": null, "e": 2068, "s": 1945, "text": "To make it rotatable, we can set the elevation and azimuth of the axes in degrees (not radians), using view_init() method." }, { "code": null, "e": 2111, "s": 2068, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 2154, "s": 2111, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 2472, "s": 2154, "text": "from mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nX, Y, Z = axes3d.get_test_data(0.1)\nax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)\n\n# rotate the axes and update\nfor angle in range(0, 360):\n ax.view_init(30, angle)\n\nplt.show()" } ]
Logging in Node.js
Logging is a very essential part in any application whether it is made in Node.js or any other programming languages. Logging helps us to detect weird behaviours of an application along with real-time errors and exceptions. One should definitely put logical logs in their application. These logs help the user to identify any mistakes and resolve it on urgent basis. There are 5 different log levels which are present at the moment with the user. These log levels are used to define different kinds of logs and helps the user to identify different scenarios. The log levels must be carefully configured to get the best deal out of these logs − error error warn warn info info verbose verbose debug debug You can put this middleware in the request pipeline so that you can directly use the power of debug module to print logs. The best advantage of debug module is that almost all the modules use debug for printing logs. You can use the debug module to print logs and errors. This middleware is mainly used for acting as a middle pipeline – you can pass logs in this pipeline which will be printed in the log file. Requests and responses are also passed through this middleware for logging purposes. It is very beneficial in an Express app. Setting up middleware is easy and can be done in any frameworks being used. application const app = express() const logMiddleware = require('my-logging-middleware') app.use(logMiddleware) router const router = express.Router() const routeLoggingMiddleware = require('my-route-logging-middleware') router.use(routeLoggingMiddleware) errors const app = express(); const errorLoggingMiddleware = require('my-error-logging-middleware') app.use(errorLoggingMiddleware) You can also use the winston package for logging purposes. It also provides different log levels, queries as well as a profiler. application const app = express() const winstonPackage = require('winston') const consoleTransport = new winstonPackage.transports.Console() const myWinstonOptions = { transports: [consoleTransport] } const logger = new winstonPackage.createLogger(myWinstonOptions) function logRequest(req, res, next) { logger.info(req.url) next() } app.use(logRequest) function logError(err, req, res, next) { logger.error(err) next() } app.use(logError)
[ { "code": null, "e": 1429, "s": 1062, "text": "Logging is a very essential part in any application whether it is made in Node.js or any other programming languages. Logging helps us to detect weird behaviours of an application along with real-time errors and exceptions. One should definitely put logical logs in their application. These logs help the user to identify any mistakes and resolve it on urgent basis." }, { "code": null, "e": 1706, "s": 1429, "text": "There are 5 different log levels which are present at the moment with the user. These log levels are used to define different kinds of logs and helps the user to identify different scenarios. The log levels must be carefully configured to get the best deal out of these logs −" }, { "code": null, "e": 1712, "s": 1706, "text": "error" }, { "code": null, "e": 1718, "s": 1712, "text": "error" }, { "code": null, "e": 1723, "s": 1718, "text": "warn" }, { "code": null, "e": 1728, "s": 1723, "text": "warn" }, { "code": null, "e": 1733, "s": 1728, "text": "info" }, { "code": null, "e": 1738, "s": 1733, "text": "info" }, { "code": null, "e": 1746, "s": 1738, "text": "verbose" }, { "code": null, "e": 1754, "s": 1746, "text": "verbose" }, { "code": null, "e": 1760, "s": 1754, "text": "debug" }, { "code": null, "e": 1766, "s": 1760, "text": "debug" }, { "code": null, "e": 2038, "s": 1766, "text": "You can put this middleware in the request pipeline so that you can directly use the power of debug module to print logs. The best advantage of debug module is that almost all the modules use debug for printing logs. You can use the debug module to print logs and errors." }, { "code": null, "e": 2379, "s": 2038, "text": "This middleware is mainly used for acting as a middle pipeline – you can pass logs in this pipeline which will be printed in the log file. Requests and responses are also passed through this middleware for logging purposes. It is very beneficial in an Express app. Setting up middleware is easy and can be done in any frameworks being used." }, { "code": null, "e": 2391, "s": 2379, "text": "application" }, { "code": null, "e": 2491, "s": 2391, "text": "const app = express()\nconst logMiddleware = require('my-logging-middleware')\napp.use(logMiddleware)" }, { "code": null, "e": 2498, "s": 2491, "text": "router" }, { "code": null, "e": 2635, "s": 2498, "text": "const router = express.Router()\nconst routeLoggingMiddleware = require('my-route-logging-middleware')\nrouter.use(routeLoggingMiddleware)" }, { "code": null, "e": 2642, "s": 2635, "text": "errors" }, { "code": null, "e": 2767, "s": 2642, "text": "const app = express();\nconst errorLoggingMiddleware = require('my-error-logging-middleware')\napp.use(errorLoggingMiddleware)" }, { "code": null, "e": 2896, "s": 2767, "text": "You can also use the winston package for logging purposes. It also provides different log levels, queries as well as a profiler." }, { "code": null, "e": 2908, "s": 2896, "text": "application" }, { "code": null, "e": 3353, "s": 2908, "text": "const app = express()\nconst winstonPackage = require('winston')\nconst consoleTransport = new winstonPackage.transports.Console()\nconst myWinstonOptions = {\n transports: [consoleTransport]\n}\nconst logger = new winstonPackage.createLogger(myWinstonOptions)\n\nfunction logRequest(req, res, next) {\n logger.info(req.url)\n next()\n}\napp.use(logRequest)\n\nfunction logError(err, req, res, next) {\n logger.error(err)\n next()\n}\napp.use(logError)" } ]
PyTorch [Vision] — Binary Image Classification | by Akshaj Verma | Towards Data Science
import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torchvisionimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torchvision import transforms, utils, datasetsfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSamplerfrom sklearn.metrics import classification_report, confusion_matrix Set the random seed. np.random.seed(0)torch.manual_seed(0) Set Seaborn style. %matplotlib inlinesns.set_style('darkgrid') Let’s define the path for our data. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")print("We're using =>", device)root_dir = "../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/"print("The data lies here =>", root_dir)###################### OUTPUT ######################We're using => cudaThe data lies here => ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/ Let’s define a dictionary to hold the image transformations for train/test sets. We will resize all images to have size (224, 224) as well as convert the images to tensor. The ToTensor operation in PyTorch convert all tensors to lie between (0, 1). ToTensor converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] image_transforms = { "train": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor() ]), "test": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor()} We 2 dataset folders with us — Train and Test. We will further divide our Train set as Train + Val. hotdog_dataset = datasets.ImageFolder(root = root_dir + "train", transform = image_transforms["train"] )hotdog_dataset###################### OUTPUT ######################Dataset ImageFolder Number of datapoints: 498 Root location: ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/train StandardTransformTransform: Compose( Resize(size=(224, 224), interpolation=PIL.Image.BILINEAR) ToTensor() ) The class_to_idx function is pre-built in PyTorch. It returns class ID's present in the dataset. hotdog_dataset.class_to_idx###################### OUTPUT ######################{'hot_dog': 0, 'not_hot_dog': 1} We will now construct a reverse of this dictionary; a mapping of ID to class. idx2class = {v: k for k, v in hotdog_dataset.class_to_idx.items()} Let’s also write a function that takes in a dataset object and returns a dictionary that contains the count of class samples. We will use this dictionary to construct plots and observe the class distribution in our data. get_class_distribution() takes in an argument called dataset_obj. We first initialize a count_dict dictionary where counts of all classes are initialized to 0. Then, let’s iterate through the dataset and increment the counter by 1 for every class label encountered in the loop. plot_from_dict() takes in 3 arguments: a dictionary called dict_obj, plot_title, and **kwargs. We pass in **kwargs because later on, we will construct subplots which require passing the ax argument in Seaborn. First convert the dictionary to a data-frame. Melt the data frame and plot. def get_class_distribution(dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for _, label_id in dataset_obj: label = idx2class[label_id] count_dict[label] += 1 return count_dictdef plot_from_dict(dict_obj, plot_title, **kwargs): return sns.barplot(data = pd.DataFrame.from_dict([dict_obj]).melt(), x = "variable", y="value", hue="variable", **kwargs).set_title(plot_title)plt.figure(figsize=(15,8))plot_from_dict(get_class_distribution(hotdog_dataset), plot_title="Entire Dataset (before train/val/test split)") We use SubsetRandomSampler to make our train and validation loaders. SubsetRandomSampler is used so that each batch receives a random distribution of classes. We could’ve also split our dataset into 2 parts — train and val ie. make 2 Subsets. But this is simpler because our data loader will pretty much handle everything now. SubsetRandomSampler(indices) takes as input the indices of data. We first create our samplers and then we’ll pass it to our data-loaders. Create a list of indices. Shuffle the indices. Split the indices based on train-val percentage. Create SubsetRandomSampler. Create a list of indices from 0 to length of dataset. hotdog_dataset_size = len(hotdog_dataset)hotdog_dataset_indices = list(range(hotdog_dataset_size)) Shuffle the list of indices using np.shuffle. np.random.shuffle(hotdog_dataset_indices) Create the split index. We choose the split index to be 20% (0.2) of the dataset size. val_split_index = int(np.floor(0.2 * hotdog_dataset_size)) Slice the lists to obtain 2 lists of indices, one for train and other for test. 0-----------val_split_index------------------------------n Train => val_split_index to n Val => 0 to val_split_index train_idx, val_idx = hotdog_dataset_indices[val_split_index:], hotdog_dataset_indices[:val_split_index] Finally, create samplers. train_sampler = SubsetRandomSampler(train_idx)val_sampler = SubsetRandomSampler(val_idx) Now that we’re done with train and val data, let’s load our test dataset. hotdog_dataset_test = datasets.ImageFolder(root = root_dir + "test", transform = image_transforms["test"] )hotdog_dataset_test###################### OUTPUT ######################Dataset ImageFolder Number of datapoints: 500 Root location: ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/test StandardTransformTransform: Compose( Resize(size=(224, 224), interpolation=PIL.Image.BILINEAR) ToTensor() ) Now, we will pass the samplers to our dataloader. Note that shuffle=True cannot be used when you're using the SubsetRandomSampler. train_loader = DataLoader(dataset=hotdog_dataset, shuffle=False, batch_size=8, sampler=train_sampler)val_loader = DataLoader(dataset=hotdog_dataset, shuffle=False, batch_size=1, sampler=val_sampler)test_loader = DataLoader(dataset=hotdog_dataset_test, shuffle=False, batch_size=1) To explore our train and val data-loaders, let’s create a new function that takes in a data-loader and returns a dictionary with class counts. Initialize a dictionary count_dict to all 0s. If the batch_size of the dataloader_obj is 1, then loop through the dataloader_obj and update the counter. Else, if the batch_size of the dataloader_obj is not 1, then loop through the dataloader_obj to obtain batches. Loop through the batches to obtain individual tensors. Now, updated the counter accordingly. def get_class_distribution_loaders(dataloader_obj, dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} if dataloader_obj.batch_size == 1: for _,label_id in dataloader_obj: y_idx = label_id.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 else: for _,label_id in dataloader_obj: for idx in label_id: y_idx = idx.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 return count_dict To plot the class distributions, we will use the plot_from_dict() function defined earlier with the ax argument. fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))plot_from_dict(get_class_distribution_loaders(train_loader, hotdog_dataset), plot_title="Train Set", ax=axes[0])plot_from_dict(get_class_distribution_loaders(val_loader, hotdog_dataset), plot_title="Val Set", ax=axes[1]) Now that we’ve looked at the class distributions, Let’s now look at a single image. single_batch = next(iter(train_loader)) single_batch is a list of 2 elements. The first element (0th index) contains the image tensors while the second element (1st index) contains the output labels. Here’s the first element of the list which is a tensor. This tensor is of the shape (batch, channels, height, width). single_batch[0].shape###################### OUTPUT ######################torch.Size([8, 3, 224, 224]) Here are the output labels for the batch. print("Output label tensors: ", single_batch[1])print("\nOutput label tensor shape: ", single_batch[1].shape)###################### OUTPUT ######################Output label tensors: tensor([1, 1, 1, 1, 1, 1, 1, 1])Output label tensor shape: torch.Size([8]) To plot the image, we’ll use plt.imshow from matloptlib. It expects the image dimension to be (height, width, channels). We'll .permute() our single image tensor to plot it. # Selecting the first image tensor from the batch. single_image = single_batch[0][0]single_image.shape###################### OUTPUT ######################torch.Size([3, 224, 224]) Let’s view the image. plt.imshow(single_image.(1, 2, 0)) PyTorch has made it easier for us to plot the images in a grid straight from the batch. We first extract out the image tensor from the list (returned by our dataloader) and set nrow. Then we use the plt.imshow() function to plot our grid. Remember to .permute() the tensor dimensions! # We do single_batch[0] because each batch is a list # where the 0th index is the image tensor and 1st index is the output label.single_batch_grid = utils.make_grid(single_batch[0], nrow=4)plt.figure(figsize = (10,10))plt.imshow(single_batch_grid.permute(1, 2, 0)) Our architecture is simple. We use 4 blocks of Conv layers. Each block consists ofConvolution + BatchNorm + ReLU + Dropout layers. We will not use an FC layer at the end. We'll stick with a Conv layer. class HotDogClassifier(nn.Module): def __init__(self): super(HotDogClassifier, self).__init__() self.block1 = self.conv_block(c_in=3, c_out=256, dropout=0.1, kernel_size=5, stride=1, padding=2) self.block2 = self.conv_block(c_in=256, c_out=128, dropout=0.1, kernel_size=3, stride=1, padding=1) self.block3 = self.conv_block(c_in=128, c_out=64, dropout=0.1, kernel_size=3, stride=1, padding=1) self.lastcnn = nn.Conv2d(in_channels=64, out_channels=2, kernel_size=56, stride=1, padding=0) self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) def forward(self, x): x = self.block1(x) x = self.maxpool(x) x = self.block2(x) x = self.block3(x) x = self.maxpool(x) x = self.lastcnn(x) return x def conv_block(self, c_in, c_out, dropout, **kwargs): seq_block = nn.Sequential( nn.Conv2d(in_channels=c_in, out_channels=c_out, **kwargs), nn.BatchNorm2d(num_features=c_out), nn.ReLU(), nn.Dropout2d(p=dropout) ) return seq_block Now we’ll initialize the model, optimizer, and loss function. Then we’ll transfer the model to GPU. We’re using the nn.CrossEntropyLoss even though it's a binary classification problem. This means, instead of returning a single output of 1/0, we'll treat return 2 values of 0 and 1. More specifically, probabilities of the output being either 1 or 0. We don’t have to manually apply a log_softmax layer after our final layer because nn.CrossEntropyLoss does that for us. However, we need to apply log_softmax for our validation and testing. model = HotDogClassifier()model.to(device)print(model)criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.008)###################### OUTPUT ######################HotDogClassifier( (block1): Sequential( (0): Conv2d(3, 256, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (block2): Sequential( (0): Conv2d(256, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (block3): Sequential( (0): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (lastcnn): Conv2d(64, 2, kernel_size=(56, 56), stride=(1, 1)) (maxpool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)) Before we start our training, let’s define a function to calculate accuracy per epoch. This function takes y_pred and y_test as input arguments. We then apply softmax to y_pred and extract the class which has a higher probability. After that, we compare the predicted classes and the actual classes to calculate the accuracy. def binary_acc(y_pred, y_test): y_pred_tag = torch.log_softmax(y_pred, dim = 1) _, y_pred_tags = torch.max(y_pred_tag, dim = 1) correct_results_sum = (y_pred_tags == y_test).sum().float() acc = correct_results_sum/y_test.shape[0] acc = torch.round(acc * 100) return acc We’ll also define 2 dictionaries which will store the accuracy/epoch and loss/epoch for both train and validation sets. accuracy_stats = { 'train': [], "val": []}loss_stats = { 'train': [], "val": []} Let’s TRAIN our model! You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you're in training mode. Well, why do we need to do that? If you're using layers such as Dropout or BatchNorm which behave differently during training and evaluation (for eample; not use dropout during evaluation), you need to tell PyTorch to act accordingly. While the default mode in PyTorch is the train, so, you don't explicitly have to write that. But it's good practice. Similarly, we’ll call model.eval() when we test our model. We'll see that below. Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss and accuracy per epoch to 0. After every epoch, we'll print out the loss/accuracy and reset it back to 0. Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader. We do optimizer.zero_grad() before we make any predictions. Since the .backward() function accumulates gradients, we need to set it to 0 manually per mini-batch. From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform backpropagation using loss.backward() and optimizer.step(). Finally, we add all the mini-batch losses (and accuracies) to obtain the average loss (and accuracy) for that epoch. We add up all the losses/accuracies for each minibatch and finally divide it by the number of minibatches ie. length of trainloader to obtain the average loss/accuracy per epoch. The procedure we follow for training is the exact same for validation except for the fact that we wrap it up in torch.no_grad and not perform any backpropagation. torch.no_grad() tells PyTorch that we do not want to perform back-propagation, which reduces memory usage and speeds up computation. print("Begin training.")for e in tqdm(range(1, 21)): # TRAINING train_epoch_loss = 0 train_epoch_acc = 0 model.train() for X_train_batch, y_train_batch in train_loader: X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device) optimizer.zero_grad() y_train_pred = model(X_train_batch).squeeze() train_loss = criterion(y_train_pred, y_train_batch) train_acc = binary_acc(y_train_pred, y_train_batch) train_loss.backward() optimizer.step() train_epoch_loss += train_loss.item() train_epoch_acc += train_acc.item() # VALIDATION with torch.no_grad(): model.eval() val_epoch_loss = 0 val_epoch_acc = 0 for X_val_batch, y_val_batch in val_loader: X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device) y_val_pred = model(X_val_batch).squeeze() y_val_pred = torch.unsqueeze(y_val_pred, 0) val_loss = criterion(y_val_pred, y_val_batch) val_acc = binary_acc(y_val_pred, y_val_batch) val_epoch_loss += val_loss.item() val_epoch_acc += val_acc.item() loss_stats['train'].append(train_epoch_loss/len(train_loader)) loss_stats['val'].append(val_epoch_loss/len(val_loader)) accuracy_stats['train'].append(train_epoch_acc/len(train_loader)) accuracy_stats['val'].append(val_epoch_acc/len(val_loader)) print(f'Epoch {e+0:02}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f} | Train Acc: {train_epoch_acc/len(train_loader):.3f}| Val Acc: {val_epoch_acc/len(val_loader):.3f}')###################### OUTPUT ######################Begin training.Epoch 01: | Train Loss: 113.08463 | Val Loss: 92.26063 | Train Acc: 51.120| Val Acc: 29.000Epoch 02: | Train Loss: 55.47888 | Val Loss: 50.39846 | Train Acc: 63.620| Val Acc: 57.000Epoch 03: | Train Loss: 33.44443 | Val Loss: 20.69457 | Train Acc: 70.500| Val Acc: 71.000Epoch 04: | Train Loss: 18.75201 | Val Loss: 1.50821 | Train Acc: 77.240| Val Acc: 71.000Epoch 05: | Train Loss: 12.88685 | Val Loss: 26.62685 | Train Acc: 75.480| Val Acc: 71.000Epoch 06: | Train Loss: 9.70507 | Val Loss: 3.25360 | Train Acc: 81.080| Val Acc: 86.000Epoch 07: | Train Loss: 11.04334 | Val Loss: 0.00000 | Train Acc: 79.320| Val Acc: 100.000Epoch 08: | Train Loss: 7.16636 | Val Loss: 10.48954 | Train Acc: 83.300| Val Acc: 71.000Epoch 09: | Train Loss: 4.32204 | Val Loss: 0.00001 | Train Acc: 86.400| Val Acc: 100.000Epoch 10: | Train Loss: 2.03338 | Val Loss: 0.00000 | Train Acc: 91.720| Val Acc: 100.000Epoch 11: | Train Loss: 1.68124 | Val Loss: 3.65754 | Train Acc: 92.320| Val Acc: 71.000Epoch 12: | Train Loss: 1.27145 | Val Loss: 5.52111 | Train Acc: 93.320| Val Acc: 86.000Epoch 13: | Train Loss: 0.42285 | Val Loss: 0.00000 | Train Acc: 97.600| Val Acc: 100.000Epoch 14: | Train Loss: 1.03441 | Val Loss: 0.00000 | Train Acc: 94.840| Val Acc: 100.000Epoch 15: | Train Loss: 0.76563 | Val Loss: 0.00000 | Train Acc: 96.340| Val Acc: 100.000Epoch 16: | Train Loss: 0.16889 | Val Loss: 0.00000 | Train Acc: 98.040| Val Acc: 100.000Epoch 17: | Train Loss: 0.42046 | Val Loss: 4.02560 | Train Acc: 96.560| Val Acc: 86.000Epoch 18: | Train Loss: 0.57535 | Val Loss: 0.00000 | Train Acc: 95.640| Val Acc: 100.000Epoch 19: | Train Loss: 0.40181 | Val Loss: 0.00000 | Train Acc: 96.620| Val Acc: 100.000Epoch 20: | Train Loss: 0.92207 | Val Loss: 0.00000 | Train Acc: 95.360| Val Acc: 100.000 To plot the loss and accuracy line plots, we again create a dataframe from the accuracy_stats and loss_stats dictionaries. train_val_acc_df = pd.DataFrame.from_dict(accuracy_stats).reset_index().melt(id_vars=['index']).rename(columns={"index":"epochs"})train_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={"index":"epochs"})fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(30,10))sns.lineplot(data=train_val_acc_df, x = "epochs", y="value", hue="variable", ax=axes[0]).set_title('Train-Val Accuracy/Epoch')sns.lineplot(data=train_val_loss_df, x = "epochs", y="value", hue="variable", ax=axes[1]).set_title('Train-Val Loss/Epoch') After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad(), just like we did it for the validation loop above. We start by defining a list that will hold our predictions. Then we loop through our batches using the test_loader. For each batch - We move our input mini-batch to GPU. We make the predictions using our trained model. Apply log_softmax activation to the predictions and pick the index of highest probability. Move the batch to the GPU from the CPU. Convert the tensor to a numpy object and append it to our list. y_pred_list = []y_true_list = []with torch.no_grad(): for x_batch, y_batch in tqdm(test_loader): x_batch, y_batch = x_batch.to(device), y_batch.to(device) y_test_pred = model(x_batch) _, y_pred_tag = torch.max(y_test_pred, dim = 1) y_pred_list.append(y_pred_tag.cpu().numpy()) y_true_list.append(y_batch.cpu().numpy()) We’ll flatten out the list so that we can use it as an input to confusion_matrix and classification_report. y_pred_list = [i[0][0][0] for i in y_pred_list]y_true_list = [i[0] for i in y_true_list] Finally, we print out the classification report which contains the precision, recall, and the F1 score. print(classification_report(y_true_list, y_pred_list))###################### OUTPUT ######################precision recall f1-score support 0 0.90 0.91 0.91 249 1 0.91 0.90 0.91 249 accuracy 0.91 498 macro avg 0.91 0.91 0.91 498weighted avg 0.91 0.91 0.91 498 Let’s use the confusion_matrix() function to make a confusion matrix. print(confusion_matrix(y_true_list, y_pred_list))###################### OUTPUT ######################[[226 23] [ 24 225]] We create a dataframe from the confusion matrix and plot it as a heatmap using the seaborn library. confusion_matrix_df = pd.DataFrame(confusion_matrix(y_true_list, y_pred_list)).rename(columns=idx2class, index=idx2class)fig, ax = plt.subplots(figsize=(7,5)) sns.heatmap(confusion_matrix_df, annot=True, ax=ax) Thank you for reading. Suggestions and constructive criticism are welcome. :) This blog post is a part of the column— “How to train you Neural Net”. You can find the series here. You can find me on LinkedIn and Twitter. If you liked this, check out my other blogposts.
[ { "code": null, "e": 588, "s": 172, "text": "import numpy as npimport pandas as pdimport seaborn as snsfrom tqdm.notebook import tqdmimport matplotlib.pyplot as pltimport torchimport torchvisionimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torchvision import transforms, utils, datasetsfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSamplerfrom sklearn.metrics import classification_report, confusion_matrix" }, { "code": null, "e": 609, "s": 588, "text": "Set the random seed." }, { "code": null, "e": 647, "s": 609, "text": "np.random.seed(0)torch.manual_seed(0)" }, { "code": null, "e": 666, "s": 647, "text": "Set Seaborn style." }, { "code": null, "e": 710, "s": 666, "text": "%matplotlib inlinesns.set_style('darkgrid')" }, { "code": null, "e": 746, "s": 710, "text": "Let’s define the path for our data." }, { "code": null, "e": 1135, "s": 746, "text": "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")print(\"We're using =>\", device)root_dir = \"../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/\"print(\"The data lies here =>\", root_dir)###################### OUTPUT ######################We're using => cudaThe data lies here => ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/" }, { "code": null, "e": 1307, "s": 1135, "text": "Let’s define a dictionary to hold the image transformations for train/test sets. We will resize all images to have size (224, 224) as well as convert the images to tensor." }, { "code": null, "e": 1384, "s": 1307, "text": "The ToTensor operation in PyTorch convert all tensors to lie between (0, 1)." }, { "code": null, "e": 1533, "s": 1384, "text": "ToTensor converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]" }, { "code": null, "e": 1761, "s": 1533, "text": "image_transforms = { \"train\": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor() ]), \"test\": transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor()}" }, { "code": null, "e": 1808, "s": 1761, "text": "We 2 dataset folders with us — Train and Test." }, { "code": null, "e": 1861, "s": 1808, "text": "We will further divide our Train set as Train + Val." }, { "code": null, "e": 2397, "s": 1861, "text": "hotdog_dataset = datasets.ImageFolder(root = root_dir + \"train\", transform = image_transforms[\"train\"] )hotdog_dataset###################### OUTPUT ######################Dataset ImageFolder Number of datapoints: 498 Root location: ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/train StandardTransformTransform: Compose( Resize(size=(224, 224), interpolation=PIL.Image.BILINEAR) ToTensor() )" }, { "code": null, "e": 2494, "s": 2397, "text": "The class_to_idx function is pre-built in PyTorch. It returns class ID's present in the dataset." }, { "code": null, "e": 2606, "s": 2494, "text": "hotdog_dataset.class_to_idx###################### OUTPUT ######################{'hot_dog': 0, 'not_hot_dog': 1}" }, { "code": null, "e": 2684, "s": 2606, "text": "We will now construct a reverse of this dictionary; a mapping of ID to class." }, { "code": null, "e": 2751, "s": 2684, "text": "idx2class = {v: k for k, v in hotdog_dataset.class_to_idx.items()}" }, { "code": null, "e": 2972, "s": 2751, "text": "Let’s also write a function that takes in a dataset object and returns a dictionary that contains the count of class samples. We will use this dictionary to construct plots and observe the class distribution in our data." }, { "code": null, "e": 3038, "s": 2972, "text": "get_class_distribution() takes in an argument called dataset_obj." }, { "code": null, "e": 3132, "s": 3038, "text": "We first initialize a count_dict dictionary where counts of all classes are initialized to 0." }, { "code": null, "e": 3250, "s": 3132, "text": "Then, let’s iterate through the dataset and increment the counter by 1 for every class label encountered in the loop." }, { "code": null, "e": 3460, "s": 3250, "text": "plot_from_dict() takes in 3 arguments: a dictionary called dict_obj, plot_title, and **kwargs. We pass in **kwargs because later on, we will construct subplots which require passing the ax argument in Seaborn." }, { "code": null, "e": 3506, "s": 3460, "text": "First convert the dictionary to a data-frame." }, { "code": null, "e": 3536, "s": 3506, "text": "Melt the data frame and plot." }, { "code": null, "e": 4101, "s": 3536, "text": "def get_class_distribution(dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} for _, label_id in dataset_obj: label = idx2class[label_id] count_dict[label] += 1 return count_dictdef plot_from_dict(dict_obj, plot_title, **kwargs): return sns.barplot(data = pd.DataFrame.from_dict([dict_obj]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", **kwargs).set_title(plot_title)plt.figure(figsize=(15,8))plot_from_dict(get_class_distribution(hotdog_dataset), plot_title=\"Entire Dataset (before train/val/test split)\")" }, { "code": null, "e": 4260, "s": 4101, "text": "We use SubsetRandomSampler to make our train and validation loaders. SubsetRandomSampler is used so that each batch receives a random distribution of classes." }, { "code": null, "e": 4428, "s": 4260, "text": "We could’ve also split our dataset into 2 parts — train and val ie. make 2 Subsets. But this is simpler because our data loader will pretty much handle everything now." }, { "code": null, "e": 4493, "s": 4428, "text": "SubsetRandomSampler(indices) takes as input the indices of data." }, { "code": null, "e": 4566, "s": 4493, "text": "We first create our samplers and then we’ll pass it to our data-loaders." }, { "code": null, "e": 4592, "s": 4566, "text": "Create a list of indices." }, { "code": null, "e": 4613, "s": 4592, "text": "Shuffle the indices." }, { "code": null, "e": 4662, "s": 4613, "text": "Split the indices based on train-val percentage." }, { "code": null, "e": 4690, "s": 4662, "text": "Create SubsetRandomSampler." }, { "code": null, "e": 4744, "s": 4690, "text": "Create a list of indices from 0 to length of dataset." }, { "code": null, "e": 4843, "s": 4744, "text": "hotdog_dataset_size = len(hotdog_dataset)hotdog_dataset_indices = list(range(hotdog_dataset_size))" }, { "code": null, "e": 4889, "s": 4843, "text": "Shuffle the list of indices using np.shuffle." }, { "code": null, "e": 4931, "s": 4889, "text": "np.random.shuffle(hotdog_dataset_indices)" }, { "code": null, "e": 5018, "s": 4931, "text": "Create the split index. We choose the split index to be 20% (0.2) of the dataset size." }, { "code": null, "e": 5077, "s": 5018, "text": "val_split_index = int(np.floor(0.2 * hotdog_dataset_size))" }, { "code": null, "e": 5157, "s": 5077, "text": "Slice the lists to obtain 2 lists of indices, one for train and other for test." }, { "code": null, "e": 5216, "s": 5157, "text": "0-----------val_split_index------------------------------n" }, { "code": null, "e": 5246, "s": 5216, "text": "Train => val_split_index to n" }, { "code": null, "e": 5274, "s": 5246, "text": "Val => 0 to val_split_index" }, { "code": null, "e": 5378, "s": 5274, "text": "train_idx, val_idx = hotdog_dataset_indices[val_split_index:], hotdog_dataset_indices[:val_split_index]" }, { "code": null, "e": 5404, "s": 5378, "text": "Finally, create samplers." }, { "code": null, "e": 5493, "s": 5404, "text": "train_sampler = SubsetRandomSampler(train_idx)val_sampler = SubsetRandomSampler(val_idx)" }, { "code": null, "e": 5567, "s": 5493, "text": "Now that we’re done with train and val data, let’s load our test dataset." }, { "code": null, "e": 6122, "s": 5567, "text": "hotdog_dataset_test = datasets.ImageFolder(root = root_dir + \"test\", transform = image_transforms[\"test\"] )hotdog_dataset_test###################### OUTPUT ######################Dataset ImageFolder Number of datapoints: 500 Root location: ../../../data/computer_vision/image_classification/hot-dog-not-hot-dog/test StandardTransformTransform: Compose( Resize(size=(224, 224), interpolation=PIL.Image.BILINEAR) ToTensor() )" }, { "code": null, "e": 6253, "s": 6122, "text": "Now, we will pass the samplers to our dataloader. Note that shuffle=True cannot be used when you're using the SubsetRandomSampler." }, { "code": null, "e": 6534, "s": 6253, "text": "train_loader = DataLoader(dataset=hotdog_dataset, shuffle=False, batch_size=8, sampler=train_sampler)val_loader = DataLoader(dataset=hotdog_dataset, shuffle=False, batch_size=1, sampler=val_sampler)test_loader = DataLoader(dataset=hotdog_dataset_test, shuffle=False, batch_size=1)" }, { "code": null, "e": 6677, "s": 6534, "text": "To explore our train and val data-loaders, let’s create a new function that takes in a data-loader and returns a dictionary with class counts." }, { "code": null, "e": 6723, "s": 6677, "text": "Initialize a dictionary count_dict to all 0s." }, { "code": null, "e": 6830, "s": 6723, "text": "If the batch_size of the dataloader_obj is 1, then loop through the dataloader_obj and update the counter." }, { "code": null, "e": 7035, "s": 6830, "text": "Else, if the batch_size of the dataloader_obj is not 1, then loop through the dataloader_obj to obtain batches. Loop through the batches to obtain individual tensors. Now, updated the counter accordingly." }, { "code": null, "e": 7580, "s": 7035, "text": "def get_class_distribution_loaders(dataloader_obj, dataset_obj): count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()} if dataloader_obj.batch_size == 1: for _,label_id in dataloader_obj: y_idx = label_id.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 else: for _,label_id in dataloader_obj: for idx in label_id: y_idx = idx.item() y_lbl = idx2class[y_idx] count_dict[str(y_lbl)] += 1 return count_dict" }, { "code": null, "e": 7693, "s": 7580, "text": "To plot the class distributions, we will use the plot_from_dict() function defined earlier with the ax argument." }, { "code": null, "e": 7972, "s": 7693, "text": "fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))plot_from_dict(get_class_distribution_loaders(train_loader, hotdog_dataset), plot_title=\"Train Set\", ax=axes[0])plot_from_dict(get_class_distribution_loaders(val_loader, hotdog_dataset), plot_title=\"Val Set\", ax=axes[1])" }, { "code": null, "e": 8056, "s": 7972, "text": "Now that we’ve looked at the class distributions, Let’s now look at a single image." }, { "code": null, "e": 8096, "s": 8056, "text": "single_batch = next(iter(train_loader))" }, { "code": null, "e": 8256, "s": 8096, "text": "single_batch is a list of 2 elements. The first element (0th index) contains the image tensors while the second element (1st index) contains the output labels." }, { "code": null, "e": 8374, "s": 8256, "text": "Here’s the first element of the list which is a tensor. This tensor is of the shape (batch, channels, height, width)." }, { "code": null, "e": 8476, "s": 8374, "text": "single_batch[0].shape###################### OUTPUT ######################torch.Size([8, 3, 224, 224])" }, { "code": null, "e": 8518, "s": 8476, "text": "Here are the output labels for the batch." }, { "code": null, "e": 8778, "s": 8518, "text": "print(\"Output label tensors: \", single_batch[1])print(\"\\nOutput label tensor shape: \", single_batch[1].shape)###################### OUTPUT ######################Output label tensors: tensor([1, 1, 1, 1, 1, 1, 1, 1])Output label tensor shape: torch.Size([8])" }, { "code": null, "e": 8952, "s": 8778, "text": "To plot the image, we’ll use plt.imshow from matloptlib. It expects the image dimension to be (height, width, channels). We'll .permute() our single image tensor to plot it." }, { "code": null, "e": 9132, "s": 8952, "text": "# Selecting the first image tensor from the batch. single_image = single_batch[0][0]single_image.shape###################### OUTPUT ######################torch.Size([3, 224, 224])" }, { "code": null, "e": 9154, "s": 9132, "text": "Let’s view the image." }, { "code": null, "e": 9189, "s": 9154, "text": "plt.imshow(single_image.(1, 2, 0))" }, { "code": null, "e": 9277, "s": 9189, "text": "PyTorch has made it easier for us to plot the images in a grid straight from the batch." }, { "code": null, "e": 9474, "s": 9277, "text": "We first extract out the image tensor from the list (returned by our dataloader) and set nrow. Then we use the plt.imshow() function to plot our grid. Remember to .permute() the tensor dimensions!" }, { "code": null, "e": 9739, "s": 9474, "text": "# We do single_batch[0] because each batch is a list # where the 0th index is the image tensor and 1st index is the output label.single_batch_grid = utils.make_grid(single_batch[0], nrow=4)plt.figure(figsize = (10,10))plt.imshow(single_batch_grid.permute(1, 2, 0))" }, { "code": null, "e": 9870, "s": 9739, "text": "Our architecture is simple. We use 4 blocks of Conv layers. Each block consists ofConvolution + BatchNorm + ReLU + Dropout layers." }, { "code": null, "e": 9941, "s": 9870, "text": "We will not use an FC layer at the end. We'll stick with a Conv layer." }, { "code": null, "e": 11025, "s": 9941, "text": "class HotDogClassifier(nn.Module): def __init__(self): super(HotDogClassifier, self).__init__() self.block1 = self.conv_block(c_in=3, c_out=256, dropout=0.1, kernel_size=5, stride=1, padding=2) self.block2 = self.conv_block(c_in=256, c_out=128, dropout=0.1, kernel_size=3, stride=1, padding=1) self.block3 = self.conv_block(c_in=128, c_out=64, dropout=0.1, kernel_size=3, stride=1, padding=1) self.lastcnn = nn.Conv2d(in_channels=64, out_channels=2, kernel_size=56, stride=1, padding=0) self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) def forward(self, x): x = self.block1(x) x = self.maxpool(x) x = self.block2(x) x = self.block3(x) x = self.maxpool(x) x = self.lastcnn(x) return x def conv_block(self, c_in, c_out, dropout, **kwargs): seq_block = nn.Sequential( nn.Conv2d(in_channels=c_in, out_channels=c_out, **kwargs), nn.BatchNorm2d(num_features=c_out), nn.ReLU(), nn.Dropout2d(p=dropout) ) return seq_block" }, { "code": null, "e": 11087, "s": 11025, "text": "Now we’ll initialize the model, optimizer, and loss function." }, { "code": null, "e": 11125, "s": 11087, "text": "Then we’ll transfer the model to GPU." }, { "code": null, "e": 11376, "s": 11125, "text": "We’re using the nn.CrossEntropyLoss even though it's a binary classification problem. This means, instead of returning a single output of 1/0, we'll treat return 2 values of 0 and 1. More specifically, probabilities of the output being either 1 or 0." }, { "code": null, "e": 11496, "s": 11376, "text": "We don’t have to manually apply a log_softmax layer after our final layer because nn.CrossEntropyLoss does that for us." }, { "code": null, "e": 11566, "s": 11496, "text": "However, we need to apply log_softmax for our validation and testing." }, { "code": null, "e": 12660, "s": 11566, "text": "model = HotDogClassifier()model.to(device)print(model)criterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.008)###################### OUTPUT ######################HotDogClassifier( (block1): Sequential( (0): Conv2d(3, 256, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (block2): Sequential( (0): Conv2d(256, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (block3): Sequential( (0): Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU() (3): Dropout2d(p=0.1, inplace=False) ) (lastcnn): Conv2d(64, 2, kernel_size=(56, 56), stride=(1, 1)) (maxpool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False))" }, { "code": null, "e": 12747, "s": 12660, "text": "Before we start our training, let’s define a function to calculate accuracy per epoch." }, { "code": null, "e": 12891, "s": 12747, "text": "This function takes y_pred and y_test as input arguments. We then apply softmax to y_pred and extract the class which has a higher probability." }, { "code": null, "e": 12986, "s": 12891, "text": "After that, we compare the predicted classes and the actual classes to calculate the accuracy." }, { "code": null, "e": 13274, "s": 12986, "text": "def binary_acc(y_pred, y_test): y_pred_tag = torch.log_softmax(y_pred, dim = 1) _, y_pred_tags = torch.max(y_pred_tag, dim = 1) correct_results_sum = (y_pred_tags == y_test).sum().float() acc = correct_results_sum/y_test.shape[0] acc = torch.round(acc * 100) return acc" }, { "code": null, "e": 13394, "s": 13274, "text": "We’ll also define 2 dictionaries which will store the accuracy/epoch and loss/epoch for both train and validation sets." }, { "code": null, "e": 13487, "s": 13394, "text": "accuracy_stats = { 'train': [], \"val\": []}loss_stats = { 'train': [], \"val\": []}" }, { "code": null, "e": 13510, "s": 13487, "text": "Let’s TRAIN our model!" }, { "code": null, "e": 13982, "s": 13510, "text": "You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you're in training mode. Well, why do we need to do that? If you're using layers such as Dropout or BatchNorm which behave differently during training and evaluation (for eample; not use dropout during evaluation), you need to tell PyTorch to act accordingly. While the default mode in PyTorch is the train, so, you don't explicitly have to write that. But it's good practice." }, { "code": null, "e": 14260, "s": 13982, "text": "Similarly, we’ll call model.eval() when we test our model. We'll see that below. Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss and accuracy per epoch to 0. After every epoch, we'll print out the loss/accuracy and reset it back to 0." }, { "code": null, "e": 14363, "s": 14260, "text": "Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader." }, { "code": null, "e": 14694, "s": 14363, "text": "We do optimizer.zero_grad() before we make any predictions. Since the .backward() function accumulates gradients, we need to set it to 0 manually per mini-batch. From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform backpropagation using loss.backward() and optimizer.step()." }, { "code": null, "e": 14990, "s": 14694, "text": "Finally, we add all the mini-batch losses (and accuracies) to obtain the average loss (and accuracy) for that epoch. We add up all the losses/accuracies for each minibatch and finally divide it by the number of minibatches ie. length of trainloader to obtain the average loss/accuracy per epoch." }, { "code": null, "e": 15286, "s": 14990, "text": "The procedure we follow for training is the exact same for validation except for the fact that we wrap it up in torch.no_grad and not perform any backpropagation. torch.no_grad() tells PyTorch that we do not want to perform back-propagation, which reduces memory usage and speeds up computation." }, { "code": null, "e": 18797, "s": 15286, "text": "print(\"Begin training.\")for e in tqdm(range(1, 21)): # TRAINING train_epoch_loss = 0 train_epoch_acc = 0 model.train() for X_train_batch, y_train_batch in train_loader: X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device) optimizer.zero_grad() y_train_pred = model(X_train_batch).squeeze() train_loss = criterion(y_train_pred, y_train_batch) train_acc = binary_acc(y_train_pred, y_train_batch) train_loss.backward() optimizer.step() train_epoch_loss += train_loss.item() train_epoch_acc += train_acc.item() # VALIDATION with torch.no_grad(): model.eval() val_epoch_loss = 0 val_epoch_acc = 0 for X_val_batch, y_val_batch in val_loader: X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device) y_val_pred = model(X_val_batch).squeeze() y_val_pred = torch.unsqueeze(y_val_pred, 0) val_loss = criterion(y_val_pred, y_val_batch) val_acc = binary_acc(y_val_pred, y_val_batch) val_epoch_loss += val_loss.item() val_epoch_acc += val_acc.item() loss_stats['train'].append(train_epoch_loss/len(train_loader)) loss_stats['val'].append(val_epoch_loss/len(val_loader)) accuracy_stats['train'].append(train_epoch_acc/len(train_loader)) accuracy_stats['val'].append(val_epoch_acc/len(val_loader)) print(f'Epoch {e+0:02}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f} | Train Acc: {train_epoch_acc/len(train_loader):.3f}| Val Acc: {val_epoch_acc/len(val_loader):.3f}')###################### OUTPUT ######################Begin training.Epoch 01: | Train Loss: 113.08463 | Val Loss: 92.26063 | Train Acc: 51.120| Val Acc: 29.000Epoch 02: | Train Loss: 55.47888 | Val Loss: 50.39846 | Train Acc: 63.620| Val Acc: 57.000Epoch 03: | Train Loss: 33.44443 | Val Loss: 20.69457 | Train Acc: 70.500| Val Acc: 71.000Epoch 04: | Train Loss: 18.75201 | Val Loss: 1.50821 | Train Acc: 77.240| Val Acc: 71.000Epoch 05: | Train Loss: 12.88685 | Val Loss: 26.62685 | Train Acc: 75.480| Val Acc: 71.000Epoch 06: | Train Loss: 9.70507 | Val Loss: 3.25360 | Train Acc: 81.080| Val Acc: 86.000Epoch 07: | Train Loss: 11.04334 | Val Loss: 0.00000 | Train Acc: 79.320| Val Acc: 100.000Epoch 08: | Train Loss: 7.16636 | Val Loss: 10.48954 | Train Acc: 83.300| Val Acc: 71.000Epoch 09: | Train Loss: 4.32204 | Val Loss: 0.00001 | Train Acc: 86.400| Val Acc: 100.000Epoch 10: | Train Loss: 2.03338 | Val Loss: 0.00000 | Train Acc: 91.720| Val Acc: 100.000Epoch 11: | Train Loss: 1.68124 | Val Loss: 3.65754 | Train Acc: 92.320| Val Acc: 71.000Epoch 12: | Train Loss: 1.27145 | Val Loss: 5.52111 | Train Acc: 93.320| Val Acc: 86.000Epoch 13: | Train Loss: 0.42285 | Val Loss: 0.00000 | Train Acc: 97.600| Val Acc: 100.000Epoch 14: | Train Loss: 1.03441 | Val Loss: 0.00000 | Train Acc: 94.840| Val Acc: 100.000Epoch 15: | Train Loss: 0.76563 | Val Loss: 0.00000 | Train Acc: 96.340| Val Acc: 100.000Epoch 16: | Train Loss: 0.16889 | Val Loss: 0.00000 | Train Acc: 98.040| Val Acc: 100.000Epoch 17: | Train Loss: 0.42046 | Val Loss: 4.02560 | Train Acc: 96.560| Val Acc: 86.000Epoch 18: | Train Loss: 0.57535 | Val Loss: 0.00000 | Train Acc: 95.640| Val Acc: 100.000Epoch 19: | Train Loss: 0.40181 | Val Loss: 0.00000 | Train Acc: 96.620| Val Acc: 100.000Epoch 20: | Train Loss: 0.92207 | Val Loss: 0.00000 | Train Acc: 95.360| Val Acc: 100.000" }, { "code": null, "e": 18920, "s": 18797, "text": "To plot the loss and accuracy line plots, we again create a dataframe from the accuracy_stats and loss_stats dictionaries." }, { "code": null, "e": 19487, "s": 18920, "text": "train_val_acc_df = pd.DataFrame.from_dict(accuracy_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})train_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(30,10))sns.lineplot(data=train_val_acc_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Train-Val Accuracy/Epoch')sns.lineplot(data=train_val_loss_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Train-Val Loss/Epoch')" }, { "code": null, "e": 19771, "s": 19487, "text": "After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad(), just like we did it for the validation loop above." }, { "code": null, "e": 19904, "s": 19771, "text": "We start by defining a list that will hold our predictions. Then we loop through our batches using the test_loader. For each batch -" }, { "code": null, "e": 19941, "s": 19904, "text": "We move our input mini-batch to GPU." }, { "code": null, "e": 19990, "s": 19941, "text": "We make the predictions using our trained model." }, { "code": null, "e": 20081, "s": 19990, "text": "Apply log_softmax activation to the predictions and pick the index of highest probability." }, { "code": null, "e": 20121, "s": 20081, "text": "Move the batch to the GPU from the CPU." }, { "code": null, "e": 20185, "s": 20121, "text": "Convert the tensor to a numpy object and append it to our list." }, { "code": null, "e": 20542, "s": 20185, "text": "y_pred_list = []y_true_list = []with torch.no_grad(): for x_batch, y_batch in tqdm(test_loader): x_batch, y_batch = x_batch.to(device), y_batch.to(device) y_test_pred = model(x_batch) _, y_pred_tag = torch.max(y_test_pred, dim = 1) y_pred_list.append(y_pred_tag.cpu().numpy()) y_true_list.append(y_batch.cpu().numpy())" }, { "code": null, "e": 20650, "s": 20542, "text": "We’ll flatten out the list so that we can use it as an input to confusion_matrix and classification_report." }, { "code": null, "e": 20739, "s": 20650, "text": "y_pred_list = [i[0][0][0] for i in y_pred_list]y_true_list = [i[0] for i in y_true_list]" }, { "code": null, "e": 20843, "s": 20739, "text": "Finally, we print out the classification report which contains the precision, recall, and the F1 score." }, { "code": null, "e": 21254, "s": 20843, "text": "print(classification_report(y_true_list, y_pred_list))###################### OUTPUT ######################precision recall f1-score support 0 0.90 0.91 0.91 249 1 0.91 0.90 0.91 249 accuracy 0.91 498 macro avg 0.91 0.91 0.91 498weighted avg 0.91 0.91 0.91 498" }, { "code": null, "e": 21324, "s": 21254, "text": "Let’s use the confusion_matrix() function to make a confusion matrix." }, { "code": null, "e": 21447, "s": 21324, "text": "print(confusion_matrix(y_true_list, y_pred_list))###################### OUTPUT ######################[[226 23] [ 24 225]]" }, { "code": null, "e": 21547, "s": 21447, "text": "We create a dataframe from the confusion matrix and plot it as a heatmap using the seaborn library." }, { "code": null, "e": 21766, "s": 21547, "text": "confusion_matrix_df = pd.DataFrame(confusion_matrix(y_true_list, y_pred_list)).rename(columns=idx2class, index=idx2class)fig, ax = plt.subplots(figsize=(7,5)) sns.heatmap(confusion_matrix_df, annot=True, ax=ax)" }, { "code": null, "e": 21844, "s": 21766, "text": "Thank you for reading. Suggestions and constructive criticism are welcome. :)" }, { "code": null, "e": 21945, "s": 21844, "text": "This blog post is a part of the column— “How to train you Neural Net”. You can find the series here." } ]
Handling Overflowing Content using CSS
We can use CSS overflow property to manage/handle the overflowing content of an element. This property allows user to clip content, provide scrollbars to view clipped content, render content outside the container thus the name overflow. Following is the syntax for CSS Overflow property − Selector { overflow: /*value*/ } Let us see an example for CSS overflow property − Live Demo <!DOCTYPE html> <html> <head> <title>CSS Overflow</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } #containerDiv { margin: 0 auto; height: 110px; overflow: scroll; } </style></head> <body> <form> <fieldset> <legend>CSS Overflow</legend> <div id="containerDiv"> This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.</div> <input type="button" onclick="add()" value="Remove Scrollbars"> </fieldset> </form> <script> function add() { document.querySelector('#containerDiv').style.overflow = "hidden"; } </script> </body> </html> Before clicking ‘Remove Scrollbars’ button − After clicking ‘Remove Scrollbars’ button − Let’s see another example for the CSS overflow property − Live Demo <!DOCTYPE html> <html> <head> <title>CSS Overflow</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } #containerDiv { margin: 0 auto; height: 100px; width: 100px; overflow: auto; } </style> </head> <body> <form> <fieldset> <legend>CSS Overflow</legend> <div id="containerDiv"> <img id="image" src="https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg"> </div> <input type="button" onclick="fitHeight()" value="Remove Scrollbars"> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var imgSelect = document.getElementById("image"); var containerDiv = document.getElementById("containerDiv"); function fitHeight() { containerDiv.style.height = imgSelect.height+'px'; containerDiv.style.width = imgSelect.width+'px'; containerDiv.style.overflow = 'hidden'; } </script> </body> </html> Before clicking any button − After clicking ‘Remove Scrollbars’ button −
[ { "code": null, "e": 1299, "s": 1062, "text": "We can use CSS overflow property to manage/handle the overflowing content of an element. This property allows user to clip content, provide scrollbars to view clipped content, render content outside the container thus the name overflow." }, { "code": null, "e": 1351, "s": 1299, "text": "Following is the syntax for CSS Overflow property −" }, { "code": null, "e": 1387, "s": 1351, "text": "Selector {\n overflow: /*value*/\n}" }, { "code": null, "e": 1437, "s": 1387, "text": "Let us see an example for CSS overflow property −" }, { "code": null, "e": 1448, "s": 1437, "text": " Live Demo" }, { "code": null, "e": 2765, "s": 1448, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Overflow</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n#containerDiv {\n margin: 0 auto;\n height: 110px;\n overflow: scroll;\n}\n</style></head>\n<body>\n<form>\n<fieldset>\n<legend>CSS Overflow</legend>\n<div id=\"containerDiv\">\nThis is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.</div>\n<input type=\"button\" onclick=\"add()\" value=\"Remove Scrollbars\">\n</fieldset>\n</form>\n<script>\nfunction add() {\n document.querySelector('#containerDiv').style.overflow = \"hidden\";\n}\n</script>\n</body>\n</html>" }, { "code": null, "e": 2810, "s": 2765, "text": "Before clicking ‘Remove Scrollbars’ button −" }, { "code": null, "e": 2854, "s": 2810, "text": "After clicking ‘Remove Scrollbars’ button −" }, { "code": null, "e": 2912, "s": 2854, "text": "Let’s see another example for the CSS overflow property −" }, { "code": null, "e": 2923, "s": 2912, "text": " Live Demo" }, { "code": null, "e": 3883, "s": 2923, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>CSS Overflow</title>\n<style>\nform {\n width:70%;\n margin: 0 auto;\n text-align: center;\n}\n* {\n padding: 2px;\n margin:5px;\n}\ninput[type=\"button\"] {\n border-radius: 10px;\n}\n#containerDiv {\n margin: 0 auto;\n height: 100px;\n width: 100px;\n overflow: auto;\n}\n</style>\n</head>\n<body>\n<form>\n<fieldset>\n<legend>CSS Overflow</legend>\n<div id=\"containerDiv\">\n<img id=\"image\" src=\"https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg\">\n</div>\n<input type=\"button\" onclick=\"fitHeight()\" value=\"Remove Scrollbars\">\n</fieldset>\n</form>\n<script>\nvar divDisplay = document.getElementById(\"divDisplay\");\nvar imgSelect = document.getElementById(\"image\");\nvar containerDiv = document.getElementById(\"containerDiv\");\nfunction fitHeight() {\n containerDiv.style.height = imgSelect.height+'px';\n containerDiv.style.width = imgSelect.width+'px';\n containerDiv.style.overflow = 'hidden';\n}\n</script>\n</body>\n</html>" }, { "code": null, "e": 3912, "s": 3883, "text": "Before clicking any button −" }, { "code": null, "e": 3956, "s": 3912, "text": "After clicking ‘Remove Scrollbars’ button −" } ]
MySQL Syntax to create Foreign Key?
The syntax to create a foreign key is as follows − alter table yourSecondTableName ADD CONSTRAINT yourConstraintname FOREIGN KEY(yourForeignKeyColumnName) references yourFirstTableName (yourPrimaryKeyColumnName); To understand the above syntax, let us create two tables. The query to create the first table is as follows − mysql> create table Department_Table -> ( -> Department_Id int not null auto_increment primary key, -> Department_Name varchar(30) -> ); Query OK, 0 rows affected (0.83 sec) The query to create the second table is as follows − mysql> create table Employee_Table -> ( -> EmployeeID int not null auto_increment primary key, -> EmployeeName varchar(80), -> Job varchar(30), -> Department_Id int not null references department(departmentID) -> ); Query OK, 0 rows affected (1.12 sec) The above Department_Id int, not null references department(departmentID) does not create a foreign key. Now follow the above syntax to create a foreign key. The query is as follows − mysql> alter table Employee_Table ADD CONSTRAINT fk_Department_Id FOREIGN KEY(Department_Id) -> references Department_Table(Department_Id); Query OK, 0 rows affected (2.82 sec) Records: 0 Duplicates: 0 Warnings:
[ { "code": null, "e": 1113, "s": 1062, "text": "The syntax to create a foreign key is as follows −" }, { "code": null, "e": 1275, "s": 1113, "text": "alter table yourSecondTableName ADD CONSTRAINT yourConstraintname FOREIGN KEY(yourForeignKeyColumnName)\nreferences yourFirstTableName (yourPrimaryKeyColumnName);" }, { "code": null, "e": 1385, "s": 1275, "text": "To understand the above syntax, let us create two tables. The query to create the first table is as follows −" }, { "code": null, "e": 1571, "s": 1385, "text": "mysql> create table Department_Table\n -> (\n -> Department_Id int not null auto_increment primary key,\n -> Department_Name varchar(30)\n -> );\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1624, "s": 1571, "text": "The query to create the second table is as follows −" }, { "code": null, "e": 1895, "s": 1624, "text": "mysql> create table Employee_Table\n -> (\n -> EmployeeID int not null auto_increment primary key,\n -> EmployeeName varchar(80),\n -> Job varchar(30),\n -> Department_Id int not null references department(departmentID)\n -> );\nQuery OK, 0 rows affected (1.12 sec)" }, { "code": null, "e": 2053, "s": 1895, "text": "The above Department_Id int, not null references department(departmentID) does not create a foreign key. Now follow the above syntax to create a foreign key." }, { "code": null, "e": 2079, "s": 2053, "text": "The query is as follows −" }, { "code": null, "e": 2294, "s": 2079, "text": "mysql> alter table Employee_Table ADD CONSTRAINT fk_Department_Id FOREIGN KEY(Department_Id)\n -> references Department_Table(Department_Id);\nQuery OK, 0 rows affected (2.82 sec)\nRecords: 0 Duplicates: 0 Warnings:" } ]
Pytorch LSTMs for time-series data | by Charlie O'Neill | Towards Data Science
You might have noticed that, despite the frequency with which we encounter sequential data in the real world, there isn’t a huge amount of content online showing how to build simple LSTMs from the ground up using the Pytorch functional API. Even the LSTM example on Pytorch’s official documentation only applies it to a natural language problem, which can be disorienting when trying to get these recurrent models working on time series data. In this article, we’ll set a solid foundation for constructing an end-to-end LSTM, from tensor input and output shapes to the LSTM itself. This article is structured with the goal of being able to implement any univariate time-series LSTM. We begin by examining the shortcomings of traditional neural networks for these tasks, and why an LSTM’s input is differently shaped to simple neural nets. We’ll then intuitively describe the mechanics that allow an LSTM to “remember.” With this approximate understanding, we can implement a Pytorch LSTM using a traditional model class structure inheriting from nn.Module, and write a forward method for it. We use this to see if we can get the LSTM to learn a simple sine wave. Finally, we attempt to write code to generalise how we might initialise an LSTM based on the problem at hand, and test it on our previous examples. Let’s suppose we have the following time-series data. Rather than using complicated recurrent models, we’re going to treat the time series as a simple input-output function: the input is the time, and the output is the value of whatever dependent variable we’re measuring. This is essentially just simplifying a univariate time series. You might be wondering there’s any difference between the problem we’ve outlined above, and an actual sequential modelling approach to time series problems (as used in LSTMs). The difference is in the recurrency of the solution. Here, we’re simply passing in the current time step and hoping the network can output the function value. However, in recurrent neural networks, we not only pass in the current input, but also previous outputs. In this way, the network can learn dependencies between previous function values and the current one. Here, the network has no way of learning these dependencies, because we simply don’t input previous outputs into the model. Let’s suppose that we’re trying to model the number of minutes Klay Thompson will play in his return from injury. Steve Kerr, the coach of the Golden State Warriors, doesn’t want Klay to come back and immediately play heavy minutes. Instead, he will start Klay with a few minutes per game, and ramp up the amount of time he’s allowed to play as the season goes on. We’re going to be Klay Thompson’s physio, and we need to predict how many minutes per game Klay will be playing in order to determine how much strapping to put on his knee. Thus, the number of games since returning from injury (representing the input time step) is the independent variable, and Klay Thompson’s number of minutes in the game is the dependent variable. Suppose we observe Klay for 11 games, recording his minutes per game in each outing to get the following data. Here, we’ve generated the minutes per game as a linear relationship with the number of games since returning. We’re going to use 9 samples for our training set, and 2 samples for validation. We know that the relationship between game number and minutes is linear. However, we’re still going to use a non-linear activation function, because that’s the whole point of a neural network. (Otherwise, this would just turn into linear regression: the composition of linear operations is just a linear operation.) As per usual, we use nn.Sequential to build our model with one hidden layer, with 13 hidden neurons. We now need to write a training loop, as we always do when using gradient descent and backpropagation to force a network to learn. To remind you, each training step has several key tasks: Compute the forward pass through the network by applying the model to the training examples.Calculate the loss based on the defined loss function, which compares the model output to the actual training labels.Backpropagate the derivative of the loss with respect to the model parameters through the network. This is done with call .backward() on the loss, after setting the current parameter gradients to zero with .zero_grad().Update the model parameters by subtracting the gradient times the learning rate. This is done with our optimiser, using optimiser.step(). Compute the forward pass through the network by applying the model to the training examples. Calculate the loss based on the defined loss function, which compares the model output to the actual training labels. Backpropagate the derivative of the loss with respect to the model parameters through the network. This is done with call .backward() on the loss, after setting the current parameter gradients to zero with .zero_grad(). Update the model parameters by subtracting the gradient times the learning rate. This is done with our optimiser, using optimiser.step(). Now, all we need to do is instantiate the required objects, including our model, our optimiser, our loss function and the number of epochs we’re going to train for. >>> Epoch 1, Training loss 422.8955, Validation loss 72.3910Epoch 10000, Training loss 0.1970, Validation loss 324.8314Epoch 20000, Training loss 0.1950, Validation loss 323.0615Epoch 30000, Training loss 0.1922, Validation loss 320.4883Epoch 40000, Training loss 0.1883, Validation loss 317.0684Epoch 50000, Training loss 0.1825, Validation loss 313.0166Epoch 60000, Training loss 0.1736, Validation loss 308.5492...Epoch 500000, Training loss 0.0007, Validation loss 299.8014 As we can see, the model is likely overfitting significantly (which could be solved with many techniques, such as regularisation, or lowering the number of model parameters, or enforcing a linear model form). The training loss is essentially zero. Due to the inherent random variation in our dependent variable, the minutes played taper off into a flat curve towards the last few games, leading the model to believes that the relationship more resembles a log rather than a straight line. Although it wasn’t very successful, this initial neural network is a proof-of-concept that we can just develop sequential models out of nothing more than inputting all the time steps together. However, without more information about the past, and without the ability to store and recall this information, model performance on sequential data will be extremely limited. The simplest neural networks make the assumption that the relationship between the input and output is independent of previous output states. It assumes that the function shape can be learnt from the input alone. In cases such as sequential data, this assumption is not true. The function value at any one particular time step can be thought of as directly influenced by the function value at past time steps. There is a temporal dependency between such values. Long-short term memory networks, or LSTMs, are a form of recurrent neural network that are excellent at learning such temporal dependencies. The key to LSTMs is the cell state, which allows information to flow from one cell to another. This represents the LSTM’s memory, which can be updated, altered or forgotten over time. The components of the LSTM that do this updating are called gates, which regulate the information contained by the cell. Gates can be viewed as combinations of neural network layers and pointwise operations. If you don’t already know how LSTMs work, the maths is straightforward and the fundamental LSTM equations are available in the Pytorch docs. There are many great resources online, such as this one. As a quick refresher, here are the four main steps each LSTM cell undertakes: Decide what information to remove from the cell state that is no longer relevant. This is controlled by a neural network layer (with a sigmoid activation function) called the forget gate. We feed the output of the previous cell into the forget gate, which in turn outputs a number between 0 and 1 determining how much or little to forget.Update the cell state with new information. An NN layer called the input gate takes the concatenation of the previous cell’s output and the current input and decides what to update. A tanh layer takes the same concatenation and creates a vector of new candidate values that could be added to the state.Update the old cell state to create a new cell state. We multiply the old state by the value determined in Step 1, forgetting the things we decided to forget earlier. Then we add the new candidate values we found in Step 2. These constitute the new cell state, scaled by how much we decided to update each state value. This is finished for this cell; we can pass this directly to the next cell in the model.Generate the model output based on the previous output and the current input. First, we take our updated cell state and pass it through an NN layer. We then find the output of the output/input vector passed through the sigmoid layer, and then pointwise compose it with the modified cell state. This allows the cell full control over composing the cell state and the current cell inputs, which gives us an appropriate output. Decide what information to remove from the cell state that is no longer relevant. This is controlled by a neural network layer (with a sigmoid activation function) called the forget gate. We feed the output of the previous cell into the forget gate, which in turn outputs a number between 0 and 1 determining how much or little to forget. Update the cell state with new information. An NN layer called the input gate takes the concatenation of the previous cell’s output and the current input and decides what to update. A tanh layer takes the same concatenation and creates a vector of new candidate values that could be added to the state. Update the old cell state to create a new cell state. We multiply the old state by the value determined in Step 1, forgetting the things we decided to forget earlier. Then we add the new candidate values we found in Step 2. These constitute the new cell state, scaled by how much we decided to update each state value. This is finished for this cell; we can pass this directly to the next cell in the model. Generate the model output based on the previous output and the current input. First, we take our updated cell state and pass it through an NN layer. We then find the output of the output/input vector passed through the sigmoid layer, and then pointwise compose it with the modified cell state. This allows the cell full control over composing the cell state and the current cell inputs, which gives us an appropriate output. Note that we give the output twice in the diagram above. One of these outputs is to be stored as a model prediction, for plotting etc. The other is passed to the next LSTM cell, much as the updated cell state is passed to the next LSTM cell. Our problem is to see if an LSTM can “learn” a sine wave. This is actually a relatively famous (read: infamous) example in the Pytorch community. It’s the only example on Pytorch’s Examples Github repository of an LSTM for a time-series problem. However, the example is old, and most people find that the code either doesn’t compile for them, or won’t converge to any sensible output. (A quick Google search gives a litany of Stack Overflow issues and questions just on this example.) Here, we’re going to break down and alter their code step by step. We begin by generating a sample of 100 different sine waves, each with the same frequency and amplitude but beginning at slightly different points on the x-axis. Let’s walk through the code above. N is the number of samples; that is, we are generating 100 different sine waves. Many people intuitively trip up at this point. Since we are used to training a neural network on individual data points, such as the simple Klay Thompson example from above, it is tempting to think of N here as the number of points at which we measure the sine function. This is wrong; we are generating N different sine waves, each with a multitude of points. The LSTM network learns by examining not one sine wave, but many. Next, we instantiate an empty array x. Think of this array as a sample of points along the x-axis. The array has 100 rows (representing the 100 different sine waves), and each row is 1000 elements long (representing L, or the granularity of the sine wave i.e. the number of distinct sampled points in each wave). We then fill x by sampling the first 1000 integers points and then adding a random integer in a certain range governed by T, where x[:] is just syntax to add the integer along rows. Note that we must reshape this second random integer to shape (N, 1) in order for Numpy to be able to broadcast it to each row of x. Finally, we simply apply the Numpy sine function to x, and let broadcasting apply the function to each sample in each row, creating one sine wave per row. We cast it to type float32. We can pick any individual sine wave and plot it using Matplotlib. Let’s pick the first sampled sine wave at index 0. To build the LSTM model, we actually only have one nn module being called for the LSTM cell specifically. First, we’ll present the entire model class (inheriting from nn.Module, as always), and then walk through it piece by piece. The key step in the initialisation is the declaration of a Pytorch LSTMCell. You can find the documentation here. The cell has three main parameters: input_size: the number of expected features in the input x. hidden_size: the number of features in the hidden state h. bias: this defaults to true, and in general we leave it that way. Some of you may be aware of a separate torch.nn class called LSTM. The distinction between the two is not really relevant here, but just know that LSTMCell is more flexible when it comes to defining our own models from scratch using the functional API. Keep in mind that the parameters of the LSTM cell are different from the inputs. The parameters here largely govern the shape of the expected inputs, so that Pytorch can set up the appropriate structure. The inputs are the actual training examples or prediction examples we feed into the cell. We define two LSTM layers using two LSTM cells. Much like a convolutional neural network, the key to setting up input and hidden sizes lies in the way the two layers connect to each other. For the first LSTM cell, we pass in an input of size 1. Recall why this is so: in an LSTM, we don’t need to pass in a sliced array of inputs. We don’t need a sliding window over the data, as the memory and forget gates take care of the cell state for us. We don’t need to specifically hand feed the model with old data each time, because of the model’s ability to recall this information. This is what makes LSTMs so special. We then give this first LSTM cell a hidden size governed by the variable when we declare our class, n_hidden. This number is rather arbitrary; here, we pick 64. As mentioned above, this becomes an output of sorts which we pass to the next LSTM cell, much like in a CNN: the output size of the last step becomes the input size of the next step. In this cell, we thus have an input of size hidden_size, and also a hidden layer of size hidden_size. We then pass this output of size hidden_size to a linear layer, which itself outputs a scalar of size one. We are outputting a scalar, because we are simply trying to predict the function value y at that particular time step. One of the most important things to keep in mind at this stage of constructing the model is the input and output size: what am I mapping from and to? In the forward method, once the individual layers of the LSTM have been instantiated with the correct sizes, we can begin to focus on the actual inputs moving through the network. An LSTM cell takes the following inputs: input, (h_0, c_0). input: a tensor of inputs of shape (batch, input_size), where we declared input_size in the creation of the LSTM cell. h_0: a tensor containing the initial hidden state for each element in the batch, of shape (batch, hidden_size). c_0: a tensor containing the initial cell state for each element in the batch, of shape (batch, hidden_size). To link the two LSTM cells (and the second LSTM cell with the linear, fully-connected layer), we also need to know what an LSTM cell actually outputs: a tensor of shape (h_1, c_1). h_0: a tensor containing the next hidden state for each element in the batch, of shape (batch, hidden_size). c_0: a tensor containing the next cell state for each element in the batch, of shape (batch, hidden_size). Here, our batch size is 100, which is given by the first dimension of our input; hence, we take n_samples = x.size(0). Since we know the shapes of the hidden and cell states are both (batch, hidden_size), we can instantiate a tensor of zeros of this size, and do so for both of our LSTM cells. The next step is arguably the most difficult. We must feed in an appropriately shaped tensor. Here, that would be a tensor of m points, where m is our training size on each sequence. However, in the Pytorch split() method (documentation here), if the parameter split_size_or_sections is not passed in, it will simply split each tensor into chunks of size 1. We want to split this along each individual batch, so our dimension will be the rows, which is equivalent to dimension 1. It’s always a good idea to check the output shape when we’re vectorising an array in this way. Suppose we choose three sine curves for the test set, and use the rest for training. We can check what our training input will look like in our split method: So, for each sample, we’re passing in an array of 97 inputs, with an extra dimension to represent that it comes from a batch. (Pytorch usually operates in this way. Even if we’re passing in a single image to the world’s simplest CNN, Pytorch expects a batch of images, and so we have to use unsqueeze().) We then output a new hidden and cell state. As we know from above, the hidden state output is used as input to the next LSTM cell. The hidden state output from the second cell is then passed to the linear layer. Great — we’ve completed our model predictions based on the actual points we have data for. But the whole point of an LSTM is to predict the future shape of the curve, based on past outputs. So, in the next stage of the forward pass, we’re going to predict the next future time steps. Recall that in the previous loop, we calculated the output to append to our outputs array by passing the second LSTM output through a linear layer. This variable is still in operation — we can access it and pass it to our model again. This is good news, as we can predict the next time step in the future, one time step after the last point we have data for. The model takes its prediction for this final data point as input, and predicts the next data point. We then do this again, with the prediction now being fed as input to the model. In total, we do this future number of times, to produce a curve of length future, in addition to the 1000 predictions we’ve already made on the 1000 points we actually have data for. The last thing we do is concatenate the array of scalar tensors representing our outputs, before returning them. That’s it! We’ve built an LSTM which takes in a certain number of inputs, and, one by one, predicts a certain number of time steps into the future. Defining a training loop in Pytorch is quite homogeneous across a variety of common applications. However, in our case, we can’t really gain an intuitive understanding of how the model is converging by examining the loss. Yes, a low loss is good, but there’s been plenty of times when I’ve gone to look at the model outputs after achieving a low loss and seen absolute garbage predictions. This is usually due to a mistake in my plotting code, or even more likely a mistake in my model declaration. Thus, the most useful tool we can apply to model assessment and debugging is plotting the model predictions at each training step to see if they improve. Our first step is to figure out the shape of our inputs and our targets. We know that our data y has the shape (100, 1000). That is, 100 different sine curves of 1000 points each. Next, we want to figure out what our train-test split is. We’ll save 3 curves for the test set, and so indexing along the first dimension of y we can use the last 97 curves for the training set. Now comes time to think about our model input. One at a time, we want to input the last time step and get a new time step prediction out. To do this, we input the first 999 samples from each sine wave, because inputting the last 1000 would lead to predicting the 1001st time step, which we can’t validate because we don’t have data on it. Similarly, for the training target, we use the first 97 sine waves, and start at the 2nd sample in each wave and use the last 999 samples from each wave; this is because we need a previous time step to actually input to the model — we can’t input nothing. Hence, the starting index for the target in the second dimension (representing the samples in each wave) is 1. This gives us two arrays of shape (97, 999). The test input and test target follow very similar reasoning, except this time, we index only the first three sine waves along the first dimension. Everything else is exactly the same, as we would expect: apart from the batch input size (97 vs 3) we need to have the same input and outputs for train and test sets. We now need to instantiate the main components of our training loop: the model itself, the loss function, and the optimiser. The model is simply an instance of our LSTM class, and the loss function we will use for what amounts to a regression problem is nn.MSELoss(). The only thing different to normal here is our optimiser. Instead of Adam, we will use what is called a limited-memory BFGS algorithm, which essentially boils down to estimating an inverse of the Hessian matrix as a guide through the variable space. You don’t need to worry about the specifics, but you do need to worry about the difference between optim.LBFGS and other optimisers. We’ll cover that in the training loop below. You might be wondering why we’re bothering to switch from a standard optimiser like Adam to this relatively unknown algorithm. An LBFGS solver is a quasi-Newton method which uses the inverse of the Hessian to estimate the curvature of the parameter space. In sequential problems, the parameter space is characterised by an abundance of long, flat valleys, which means that the LBFGS algorithm often outperforms other methods such as Adam, particularly when there is not a huge amount of data. Finally, we get around to constructing the training loop. Fair warning, as much as I’ll try to make this look like a typical Pytorch training loop, there will be some differences. These are mainly in the function we have to pass to the optimiser, closure, which represents the typical forward and backward pass through the network. We update the weights with optimiser.step() by passing in this function. According to Pytorch, the function closure is a callable that reevaluates the model (forward pass), and returns the loss. So this is exactly what we do. The training loop starts out much as other garden-variety training loops do. However, notice that the typical steps of forward and backwards pass are captured in the function closure. This is just an idiosyncrasy of how the optimiser function is designed in Pytorch. We return the loss in closure, and then pass this function to the optimiser during optimiser.step(). And that’s pretty much it for the training step. Next, we want to plot some predictions, so we can sanity-check our results as we go. To do this, we need to take the test input, and pass it through the model. This is where our future parameter we included in the model itself is going to come in handy. Recall that passing in some non-negative integer future to the forward pass through the model will give us future predictions after the last output from the actual samples. This allows us to see if the model generalises into future time steps. We then detach this output from the current computational graph and store it as a numpy array. Finally, we write some simple code to plot the model’s predictions on the test set at each epoch. There are only three test sine curves, so we only need to call our draw function three times (we’ll draw each curve in a different colour). The plotted lines indicate future predictions, and the solid lines indicate predictions in the current range of the data. The predictions clearly improve over time, as well as the loss going down. Our model works: by the 8th epoch, the model has learnt the sine wave. However, if you keep training the model, you might see the predictions start to do something funny. This is because, at each time step, the LSTM relies on outputs from the previous time step. If the prediction changes slightly for the 1001st prediction, this will perturb the predictions all the way up to prediction 2000, resulting in a nonsensical curve. There are many ways to counter this, but they are beyond the scope of this article. The best strategy right now would be to watch the plots to see if this error accumulation starts happening. Then, you can either go back to an earlier epoch, or train past it and see what happens. If you’re having trouble getting your LSTM to converge, here’s a few things you can try: Lower the number of model parameters (maybe even down to 15) by changing the size of the hidden layer. This reduces the model search space. Try downsampling from the first LSTM cell to the second by reducing the hidden_size passed to the second cell. You could also do this from the second LSTM cell to the linear fully-connected layer. Add batchnorm regularisation, which limits the size of the weights by placing penalties on larger weight values, giving the loss a smoother topography. Add dropout, which zeros out a random fraction of neuronal outputs across the whole model at each epoch. This generates slightly different models each time, meaning the model is forced to rely on individual neurons less. If you implement the last two strategies, remember to call model.train() to instantiate the regularisation during training, and turn off the regularisation during prediction and evaluation using model.eval(). This whole exercise is pointless if we still can’t apply an LSTM to other shapes of input. Let’s generate some new data, except this time, we’ll randomly generate the number of curves and the samples in each curve. We won’t know what the actual values of these parameters are, and so this is a perfect way to see if we can construct an LSTM based on the relationships between input and output shapes. We could then change the following input and output shapes by determining the percentage of samples in each curve we’d like to use for the training set. The input and output shapes thus become: You can verify that this works by running these inputs and targets through the LSTM (hint: make sure you instantiate a variable for future based on the length of the input). Let’s see if we can apply this to the original Klay Thompson example. We need to generate more than one set of minutes if we’re going to feed it to our LSTM. That is, we’re going to generate 100 different hypothetical sets of minutes that Klay Thompson played in 100 different hypothetical worlds. We’ll feed 95 of these in for training, and plot three of the remaining five to see how our model is learning. After using the code above to reshape the inputs and outputs based on L and N, we run the model and achieve the following: This gives us the following images (we only show the first and last): Very interesting! Initially, the LSTM also thinks the curve is logarithmic. Whilst it figures out that the curve is linear on the first 11 games after a bit of training, it insists on providing a logarithmic curve for future games. What is so fascinating about that is that the LSTM is right — Klay can’t keep linearly increasing his game time, as a basketball game only goes for 48 minutes, and most processes such as this are logarithmic anyway. Obviously, there’s no way that the LSTM could know this, but regardless, it’s interesting to see how the model ends up interpreting our toy data. A future task could be to play around with the hyperparameters of the LSTM to see if it is possible to make it learn a linear function for future time steps as well. Additionally, I like to create a Python class to store all these functions in one spot. Then, you can create an object with the data, and you can write functions which read the shape of the data, and feed it to the appropriate LSTM constructors. In summary, creating an LSTM for univariate time series data in Pytorch doesn’t need to be overly complicated. However, the lack of available resources online (particularly resources that don’t focus on natural language forms of sequential data) make it difficult to learn how to construct such recurrent models. Hopefully, this article provided guidance on setting up your inputs and targets, writing a Pytorch class for the LSTM forward method, defining a training loop with the quirks of our new optimiser, and debugging using visual tools such as plotting. If you would like to learn more about the maths behind the LSTM cell, I highly recommend this article which sets out the fundamental equations of LSTMs beautifully (I have no connection to the author). I also recommend attempting to adapt the above code to multivariate time-series. All the core ideas are the same — you just need to think about how you might expand the dimensionality of the input.
[ { "code": null, "e": 748, "s": 166, "text": "You might have noticed that, despite the frequency with which we encounter sequential data in the real world, there isn’t a huge amount of content online showing how to build simple LSTMs from the ground up using the Pytorch functional API. Even the LSTM example on Pytorch’s official documentation only applies it to a natural language problem, which can be disorienting when trying to get these recurrent models working on time series data. In this article, we’ll set a solid foundation for constructing an end-to-end LSTM, from tensor input and output shapes to the LSTM itself." }, { "code": null, "e": 1477, "s": 748, "text": "This article is structured with the goal of being able to implement any univariate time-series LSTM. We begin by examining the shortcomings of traditional neural networks for these tasks, and why an LSTM’s input is differently shaped to simple neural nets. We’ll then intuitively describe the mechanics that allow an LSTM to “remember.” With this approximate understanding, we can implement a Pytorch LSTM using a traditional model class structure inheriting from nn.Module, and write a forward method for it. We use this to see if we can get the LSTM to learn a simple sine wave. Finally, we attempt to write code to generalise how we might initialise an LSTM based on the problem at hand, and test it on our previous examples." }, { "code": null, "e": 1813, "s": 1477, "text": "Let’s suppose we have the following time-series data. Rather than using complicated recurrent models, we’re going to treat the time series as a simple input-output function: the input is the time, and the output is the value of whatever dependent variable we’re measuring. This is essentially just simplifying a univariate time series." }, { "code": null, "e": 2479, "s": 1813, "text": "You might be wondering there’s any difference between the problem we’ve outlined above, and an actual sequential modelling approach to time series problems (as used in LSTMs). The difference is in the recurrency of the solution. Here, we’re simply passing in the current time step and hoping the network can output the function value. However, in recurrent neural networks, we not only pass in the current input, but also previous outputs. In this way, the network can learn dependencies between previous function values and the current one. Here, the network has no way of learning these dependencies, because we simply don’t input previous outputs into the model." }, { "code": null, "e": 3017, "s": 2479, "text": "Let’s suppose that we’re trying to model the number of minutes Klay Thompson will play in his return from injury. Steve Kerr, the coach of the Golden State Warriors, doesn’t want Klay to come back and immediately play heavy minutes. Instead, he will start Klay with a few minutes per game, and ramp up the amount of time he’s allowed to play as the season goes on. We’re going to be Klay Thompson’s physio, and we need to predict how many minutes per game Klay will be playing in order to determine how much strapping to put on his knee." }, { "code": null, "e": 3323, "s": 3017, "text": "Thus, the number of games since returning from injury (representing the input time step) is the independent variable, and Klay Thompson’s number of minutes in the game is the dependent variable. Suppose we observe Klay for 11 games, recording his minutes per game in each outing to get the following data." }, { "code": null, "e": 3514, "s": 3323, "text": "Here, we’ve generated the minutes per game as a linear relationship with the number of games since returning. We’re going to use 9 samples for our training set, and 2 samples for validation." }, { "code": null, "e": 3931, "s": 3514, "text": "We know that the relationship between game number and minutes is linear. However, we’re still going to use a non-linear activation function, because that’s the whole point of a neural network. (Otherwise, this would just turn into linear regression: the composition of linear operations is just a linear operation.) As per usual, we use nn.Sequential to build our model with one hidden layer, with 13 hidden neurons." }, { "code": null, "e": 4119, "s": 3931, "text": "We now need to write a training loop, as we always do when using gradient descent and backpropagation to force a network to learn. To remind you, each training step has several key tasks:" }, { "code": null, "e": 4685, "s": 4119, "text": "Compute the forward pass through the network by applying the model to the training examples.Calculate the loss based on the defined loss function, which compares the model output to the actual training labels.Backpropagate the derivative of the loss with respect to the model parameters through the network. This is done with call .backward() on the loss, after setting the current parameter gradients to zero with .zero_grad().Update the model parameters by subtracting the gradient times the learning rate. This is done with our optimiser, using optimiser.step()." }, { "code": null, "e": 4778, "s": 4685, "text": "Compute the forward pass through the network by applying the model to the training examples." }, { "code": null, "e": 4896, "s": 4778, "text": "Calculate the loss based on the defined loss function, which compares the model output to the actual training labels." }, { "code": null, "e": 5116, "s": 4896, "text": "Backpropagate the derivative of the loss with respect to the model parameters through the network. This is done with call .backward() on the loss, after setting the current parameter gradients to zero with .zero_grad()." }, { "code": null, "e": 5254, "s": 5116, "text": "Update the model parameters by subtracting the gradient times the learning rate. This is done with our optimiser, using optimiser.step()." }, { "code": null, "e": 5419, "s": 5254, "text": "Now, all we need to do is instantiate the required objects, including our model, our optimiser, our loss function and the number of epochs we’re going to train for." }, { "code": null, "e": 5897, "s": 5419, "text": ">>> Epoch 1, Training loss 422.8955, Validation loss 72.3910Epoch 10000, Training loss 0.1970, Validation loss 324.8314Epoch 20000, Training loss 0.1950, Validation loss 323.0615Epoch 30000, Training loss 0.1922, Validation loss 320.4883Epoch 40000, Training loss 0.1883, Validation loss 317.0684Epoch 50000, Training loss 0.1825, Validation loss 313.0166Epoch 60000, Training loss 0.1736, Validation loss 308.5492...Epoch 500000, Training loss 0.0007, Validation loss 299.8014" }, { "code": null, "e": 6386, "s": 5897, "text": "As we can see, the model is likely overfitting significantly (which could be solved with many techniques, such as regularisation, or lowering the number of model parameters, or enforcing a linear model form). The training loss is essentially zero. Due to the inherent random variation in our dependent variable, the minutes played taper off into a flat curve towards the last few games, leading the model to believes that the relationship more resembles a log rather than a straight line." }, { "code": null, "e": 6755, "s": 6386, "text": "Although it wasn’t very successful, this initial neural network is a proof-of-concept that we can just develop sequential models out of nothing more than inputting all the time steps together. However, without more information about the past, and without the ability to store and recall this information, model performance on sequential data will be extremely limited." }, { "code": null, "e": 7358, "s": 6755, "text": "The simplest neural networks make the assumption that the relationship between the input and output is independent of previous output states. It assumes that the function shape can be learnt from the input alone. In cases such as sequential data, this assumption is not true. The function value at any one particular time step can be thought of as directly influenced by the function value at past time steps. There is a temporal dependency between such values. Long-short term memory networks, or LSTMs, are a form of recurrent neural network that are excellent at learning such temporal dependencies." }, { "code": null, "e": 7750, "s": 7358, "text": "The key to LSTMs is the cell state, which allows information to flow from one cell to another. This represents the LSTM’s memory, which can be updated, altered or forgotten over time. The components of the LSTM that do this updating are called gates, which regulate the information contained by the cell. Gates can be viewed as combinations of neural network layers and pointwise operations." }, { "code": null, "e": 8026, "s": 7750, "text": "If you don’t already know how LSTMs work, the maths is straightforward and the fundamental LSTM equations are available in the Pytorch docs. There are many great resources online, such as this one. As a quick refresher, here are the four main steps each LSTM cell undertakes:" }, { "code": null, "e": 9498, "s": 8026, "text": "Decide what information to remove from the cell state that is no longer relevant. This is controlled by a neural network layer (with a sigmoid activation function) called the forget gate. We feed the output of the previous cell into the forget gate, which in turn outputs a number between 0 and 1 determining how much or little to forget.Update the cell state with new information. An NN layer called the input gate takes the concatenation of the previous cell’s output and the current input and decides what to update. A tanh layer takes the same concatenation and creates a vector of new candidate values that could be added to the state.Update the old cell state to create a new cell state. We multiply the old state by the value determined in Step 1, forgetting the things we decided to forget earlier. Then we add the new candidate values we found in Step 2. These constitute the new cell state, scaled by how much we decided to update each state value. This is finished for this cell; we can pass this directly to the next cell in the model.Generate the model output based on the previous output and the current input. First, we take our updated cell state and pass it through an NN layer. We then find the output of the output/input vector passed through the sigmoid layer, and then pointwise compose it with the modified cell state. This allows the cell full control over composing the cell state and the current cell inputs, which gives us an appropriate output." }, { "code": null, "e": 9837, "s": 9498, "text": "Decide what information to remove from the cell state that is no longer relevant. This is controlled by a neural network layer (with a sigmoid activation function) called the forget gate. We feed the output of the previous cell into the forget gate, which in turn outputs a number between 0 and 1 determining how much or little to forget." }, { "code": null, "e": 10140, "s": 9837, "text": "Update the cell state with new information. An NN layer called the input gate takes the concatenation of the previous cell’s output and the current input and decides what to update. A tanh layer takes the same concatenation and creates a vector of new candidate values that could be added to the state." }, { "code": null, "e": 10548, "s": 10140, "text": "Update the old cell state to create a new cell state. We multiply the old state by the value determined in Step 1, forgetting the things we decided to forget earlier. Then we add the new candidate values we found in Step 2. These constitute the new cell state, scaled by how much we decided to update each state value. This is finished for this cell; we can pass this directly to the next cell in the model." }, { "code": null, "e": 10973, "s": 10548, "text": "Generate the model output based on the previous output and the current input. First, we take our updated cell state and pass it through an NN layer. We then find the output of the output/input vector passed through the sigmoid layer, and then pointwise compose it with the modified cell state. This allows the cell full control over composing the cell state and the current cell inputs, which gives us an appropriate output." }, { "code": null, "e": 11215, "s": 10973, "text": "Note that we give the output twice in the diagram above. One of these outputs is to be stored as a model prediction, for plotting etc. The other is passed to the next LSTM cell, much as the updated cell state is passed to the next LSTM cell." }, { "code": null, "e": 11767, "s": 11215, "text": "Our problem is to see if an LSTM can “learn” a sine wave. This is actually a relatively famous (read: infamous) example in the Pytorch community. It’s the only example on Pytorch’s Examples Github repository of an LSTM for a time-series problem. However, the example is old, and most people find that the code either doesn’t compile for them, or won’t converge to any sensible output. (A quick Google search gives a litany of Stack Overflow issues and questions just on this example.) Here, we’re going to break down and alter their code step by step." }, { "code": null, "e": 11929, "s": 11767, "text": "We begin by generating a sample of 100 different sine waves, each with the same frequency and amplitude but beginning at slightly different points on the x-axis." }, { "code": null, "e": 12472, "s": 11929, "text": "Let’s walk through the code above. N is the number of samples; that is, we are generating 100 different sine waves. Many people intuitively trip up at this point. Since we are used to training a neural network on individual data points, such as the simple Klay Thompson example from above, it is tempting to think of N here as the number of points at which we measure the sine function. This is wrong; we are generating N different sine waves, each with a multitude of points. The LSTM network learns by examining not one sine wave, but many." }, { "code": null, "e": 13100, "s": 12472, "text": "Next, we instantiate an empty array x. Think of this array as a sample of points along the x-axis. The array has 100 rows (representing the 100 different sine waves), and each row is 1000 elements long (representing L, or the granularity of the sine wave i.e. the number of distinct sampled points in each wave). We then fill x by sampling the first 1000 integers points and then adding a random integer in a certain range governed by T, where x[:] is just syntax to add the integer along rows. Note that we must reshape this second random integer to shape (N, 1) in order for Numpy to be able to broadcast it to each row of x." }, { "code": null, "e": 13401, "s": 13100, "text": "Finally, we simply apply the Numpy sine function to x, and let broadcasting apply the function to each sample in each row, creating one sine wave per row. We cast it to type float32. We can pick any individual sine wave and plot it using Matplotlib. Let’s pick the first sampled sine wave at index 0." }, { "code": null, "e": 13632, "s": 13401, "text": "To build the LSTM model, we actually only have one nn module being called for the LSTM cell specifically. First, we’ll present the entire model class (inheriting from nn.Module, as always), and then walk through it piece by piece." }, { "code": null, "e": 13782, "s": 13632, "text": "The key step in the initialisation is the declaration of a Pytorch LSTMCell. You can find the documentation here. The cell has three main parameters:" }, { "code": null, "e": 13842, "s": 13782, "text": "input_size: the number of expected features in the input x." }, { "code": null, "e": 13901, "s": 13842, "text": "hidden_size: the number of features in the hidden state h." }, { "code": null, "e": 13967, "s": 13901, "text": "bias: this defaults to true, and in general we leave it that way." }, { "code": null, "e": 14220, "s": 13967, "text": "Some of you may be aware of a separate torch.nn class called LSTM. The distinction between the two is not really relevant here, but just know that LSTMCell is more flexible when it comes to defining our own models from scratch using the functional API." }, { "code": null, "e": 14514, "s": 14220, "text": "Keep in mind that the parameters of the LSTM cell are different from the inputs. The parameters here largely govern the shape of the expected inputs, so that Pytorch can set up the appropriate structure. The inputs are the actual training examples or prediction examples we feed into the cell." }, { "code": null, "e": 15129, "s": 14514, "text": "We define two LSTM layers using two LSTM cells. Much like a convolutional neural network, the key to setting up input and hidden sizes lies in the way the two layers connect to each other. For the first LSTM cell, we pass in an input of size 1. Recall why this is so: in an LSTM, we don’t need to pass in a sliced array of inputs. We don’t need a sliding window over the data, as the memory and forget gates take care of the cell state for us. We don’t need to specifically hand feed the model with old data each time, because of the model’s ability to recall this information. This is what makes LSTMs so special." }, { "code": null, "e": 15801, "s": 15129, "text": "We then give this first LSTM cell a hidden size governed by the variable when we declare our class, n_hidden. This number is rather arbitrary; here, we pick 64. As mentioned above, this becomes an output of sorts which we pass to the next LSTM cell, much like in a CNN: the output size of the last step becomes the input size of the next step. In this cell, we thus have an input of size hidden_size, and also a hidden layer of size hidden_size. We then pass this output of size hidden_size to a linear layer, which itself outputs a scalar of size one. We are outputting a scalar, because we are simply trying to predict the function value y at that particular time step." }, { "code": null, "e": 15951, "s": 15801, "text": "One of the most important things to keep in mind at this stage of constructing the model is the input and output size: what am I mapping from and to?" }, { "code": null, "e": 16191, "s": 15951, "text": "In the forward method, once the individual layers of the LSTM have been instantiated with the correct sizes, we can begin to focus on the actual inputs moving through the network. An LSTM cell takes the following inputs: input, (h_0, c_0)." }, { "code": null, "e": 16310, "s": 16191, "text": "input: a tensor of inputs of shape (batch, input_size), where we declared input_size in the creation of the LSTM cell." }, { "code": null, "e": 16422, "s": 16310, "text": "h_0: a tensor containing the initial hidden state for each element in the batch, of shape (batch, hidden_size)." }, { "code": null, "e": 16532, "s": 16422, "text": "c_0: a tensor containing the initial cell state for each element in the batch, of shape (batch, hidden_size)." }, { "code": null, "e": 16713, "s": 16532, "text": "To link the two LSTM cells (and the second LSTM cell with the linear, fully-connected layer), we also need to know what an LSTM cell actually outputs: a tensor of shape (h_1, c_1)." }, { "code": null, "e": 16822, "s": 16713, "text": "h_0: a tensor containing the next hidden state for each element in the batch, of shape (batch, hidden_size)." }, { "code": null, "e": 16929, "s": 16822, "text": "c_0: a tensor containing the next cell state for each element in the batch, of shape (batch, hidden_size)." }, { "code": null, "e": 17223, "s": 16929, "text": "Here, our batch size is 100, which is given by the first dimension of our input; hence, we take n_samples = x.size(0). Since we know the shapes of the hidden and cell states are both (batch, hidden_size), we can instantiate a tensor of zeros of this size, and do so for both of our LSTM cells." }, { "code": null, "e": 17703, "s": 17223, "text": "The next step is arguably the most difficult. We must feed in an appropriately shaped tensor. Here, that would be a tensor of m points, where m is our training size on each sequence. However, in the Pytorch split() method (documentation here), if the parameter split_size_or_sections is not passed in, it will simply split each tensor into chunks of size 1. We want to split this along each individual batch, so our dimension will be the rows, which is equivalent to dimension 1." }, { "code": null, "e": 17956, "s": 17703, "text": "It’s always a good idea to check the output shape when we’re vectorising an array in this way. Suppose we choose three sine curves for the test set, and use the rest for training. We can check what our training input will look like in our split method:" }, { "code": null, "e": 18473, "s": 17956, "text": "So, for each sample, we’re passing in an array of 97 inputs, with an extra dimension to represent that it comes from a batch. (Pytorch usually operates in this way. Even if we’re passing in a single image to the world’s simplest CNN, Pytorch expects a batch of images, and so we have to use unsqueeze().) We then output a new hidden and cell state. As we know from above, the hidden state output is used as input to the next LSTM cell. The hidden state output from the second cell is then passed to the linear layer." }, { "code": null, "e": 19217, "s": 18473, "text": "Great — we’ve completed our model predictions based on the actual points we have data for. But the whole point of an LSTM is to predict the future shape of the curve, based on past outputs. So, in the next stage of the forward pass, we’re going to predict the next future time steps. Recall that in the previous loop, we calculated the output to append to our outputs array by passing the second LSTM output through a linear layer. This variable is still in operation — we can access it and pass it to our model again. This is good news, as we can predict the next time step in the future, one time step after the last point we have data for. The model takes its prediction for this final data point as input, and predicts the next data point." }, { "code": null, "e": 19480, "s": 19217, "text": "We then do this again, with the prediction now being fed as input to the model. In total, we do this future number of times, to produce a curve of length future, in addition to the 1000 predictions we’ve already made on the 1000 points we actually have data for." }, { "code": null, "e": 19741, "s": 19480, "text": "The last thing we do is concatenate the array of scalar tensors representing our outputs, before returning them. That’s it! We’ve built an LSTM which takes in a certain number of inputs, and, one by one, predicts a certain number of time steps into the future." }, { "code": null, "e": 20394, "s": 19741, "text": "Defining a training loop in Pytorch is quite homogeneous across a variety of common applications. However, in our case, we can’t really gain an intuitive understanding of how the model is converging by examining the loss. Yes, a low loss is good, but there’s been plenty of times when I’ve gone to look at the model outputs after achieving a low loss and seen absolute garbage predictions. This is usually due to a mistake in my plotting code, or even more likely a mistake in my model declaration. Thus, the most useful tool we can apply to model assessment and debugging is plotting the model predictions at each training step to see if they improve." }, { "code": null, "e": 20769, "s": 20394, "text": "Our first step is to figure out the shape of our inputs and our targets. We know that our data y has the shape (100, 1000). That is, 100 different sine curves of 1000 points each. Next, we want to figure out what our train-test split is. We’ll save 3 curves for the test set, and so indexing along the first dimension of y we can use the last 97 curves for the training set." }, { "code": null, "e": 21520, "s": 20769, "text": "Now comes time to think about our model input. One at a time, we want to input the last time step and get a new time step prediction out. To do this, we input the first 999 samples from each sine wave, because inputting the last 1000 would lead to predicting the 1001st time step, which we can’t validate because we don’t have data on it. Similarly, for the training target, we use the first 97 sine waves, and start at the 2nd sample in each wave and use the last 999 samples from each wave; this is because we need a previous time step to actually input to the model — we can’t input nothing. Hence, the starting index for the target in the second dimension (representing the samples in each wave) is 1. This gives us two arrays of shape (97, 999)." }, { "code": null, "e": 21835, "s": 21520, "text": "The test input and test target follow very similar reasoning, except this time, we index only the first three sine waves along the first dimension. Everything else is exactly the same, as we would expect: apart from the batch input size (97 vs 3) we need to have the same input and outputs for train and test sets." }, { "code": null, "e": 22531, "s": 21835, "text": "We now need to instantiate the main components of our training loop: the model itself, the loss function, and the optimiser. The model is simply an instance of our LSTM class, and the loss function we will use for what amounts to a regression problem is nn.MSELoss(). The only thing different to normal here is our optimiser. Instead of Adam, we will use what is called a limited-memory BFGS algorithm, which essentially boils down to estimating an inverse of the Hessian matrix as a guide through the variable space. You don’t need to worry about the specifics, but you do need to worry about the difference between optim.LBFGS and other optimisers. We’ll cover that in the training loop below." }, { "code": null, "e": 23024, "s": 22531, "text": "You might be wondering why we’re bothering to switch from a standard optimiser like Adam to this relatively unknown algorithm. An LBFGS solver is a quasi-Newton method which uses the inverse of the Hessian to estimate the curvature of the parameter space. In sequential problems, the parameter space is characterised by an abundance of long, flat valleys, which means that the LBFGS algorithm often outperforms other methods such as Adam, particularly when there is not a huge amount of data." }, { "code": null, "e": 23582, "s": 23024, "text": "Finally, we get around to constructing the training loop. Fair warning, as much as I’ll try to make this look like a typical Pytorch training loop, there will be some differences. These are mainly in the function we have to pass to the optimiser, closure, which represents the typical forward and backward pass through the network. We update the weights with optimiser.step() by passing in this function. According to Pytorch, the function closure is a callable that reevaluates the model (forward pass), and returns the loss. So this is exactly what we do." }, { "code": null, "e": 23999, "s": 23582, "text": "The training loop starts out much as other garden-variety training loops do. However, notice that the typical steps of forward and backwards pass are captured in the function closure. This is just an idiosyncrasy of how the optimiser function is designed in Pytorch. We return the loss in closure, and then pass this function to the optimiser during optimiser.step(). And that’s pretty much it for the training step." }, { "code": null, "e": 24592, "s": 23999, "text": "Next, we want to plot some predictions, so we can sanity-check our results as we go. To do this, we need to take the test input, and pass it through the model. This is where our future parameter we included in the model itself is going to come in handy. Recall that passing in some non-negative integer future to the forward pass through the model will give us future predictions after the last output from the actual samples. This allows us to see if the model generalises into future time steps. We then detach this output from the current computational graph and store it as a numpy array." }, { "code": null, "e": 24952, "s": 24592, "text": "Finally, we write some simple code to plot the model’s predictions on the test set at each epoch. There are only three test sine curves, so we only need to call our draw function three times (we’ll draw each curve in a different colour). The plotted lines indicate future predictions, and the solid lines indicate predictions in the current range of the data." }, { "code": null, "e": 25736, "s": 24952, "text": "The predictions clearly improve over time, as well as the loss going down. Our model works: by the 8th epoch, the model has learnt the sine wave. However, if you keep training the model, you might see the predictions start to do something funny. This is because, at each time step, the LSTM relies on outputs from the previous time step. If the prediction changes slightly for the 1001st prediction, this will perturb the predictions all the way up to prediction 2000, resulting in a nonsensical curve. There are many ways to counter this, but they are beyond the scope of this article. The best strategy right now would be to watch the plots to see if this error accumulation starts happening. Then, you can either go back to an earlier epoch, or train past it and see what happens." }, { "code": null, "e": 25825, "s": 25736, "text": "If you’re having trouble getting your LSTM to converge, here’s a few things you can try:" }, { "code": null, "e": 25965, "s": 25825, "text": "Lower the number of model parameters (maybe even down to 15) by changing the size of the hidden layer. This reduces the model search space." }, { "code": null, "e": 26162, "s": 25965, "text": "Try downsampling from the first LSTM cell to the second by reducing the hidden_size passed to the second cell. You could also do this from the second LSTM cell to the linear fully-connected layer." }, { "code": null, "e": 26314, "s": 26162, "text": "Add batchnorm regularisation, which limits the size of the weights by placing penalties on larger weight values, giving the loss a smoother topography." }, { "code": null, "e": 26535, "s": 26314, "text": "Add dropout, which zeros out a random fraction of neuronal outputs across the whole model at each epoch. This generates slightly different models each time, meaning the model is forced to rely on individual neurons less." }, { "code": null, "e": 26744, "s": 26535, "text": "If you implement the last two strategies, remember to call model.train() to instantiate the regularisation during training, and turn off the regularisation during prediction and evaluation using model.eval()." }, { "code": null, "e": 27145, "s": 26744, "text": "This whole exercise is pointless if we still can’t apply an LSTM to other shapes of input. Let’s generate some new data, except this time, we’ll randomly generate the number of curves and the samples in each curve. We won’t know what the actual values of these parameters are, and so this is a perfect way to see if we can construct an LSTM based on the relationships between input and output shapes." }, { "code": null, "e": 27298, "s": 27145, "text": "We could then change the following input and output shapes by determining the percentage of samples in each curve we’d like to use for the training set." }, { "code": null, "e": 27339, "s": 27298, "text": "The input and output shapes thus become:" }, { "code": null, "e": 27513, "s": 27339, "text": "You can verify that this works by running these inputs and targets through the LSTM (hint: make sure you instantiate a variable for future based on the length of the input)." }, { "code": null, "e": 27922, "s": 27513, "text": "Let’s see if we can apply this to the original Klay Thompson example. We need to generate more than one set of minutes if we’re going to feed it to our LSTM. That is, we’re going to generate 100 different hypothetical sets of minutes that Klay Thompson played in 100 different hypothetical worlds. We’ll feed 95 of these in for training, and plot three of the remaining five to see how our model is learning." }, { "code": null, "e": 28045, "s": 27922, "text": "After using the code above to reshape the inputs and outputs based on L and N, we run the model and achieve the following:" }, { "code": null, "e": 28115, "s": 28045, "text": "This gives us the following images (we only show the first and last):" }, { "code": null, "e": 29121, "s": 28115, "text": "Very interesting! Initially, the LSTM also thinks the curve is logarithmic. Whilst it figures out that the curve is linear on the first 11 games after a bit of training, it insists on providing a logarithmic curve for future games. What is so fascinating about that is that the LSTM is right — Klay can’t keep linearly increasing his game time, as a basketball game only goes for 48 minutes, and most processes such as this are logarithmic anyway. Obviously, there’s no way that the LSTM could know this, but regardless, it’s interesting to see how the model ends up interpreting our toy data. A future task could be to play around with the hyperparameters of the LSTM to see if it is possible to make it learn a linear function for future time steps as well. Additionally, I like to create a Python class to store all these functions in one spot. Then, you can create an object with the data, and you can write functions which read the shape of the data, and feed it to the appropriate LSTM constructors." }, { "code": null, "e": 29682, "s": 29121, "text": "In summary, creating an LSTM for univariate time series data in Pytorch doesn’t need to be overly complicated. However, the lack of available resources online (particularly resources that don’t focus on natural language forms of sequential data) make it difficult to learn how to construct such recurrent models. Hopefully, this article provided guidance on setting up your inputs and targets, writing a Pytorch class for the LSTM forward method, defining a training loop with the quirks of our new optimiser, and debugging using visual tools such as plotting." } ]
Find number of days between two given dates | Practice | GeeksforGeeks
Given two dates, find the total number of days between them. Note: The system follows Gregorian calender from the beginning of time. Example 1: Input: d1 = 10, m1 = 2, y1 = 2014 d2 = 10, m2 = 3, y2 = 2015 Output: 393 Explanation: By counting manually, we find out there are 393 days between the two dates. Example 2: Input: d1 = 10, m1 = 2, y1 = 2001 d2 = 10, m2 = 2, y2 = 2002 Output: 365 Explanation: By counting manually, we find out there are 365 days between the two dates. Your Task: You don't need to read input or print anything. Your task is to complete the function noOfDays() which takes Integers d1,m1,y1 for the first date and d2,m2,y2 as the second date as input and returns the answer. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= d1,d2 <= 31 1 <= m1,m2 <= 12 1 <= y1,y2 <= 3000 -1 Panu7 months ago Panu int noOfDays(int d1, int m1, int y1, int d2, int m2, int y2) { int monthdays[12]={31,28,31,30,31,30,31,31,30,31,30,31}; long int n1=y1*365+d1; for(int i=0;i<m1-1;i++) n1+="monthdays[i];" n1+="countleapyears(y1,m1);" long="" int="" n2="y2*365+d2;" for(int="" i="0;i&lt;m2-1;i++)" n2+="monthdays[i];" n2+="countleapyears(y2,m2);" if(n2="">n1) return n2-n1; else return n1-n2; } 0 Panu This comment was deleted. 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": 371, "s": 238, "text": "Given two dates, find the total number of days between them.\nNote: The system follows Gregorian calender from the beginning of time." }, { "code": null, "e": 384, "s": 373, "text": "Example 1:" }, { "code": null, "e": 546, "s": 384, "text": "Input:\nd1 = 10, m1 = 2, y1 = 2014\nd2 = 10, m2 = 3, y2 = 2015\nOutput:\n393\nExplanation:\nBy counting manually, we find out there\nare 393 days between the two dates." }, { "code": null, "e": 557, "s": 546, "text": "Example 2:" }, { "code": null, "e": 719, "s": 557, "text": "Input:\nd1 = 10, m1 = 2, y1 = 2001\nd2 = 10, m2 = 2, y2 = 2002\nOutput:\n365\nExplanation:\nBy counting manually, we find out there\nare 365 days between the two dates." }, { "code": null, "e": 943, "s": 721, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function noOfDays() which takes Integers d1,m1,y1 for the first date and d2,m2,y2 as the second date as input and returns the answer." }, { "code": null, "e": 1007, "s": 945, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1075, "s": 1009, "text": "Constraints:\n1 <= d1,d2 <= 31\n1 <= m1,m2 <= 12\n1 <= y1,y2 <= 3000" }, { "code": null, "e": 1078, "s": 1075, "text": "-1" }, { "code": null, "e": 1095, "s": 1078, "text": "Panu7 months ago" }, { "code": null, "e": 1100, "s": 1095, "text": "Panu" }, { "code": null, "e": 1529, "s": 1100, "text": "int noOfDays(int d1, int m1, int y1, int d2, int m2, int y2) { int monthdays[12]={31,28,31,30,31,30,31,31,30,31,30,31}; long int n1=y1*365+d1; for(int i=0;i<m1-1;i++) n1+=\"monthdays[i];\" n1+=\"countleapyears(y1,m1);\" long=\"\" int=\"\" n2=\"y2*365+d2;\" for(int=\"\" i=\"0;i&lt;m2-1;i++)\" n2+=\"monthdays[i];\" n2+=\"countleapyears(y2,m2);\" if(n2=\"\">n1) return n2-n1; else return n1-n2; }" }, { "code": null, "e": 1531, "s": 1529, "text": "0" }, { "code": null, "e": 1536, "s": 1531, "text": "Panu" }, { "code": null, "e": 1562, "s": 1536, "text": "This comment was deleted." }, { "code": null, "e": 1708, "s": 1562, "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": 1744, "s": 1708, "text": " Login to access your submissions. " }, { "code": null, "e": 1754, "s": 1744, "text": "\nProblem\n" }, { "code": null, "e": 1764, "s": 1754, "text": "\nContest\n" }, { "code": null, "e": 1827, "s": 1764, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1975, "s": 1827, "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": 2183, "s": 1975, "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": 2289, "s": 2183, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Calculating percentage in a MySQL query and round off the result
For this, you can use CONCAT() and round(). Let us first create a table − mysql> create table DemoTable1844 ( Number int, TotalNumber int ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1844 values(50,500); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1844 values(80,500); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1844 values(98,500); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1844 values(45,500); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1844; This will produce the following output − +--------+-------------+ | Number | TotalNumber | +--------+-------------+ | 50 | 500 | | 80 | 500 | | 98 | 500 | | 45 | 500 | +--------+-------------+ 4 rows in set (0.00 sec) Here is the query to calculating percentage in a query and rounding off the result − mysql> select concat(round(((Number / TotalNumber) * 100 ),2), '%') as Result from DemoTable1844; This will produce the following output − +--------+ | Result | +--------+ | 10.00% | | 16.00% | | 19.60% | | 9.00% | +--------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "For this, you can use CONCAT() and round(). Let us first create a table −" }, { "code": null, "e": 1260, "s": 1136, "text": "mysql> create table DemoTable1844\n (\n Number int,\n TotalNumber int\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1316, "s": 1260, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1656, "s": 1316, "text": "mysql> insert into DemoTable1844 values(50,500);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1844 values(80,500);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1844 values(98,500);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1844 values(45,500);\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1716, "s": 1656, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1752, "s": 1716, "text": "mysql> select * from DemoTable1844;" }, { "code": null, "e": 1793, "s": 1752, "text": "This will produce the following output −" }, { "code": null, "e": 2018, "s": 1793, "text": "+--------+-------------+\n| Number | TotalNumber |\n+--------+-------------+\n| 50 | 500 |\n| 80 | 500 |\n| 98 | 500 |\n| 45 | 500 |\n+--------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2103, "s": 2018, "text": "Here is the query to calculating percentage in a query and rounding off the result −" }, { "code": null, "e": 2201, "s": 2103, "text": "mysql> select concat(round(((Number / TotalNumber) * 100 ),2), '%') as Result from DemoTable1844;" }, { "code": null, "e": 2242, "s": 2201, "text": "This will produce the following output −" }, { "code": null, "e": 2355, "s": 2242, "text": "+--------+\n| Result |\n+--------+\n| 10.00% |\n| 16.00% |\n| 19.60% |\n| 9.00% |\n+--------+\n4 rows in set (0.00 sec)" } ]
What is the difference between VAR and DYNAMIC keywords in C#?
Store any type of value in the dynamic data type variable created using dynamic keyword. Type checking for these types of variables takes place at run-time. Dynamic are dynamically typed variables. The following is the syntax for declaring a dynamic type − dynamic <variable_name> = value; The following is an example − dynamic val1 = 100; dynamic val2 = 5; dynamic val3 = 20; The dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime. The "var" keyword initializes variables with var support. Just assign whatever value you want for the variable, integer, string, float, etc. It is a statically typed variable. Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { var myInt = 5; var myString = "Amit"; Console.WriteLine("Rank: {0} \nName: {1}",myInt,myString); } } } Rank: 5 Name: Amit
[ { "code": null, "e": 1260, "s": 1062, "text": "Store any type of value in the dynamic data type variable created using dynamic keyword. Type checking for these types of variables takes place at run-time. Dynamic are dynamically typed variables." }, { "code": null, "e": 1319, "s": 1260, "text": "The following is the syntax for declaring a dynamic type −" }, { "code": null, "e": 1352, "s": 1319, "text": "dynamic <variable_name> = value;" }, { "code": null, "e": 1382, "s": 1352, "text": "The following is an example −" }, { "code": null, "e": 1439, "s": 1382, "text": "dynamic val1 = 100;\ndynamic val2 = 5;\ndynamic val3 = 20;" }, { "code": null, "e": 1634, "s": 1439, "text": "The dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime." }, { "code": null, "e": 1810, "s": 1634, "text": "The \"var\" keyword initializes variables with var support. Just assign whatever value you want for the variable, integer, string, float, etc. It is a statically typed variable." }, { "code": null, "e": 1821, "s": 1810, "text": " Live Demo" }, { "code": null, "e": 2051, "s": 1821, "text": "using System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n var myInt = 5;\n var myString = \"Amit\";\n Console.WriteLine(\"Rank: {0} \\nName: {1}\",myInt,myString);\n }\n }\n}" }, { "code": null, "e": 2070, "s": 2051, "text": "Rank: 5\nName: Amit" } ]
Make Your Inventory Simulation in Python | Towards Data Science
This article is an extract from my book Inventory Optimization: Models and Simulations. You can read my other articles here and subscribe to my blog here. I am also active on LinkedIn. Before jumping in Python and coding our inventory simulation, let’s take the time to define the inventory policy we will simulate: a periodic replenishment inventory policy with an up-to level. Products following a periodic replenishment policy are ordered periodically, based on a fixed schedule and an up-to level S. At the beginning of any review period, we need to order enough products to bring our net inventory up to level S. As you can see in the figure above, the order quantity depends on how much stock we have when we make the order and is therefore variable. On the other hand, the orders are made following a fixed schedule: the elapsed time between two consecutive orders will always be the same. This periodic replenishment policy is actually the most common in supply chains because it is often forced onto supply chains by the widespread use of MRP/DRP. These tools follow a predefined schedule — often daily or weekly — resulting in the implicit use of a periodic review policy. The fixed review period policy is often noted (R, S), with R being the fixed review period and S the up-to level. Periodic replenishments allow businesses to group their orders to each of their suppliers. This helps both clients and suppliers to streamline their operations as they can plan orders and workload in advance. 🛡️ Risks. This periodic policy is riskier than a continuous one (where you can make an order at any point in time) due to the blind spot it creates: you cannot order in-between two review periods. If you make an order every Friday with your supplier but are out-of-stock on Monday evening, you will have to wait four more days before making a new order. You will possibly suffer lost sales due to being out-of-stock in the meantime. That is riskier than the fixed reorder point policy, where you would have made a new order directly on Monday evening. ️📦 Variable Order Quantity. Another issue is that the order quantity will vary at each order. This might disrupt a smooth operational flow. For example, if you have a palletized product, you might not want to remove the packaging around an entire pallet to ship a single unit. In a continuous policy, we order our products based on a fixed threshold. As soon as the net inventory reaches the threshold (or goes below), we request a predetermined number of units from our supplier (or launch a production batch). This threshold is called the reorder point or ROP. Continuous policies assume that a client can make an order with its supplier at any time. In reality, this might not be the case. For example, a supplier might only accept orders once a month (or only send one shipment a month — which is the same). In such a case, it isn’t reasonable to think that you would follow a fixed reorder point policy, as the supplier is actually following its own calendar. In practice, a real continuous policy is therefore exceptional (some fully automated production processes, or internal processes, could follow these assumptions). Before jumping in your first inventory simulation, you might want to read my previous article, Inventory Optimization, which lays the foundations for optimizing policies. towardsdatascience.com Let’s start by defining the variable time — it will set the duration of our simulation. We can then populate a demand array that follows a normal distribution. import numpy as nptime = 200d_mu = 100d_std = 25d = np.maximum(np.random.normal(d_mu, d_std, time).round(0).astype(int),0) In this simulation, we assume that our demand is normally distributed and strictly positive. Feel free to change this assumption by changing the way you set it up. We can then define the remaining inputs of our policy and compute the various parameters. from scipy.stats import normL, R, alpha = 4, 1, 0.95 z = norm.ppf(alpha) x_std = np.sqrt(L+R)*d_std Note that we compute x_std as the demand deviation over the risk-horizon, which I coined in my book. Risk-horizonMaximum period of time that you need to wait to receive an order. During this period your inventory is at risk of being depleted. nicolas-vandeput.medium.com You can see in the figure below how our policy (and simulation) would behave over the first timesteps. The order made at the end of timestep 0 will be available in period timestep 5. Let’s set up our different inventory levels using the usual safety stock formula. 📦 Cycle stock Cs. Stock needed to fulfill the expected demand (or forecast) over a replenishment cycle. 🛡️ Safety stock Ss. Stock protecting the supply chain against demand variability (or forecast error) and supply lack of reliability. 🚚 In-transit stock Is. Inventory in transit in between different locations. Usually, these are goods ordered from a supplier but not yet available in our warehouse for our clients to buy. Ss = np.round(x_std*z).astype(int) Cs = 1/2 * d_mu * R Is = d_mu * L S = Ss + 2*Cs + Is nicolas-vandeput.medium.com As our incoming orders can stay in transit for multiple periods (in our example, 4 periods), we will define transit as a 2-dimensional array. hand = np.zeros(time, dtype=int) transit = np.zeros((time,L+1), dtype=int) As you can see in the table below, a new order will start at the end of the 2nd dimension (transit[time,-1]) and then make its way through the 2nd dimension as time passes by (one layer per period) until it reaches the last slot (transit[time,0]). The last slot means that this in-transit inventory will be received at the end of the current period (in other words, be available as of the next period). We also have to create two objects to track the service level of our policy: stock-out_period will contain a Boolean that flags if there is a shortage during a period. stock-out_cycle will contain a Boolean for each order cycle (i.e., review period) that flags if we had a shortage at any time during the last cycle. stock−out_period = np.full(time, False, dtype=bool)stock−out_cycle = [] We now have to initialize these arrays for the first timestep. The initial on-hand and net inventories are S minus the demand during the first period. The in-transit stock is initialized for the second period as the demand in the first period. hand[0] = S − d[0]transit[1,−1] = d[0] We can now start our simulation. These are the main steps performed at each timestep t: Check whether we received an order at the beginning of the period (transit[ t-1,0] > 0). If so, we need to compute the cycle service level by checking if there was a stock-out last period.Update the on-hand inventory by subtracting the demand d[t] and adding the received inventory transit[t-1,0]Indicate in stockout_period[t] whether we had a shortage.Update the net inventory position net[t].Remember that it is the total intransit inventory transit[t].sum() plus the on-hand inventory hand[t]Update the in-transit array by offsetting the values of the previous timestep by 1: transit[t,:-1] = transit[t-1,1:]. This represents the fact that the orders move through the supply pipeline.If we are at the review period (t%R==0), we make an order based on the current net inventory position net[t] and the up-to level S. The order is then stored at the extreme of the in-transit array transit[t,L]. Check whether we received an order at the beginning of the period (transit[ t-1,0] > 0). If so, we need to compute the cycle service level by checking if there was a stock-out last period. Update the on-hand inventory by subtracting the demand d[t] and adding the received inventory transit[t-1,0] Indicate in stockout_period[t] whether we had a shortage. Update the net inventory position net[t].Remember that it is the total intransit inventory transit[t].sum() plus the on-hand inventory hand[t] Update the in-transit array by offsetting the values of the previous timestep by 1: transit[t,:-1] = transit[t-1,1:]. This represents the fact that the orders move through the supply pipeline. If we are at the review period (t%R==0), we make an order based on the current net inventory position net[t] and the up-to level S. The order is then stored at the extreme of the in-transit array transit[t,L]. for t in range(1,time): if transit[t−1,0]>0: stockout_cycle.append(stockout_period[t−1]) hand[t] = hand[t−1] − d[t] + transit[t−1,0] stockout_period[t] = hand[t] < 0 transit[t,:−1] = transit[t−1,1:] if 0==t%R: net = hand[t] + transit[t].sum() transit[t,L] = S − net Finally, we can create a DataFrame df to hold our simulation results and plot them on a graph similar to the figure below. df = pd.DataFrame(data= {'Demand':d, 'On−hand':hand, 'In−transit':list(transit)}) df = df.iloc[R+L:,:] #Remove initialization periods print(df)df['On−hand'].plot(title='Inventory Policy (%d,%d)' %(R,S), ylim=(0,S), legend=True) We can also print cycle and period service levels. print('Alpha:',alpha∗100)SL_alpha = 1−sum(stockout_cycle)/len(stockout_cycle)print('Cycle Service Level:', round(SL_alpha∗100,1))SL_period = 1−sum(stockout_period)/timeprint('Period Service Level:', round(SL_period∗100,1)) Simulations are compelling to optimize policies that do not fit the usual assumptions (normality, fixed lead times, no lost sales, etc.). The code above is only a first step towards simulation-driven inventory optimization. If you want to play with this new tool, See how much stock variation and service level you can expect from different safety stock levels and lead times. Try out different demand probabilities functions (such as Poisson or Gamma) to see how they would differ from the normal assumption. You can also use a custom distribution.
[ { "code": null, "e": 356, "s": 171, "text": "This article is an extract from my book Inventory Optimization: Models and Simulations. You can read my other articles here and subscribe to my blog here. I am also active on LinkedIn." }, { "code": null, "e": 550, "s": 356, "text": "Before jumping in Python and coding our inventory simulation, let’s take the time to define the inventory policy we will simulate: a periodic replenishment inventory policy with an up-to level." }, { "code": null, "e": 675, "s": 550, "text": "Products following a periodic replenishment policy are ordered periodically, based on a fixed schedule and an up-to level S." }, { "code": null, "e": 1068, "s": 675, "text": "At the beginning of any review period, we need to order enough products to bring our net inventory up to level S. As you can see in the figure above, the order quantity depends on how much stock we have when we make the order and is therefore variable. On the other hand, the orders are made following a fixed schedule: the elapsed time between two consecutive orders will always be the same." }, { "code": null, "e": 1354, "s": 1068, "text": "This periodic replenishment policy is actually the most common in supply chains because it is often forced onto supply chains by the widespread use of MRP/DRP. These tools follow a predefined schedule — often daily or weekly — resulting in the implicit use of a periodic review policy." }, { "code": null, "e": 1468, "s": 1354, "text": "The fixed review period policy is often noted (R, S), with R being the fixed review period and S the up-to level." }, { "code": null, "e": 1677, "s": 1468, "text": "Periodic replenishments allow businesses to group their orders to each of their suppliers. This helps both clients and suppliers to streamline their operations as they can plan orders and workload in advance." }, { "code": null, "e": 2229, "s": 1677, "text": "🛡️ Risks. This periodic policy is riskier than a continuous one (where you can make an order at any point in time) due to the blind spot it creates: you cannot order in-between two review periods. If you make an order every Friday with your supplier but are out-of-stock on Monday evening, you will have to wait four more days before making a new order. You will possibly suffer lost sales due to being out-of-stock in the meantime. That is riskier than the fixed reorder point policy, where you would have made a new order directly on Monday evening." }, { "code": null, "e": 2506, "s": 2229, "text": "️📦 Variable Order Quantity. Another issue is that the order quantity will vary at each order. This might disrupt a smooth operational flow. For example, if you have a palletized product, you might not want to remove the packaging around an entire pallet to ship a single unit." }, { "code": null, "e": 2792, "s": 2506, "text": "In a continuous policy, we order our products based on a fixed threshold. As soon as the net inventory reaches the threshold (or goes below), we request a predetermined number of units from our supplier (or launch a production batch). This threshold is called the reorder point or ROP." }, { "code": null, "e": 3357, "s": 2792, "text": "Continuous policies assume that a client can make an order with its supplier at any time. In reality, this might not be the case. For example, a supplier might only accept orders once a month (or only send one shipment a month — which is the same). In such a case, it isn’t reasonable to think that you would follow a fixed reorder point policy, as the supplier is actually following its own calendar. In practice, a real continuous policy is therefore exceptional (some fully automated production processes, or internal processes, could follow these assumptions)." }, { "code": null, "e": 3528, "s": 3357, "text": "Before jumping in your first inventory simulation, you might want to read my previous article, Inventory Optimization, which lays the foundations for optimizing policies." }, { "code": null, "e": 3551, "s": 3528, "text": "towardsdatascience.com" }, { "code": null, "e": 3711, "s": 3551, "text": "Let’s start by defining the variable time — it will set the duration of our simulation. We can then populate a demand array that follows a normal distribution." }, { "code": null, "e": 3834, "s": 3711, "text": "import numpy as nptime = 200d_mu = 100d_std = 25d = np.maximum(np.random.normal(d_mu, d_std, time).round(0).astype(int),0)" }, { "code": null, "e": 3998, "s": 3834, "text": "In this simulation, we assume that our demand is normally distributed and strictly positive. Feel free to change this assumption by changing the way you set it up." }, { "code": null, "e": 4088, "s": 3998, "text": "We can then define the remaining inputs of our policy and compute the various parameters." }, { "code": null, "e": 4188, "s": 4088, "text": "from scipy.stats import normL, R, alpha = 4, 1, 0.95 z = norm.ppf(alpha) x_std = np.sqrt(L+R)*d_std" }, { "code": null, "e": 4289, "s": 4188, "text": "Note that we compute x_std as the demand deviation over the risk-horizon, which I coined in my book." }, { "code": null, "e": 4431, "s": 4289, "text": "Risk-horizonMaximum period of time that you need to wait to receive an order. During this period your inventory is at risk of being depleted." }, { "code": null, "e": 4459, "s": 4431, "text": "nicolas-vandeput.medium.com" }, { "code": null, "e": 4642, "s": 4459, "text": "You can see in the figure below how our policy (and simulation) would behave over the first timesteps. The order made at the end of timestep 0 will be available in period timestep 5." }, { "code": null, "e": 4724, "s": 4642, "text": "Let’s set up our different inventory levels using the usual safety stock formula." }, { "code": null, "e": 4828, "s": 4724, "text": "📦 Cycle stock Cs. Stock needed to fulfill the expected demand (or forecast) over a replenishment cycle." }, { "code": null, "e": 4961, "s": 4828, "text": "🛡️ Safety stock Ss. Stock protecting the supply chain against demand variability (or forecast error) and supply lack of reliability." }, { "code": null, "e": 5149, "s": 4961, "text": "🚚 In-transit stock Is. Inventory in transit in between different locations. Usually, these are goods ordered from a supplier but not yet available in our warehouse for our clients to buy." }, { "code": null, "e": 5237, "s": 5149, "text": "Ss = np.round(x_std*z).astype(int) Cs = 1/2 * d_mu * R Is = d_mu * L S = Ss + 2*Cs + Is" }, { "code": null, "e": 5265, "s": 5237, "text": "nicolas-vandeput.medium.com" }, { "code": null, "e": 5407, "s": 5265, "text": "As our incoming orders can stay in transit for multiple periods (in our example, 4 periods), we will define transit as a 2-dimensional array." }, { "code": null, "e": 5482, "s": 5407, "text": "hand = np.zeros(time, dtype=int) transit = np.zeros((time,L+1), dtype=int)" }, { "code": null, "e": 5885, "s": 5482, "text": "As you can see in the table below, a new order will start at the end of the 2nd dimension (transit[time,-1]) and then make its way through the 2nd dimension as time passes by (one layer per period) until it reaches the last slot (transit[time,0]). The last slot means that this in-transit inventory will be received at the end of the current period (in other words, be available as of the next period)." }, { "code": null, "e": 5962, "s": 5885, "text": "We also have to create two objects to track the service level of our policy:" }, { "code": null, "e": 6053, "s": 5962, "text": "stock-out_period will contain a Boolean that flags if there is a shortage during a period." }, { "code": null, "e": 6202, "s": 6053, "text": "stock-out_cycle will contain a Boolean for each order cycle (i.e., review period) that flags if we had a shortage at any time during the last cycle." }, { "code": null, "e": 6274, "s": 6202, "text": "stock−out_period = np.full(time, False, dtype=bool)stock−out_cycle = []" }, { "code": null, "e": 6518, "s": 6274, "text": "We now have to initialize these arrays for the first timestep. The initial on-hand and net inventories are S minus the demand during the first period. The in-transit stock is initialized for the second period as the demand in the first period." }, { "code": null, "e": 6557, "s": 6518, "text": "hand[0] = S − d[0]transit[1,−1] = d[0]" }, { "code": null, "e": 6645, "s": 6557, "text": "We can now start our simulation. These are the main steps performed at each timestep t:" }, { "code": null, "e": 7542, "s": 6645, "text": "Check whether we received an order at the beginning of the period (transit[ t-1,0] > 0). If so, we need to compute the cycle service level by checking if there was a stock-out last period.Update the on-hand inventory by subtracting the demand d[t] and adding the received inventory transit[t-1,0]Indicate in stockout_period[t] whether we had a shortage.Update the net inventory position net[t].Remember that it is the total intransit inventory transit[t].sum() plus the on-hand inventory hand[t]Update the in-transit array by offsetting the values of the previous timestep by 1: transit[t,:-1] = transit[t-1,1:]. This represents the fact that the orders move through the supply pipeline.If we are at the review period (t%R==0), we make an order based on the current net inventory position net[t] and the up-to level S. The order is then stored at the extreme of the in-transit array transit[t,L]." }, { "code": null, "e": 7731, "s": 7542, "text": "Check whether we received an order at the beginning of the period (transit[ t-1,0] > 0). If so, we need to compute the cycle service level by checking if there was a stock-out last period." }, { "code": null, "e": 7840, "s": 7731, "text": "Update the on-hand inventory by subtracting the demand d[t] and adding the received inventory transit[t-1,0]" }, { "code": null, "e": 7898, "s": 7840, "text": "Indicate in stockout_period[t] whether we had a shortage." }, { "code": null, "e": 8041, "s": 7898, "text": "Update the net inventory position net[t].Remember that it is the total intransit inventory transit[t].sum() plus the on-hand inventory hand[t]" }, { "code": null, "e": 8234, "s": 8041, "text": "Update the in-transit array by offsetting the values of the previous timestep by 1: transit[t,:-1] = transit[t-1,1:]. This represents the fact that the orders move through the supply pipeline." }, { "code": null, "e": 8444, "s": 8234, "text": "If we are at the review period (t%R==0), we make an order based on the current net inventory position net[t] and the up-to level S. The order is then stored at the extreme of the in-transit array transit[t,L]." }, { "code": null, "e": 8730, "s": 8444, "text": "for t in range(1,time): if transit[t−1,0]>0: stockout_cycle.append(stockout_period[t−1]) hand[t] = hand[t−1] − d[t] + transit[t−1,0] stockout_period[t] = hand[t] < 0 transit[t,:−1] = transit[t−1,1:] if 0==t%R: net = hand[t] + transit[t].sum() transit[t,L] = S − net" }, { "code": null, "e": 8853, "s": 8730, "text": "Finally, we can create a DataFrame df to hold our simulation results and plot them on a graph similar to the figure below." }, { "code": null, "e": 9081, "s": 8853, "text": "df = pd.DataFrame(data= {'Demand':d, 'On−hand':hand, 'In−transit':list(transit)}) df = df.iloc[R+L:,:] #Remove initialization periods print(df)df['On−hand'].plot(title='Inventory Policy (%d,%d)' %(R,S), ylim=(0,S), legend=True)" }, { "code": null, "e": 9132, "s": 9081, "text": "We can also print cycle and period service levels." }, { "code": null, "e": 9355, "s": 9132, "text": "print('Alpha:',alpha∗100)SL_alpha = 1−sum(stockout_cycle)/len(stockout_cycle)print('Cycle Service Level:', round(SL_alpha∗100,1))SL_period = 1−sum(stockout_period)/timeprint('Period Service Level:', round(SL_period∗100,1))" }, { "code": null, "e": 9579, "s": 9355, "text": "Simulations are compelling to optimize policies that do not fit the usual assumptions (normality, fixed lead times, no lost sales, etc.). The code above is only a first step towards simulation-driven inventory optimization." }, { "code": null, "e": 9619, "s": 9579, "text": "If you want to play with this new tool," }, { "code": null, "e": 9732, "s": 9619, "text": "See how much stock variation and service level you can expect from different safety stock levels and lead times." } ]
Google Colab - Executing External Python Files
Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive. Tools / Command palette You will see the list of commands as shown in this screenshot − Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell. # Run this cell to mount your Google Drive. from google.colab import drive drive.mount('/content/drive') If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below − Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen − If you grant the permissions, you will receive your code as follows − Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below − Now, you are ready to use the contents of your drive in Colab. You can list the contents of the drive using the ls command as follows − !ls "/content/drive/My Drive/Colab Notebooks" This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here − Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell − !python3 "/content/drive/My Drive/Colab Notebooks/hello.py" The contents of hello.py are given here for your reference − print("Welcome to TutorialsPoint!") You will now see the following output − Welcome to TutorialsPoint! Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter. 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2291, "s": 2041, "text": "Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive." }, { "code": null, "e": 2316, "s": 2291, "text": "Tools / Command palette\n" }, { "code": null, "e": 2380, "s": 2316, "text": "You will see the list of commands as shown in this screenshot −" }, { "code": null, "e": 2553, "s": 2380, "text": "Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell." }, { "code": null, "e": 2659, "s": 2553, "text": "# Run this cell to mount your Google Drive.\nfrom google.colab import drive\ndrive.mount('/content/drive')\n" }, { "code": null, "e": 2781, "s": 2659, "text": "If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below −" }, { "code": null, "e": 2909, "s": 2781, "text": "Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen −" }, { "code": null, "e": 2979, "s": 2909, "text": "If you grant the permissions, you will receive your code as follows −" }, { "code": null, "e": 3108, "s": 2979, "text": "Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below −" }, { "code": null, "e": 3171, "s": 3108, "text": "Now, you are ready to use the contents of your drive in Colab." }, { "code": null, "e": 3244, "s": 3171, "text": "You can list the contents of the drive using the ls command as follows −" }, { "code": null, "e": 3291, "s": 3244, "text": "!ls \"/content/drive/My Drive/Colab Notebooks\"\n" }, { "code": null, "e": 3415, "s": 3291, "text": "This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here −" }, { "code": null, "e": 3556, "s": 3415, "text": "Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb\n" }, { "code": null, "e": 3698, "s": 3556, "text": "Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell −" }, { "code": null, "e": 3759, "s": 3698, "text": "!python3 \"/content/drive/My Drive/Colab Notebooks/hello.py\"\n" }, { "code": null, "e": 3820, "s": 3759, "text": "The contents of hello.py are given here for your reference −" }, { "code": null, "e": 3857, "s": 3820, "text": "print(\"Welcome to TutorialsPoint!\")\n" }, { "code": null, "e": 3897, "s": 3857, "text": "You will now see the following output −" }, { "code": null, "e": 3925, "s": 3897, "text": "Welcome to TutorialsPoint!\n" }, { "code": null, "e": 4031, "s": 3925, "text": "Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter." }, { "code": null, "e": 4066, "s": 4031, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4080, "s": 4066, "text": " Asif Hussain" }, { "code": null, "e": 4112, "s": 4080, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4129, "s": 4112, "text": " Aditya Kulkarni" }, { "code": null, "e": 4164, "s": 4129, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4178, "s": 4164, "text": " Sasha Miller" }, { "code": null, "e": 4213, "s": 4178, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4226, "s": 4213, "text": " Zach Miller" }, { "code": null, "e": 4261, "s": 4226, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4275, "s": 4261, "text": " Sasha Miller" }, { "code": null, "e": 4310, "s": 4275, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4324, "s": 4310, "text": " Sasha Miller" }, { "code": null, "e": 4331, "s": 4324, "text": " Print" }, { "code": null, "e": 4342, "s": 4331, "text": " Add Notes" } ]
Python | Mean of tuple list
18 Oct, 2019 Sometimes, while working with Python tuple list, we can have a problem in which we need to find the average of tuple values in the list. This problem has the possible application in many domains including mathematics. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loopsThe first approach that can be thought of to solve this problem can be a brute force approach in which we just loop each tuple to add element and then just divide it by number of tuples in the list. # Python3 code to demonstrate working of# Mean of tuple list# Using loops # Initializing listtest_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original listprint("The original list is : " + str(test_list)) # Average of tuple list# Using loopssum = 0for sub in test_list: for i in sub: sum = sum + ires = sum / len(test_list) # printing resultprint("The mean of tuple list is : " + str(res)) The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666 Method #2 : Using chain() + sum()In order to reduce the line of codes, the chain() functionality can be used so that all the elements can be extracted and then can be added using sum(). # Python3 code to demonstrate working of# Mean of tuple list# Using chain() + sum()from itertools import chain # Initializing listtest_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original listprint("The original list is : " + str(test_list)) # Average of tuple list# Using chain() + sum()temp = list(chain(*test_list)) res = sum(temp)/ len(test_list) # printing resultprint("The mean of tuple list is : " + str(res)) The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666 Python list-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 310, "s": 28, "text": "Sometimes, while working with Python tuple list, we can have a problem in which we need to find the average of tuple values in the list. This problem has the possible application in many domains including mathematics. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 532, "s": 310, "text": "Method #1 : Using loopsThe first approach that can be thought of to solve this problem can be a brute force approach in which we just loop each tuple to add element and then just divide it by number of tuples in the list." }, { "code": "# Python3 code to demonstrate working of# Mean of tuple list# Using loops # Initializing listtest_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Average of tuple list# Using loopssum = 0for sub in test_list: for i in sub: sum = sum + ires = sum / len(test_list) # printing resultprint(\"The mean of tuple list is : \" + str(res))", "e": 942, "s": 532, "text": null }, { "code": null, "e": 1045, "s": 942, "text": "The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)]\nThe mean of tuple list is : 13.666666666666666\n" }, { "code": null, "e": 1233, "s": 1047, "text": "Method #2 : Using chain() + sum()In order to reduce the line of codes, the chain() functionality can be used so that all the elements can be extracted and then can be added using sum()." }, { "code": "# Python3 code to demonstrate working of# Mean of tuple list# Using chain() + sum()from itertools import chain # Initializing listtest_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Average of tuple list# Using chain() + sum()temp = list(chain(*test_list)) res = sum(temp)/ len(test_list) # printing resultprint(\"The mean of tuple list is : \" + str(res))", "e": 1660, "s": 1233, "text": null }, { "code": null, "e": 1763, "s": 1660, "text": "The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)]\nThe mean of tuple list is : 13.666666666666666\n" }, { "code": null, "e": 1784, "s": 1763, "text": "Python list-programs" }, { "code": null, "e": 1791, "s": 1784, "text": "Python" }, { "code": null, "e": 1807, "s": 1791, "text": "Python Programs" }, { "code": null, "e": 1905, "s": 1807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1923, "s": 1905, "text": "Python Dictionary" }, { "code": null, "e": 1965, "s": 1923, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1987, "s": 1965, "text": "Enumerate() in Python" }, { "code": null, "e": 2022, "s": 1987, "text": "Read a file line by line in Python" }, { "code": null, "e": 2048, "s": 2022, "text": "Python String | replace()" }, { "code": null, "e": 2091, "s": 2048, "text": "Python program to convert a list to string" }, { "code": null, "e": 2113, "s": 2091, "text": "Defaultdict in Python" }, { "code": null, "e": 2152, "s": 2113, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2190, "s": 2152, "text": "Python | Convert a list to dictionary" } ]
Longest path in an undirected tree
07 Jul, 2022 Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes. Example: Input : Below shown Tree using adjacency list representation: Output : 5 In below tree longest path is of length 5 from node 5 to node 7 This problem is the same as the diameter of the n-ary tree. We have discussed a simple solution here. In this post, an efficient solution is discussed. We can find the longest path using two BFSs. The idea is based on the following fact: If we start BFS from any node x and find a node with the longest distance from x, it must be an endpoint of the longest path. It can be proved using contradiction. So our algorithm reduces to simple two BFSs. First BFS to find an endpoint of the longest path and second BFS from this endpoint to find the actual longest path. For the proof of why does this algorithm works, there is a nice explanation here Proof of correctness: Algorithm for the diameter of a tree in graph theory As we can see in the above diagram, if we start our BFS from node-0, the node at the farthest distance from it will be node-5, now if we start our BFS from node-5 the node at the farthest distance will be node-7, finally, the path from node-5 to node-7 will constitute our longest path. Implementation: C++ Java C# Python3 Javascript // C++ program to find longest path of the tree#include <bits/stdc++.h>using namespace std; // This class represents a undirected graph using adjacency listclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w);// function to add an edge to graph void longestPathLength(); // prints longest path of the tree pair<int, int> bfs(int u); // function returns maximum distant // node from u with its distance}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Since the graph is undirected} // method returns farthest node and its distance from node upair<int, int> Graph::bfs(int u){ // mark all distance with -1 int dis[V]; memset(dis, -1, sizeof(dis)); queue<int> q; q.push(u); // distance of u from u will be 0 dis[u] = 0; while (!q.empty()) { int t = q.front(); q.pop(); // loop for all adjacent nodes of node-t for (auto it = adj[t].begin(); it != adj[t].end(); it++) { int v = *it; // push node into queue only if // it is not visited already if (dis[v] == -1) { q.push(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx; // get farthest node distance and its index for (int i = 0; i < V; i++) { if (dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return make_pair(nodeIdx, maxDis);} // method prints longest path of given treevoid Graph::longestPathLength(){ pair<int, int> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); cout << "Longest path is from " << t1.first << " to " << t2.first << " of length " << t2.second;} // Driver code to test above methodsint main(){ // Create a graph given in the example Graph g(10); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(2, 9); g.addEdge(2, 4); g.addEdge(4, 5); g.addEdge(1, 6); g.addEdge(6, 7); g.addEdge(6, 8); g.longestPathLength(); return 0;} // Java program to find longest path of the tree import java.util.Arrays;import java.util.LinkedList;import java.util.Queue; class LongestPathUndirectedTree { // Utility Pair class for storing maximum distance // Node with its distance static class Pair<T,V> { T first; // maximum distance Node V second; // distance of maximum distance node //Constructor Pair(T first, V second) { this.first = first; this.second = second; } } // This class represents a undirected graph using adjacency list static class Graph { int V; // No. of vertices LinkedList<Integer>[] adj; //Adjacency List // Constructor Graph(int V) { this.V = V; // Initializing Adjacency List adj = new LinkedList[V]; for(int i = 0; i < V; ++i) { adj[i] = new LinkedList<Integer>(); } } // function to add an edge to graph void addEdge(int s, int d) { adj[s].add(d); // Add d to s's list. adj[d].add(s); // Since the graph is undirected } // method returns farthest node and its distance from node u Pair<Integer, Integer> bfs(int u) { int[] dis = new int[V]; // mark all distance with -1 Arrays.fill(dis, -1); Queue<Integer> q = new LinkedList<>(); q.add(u); // distance of u from u will be 0 dis[u] = 0; while (!q.isEmpty()) { int t = q.poll(); // loop for all adjacent nodes of node-t for(int i = 0; i < adj[t].size(); ++i) { int v = adj[t].get(i); // push node into queue only if // it is not visited already if(dis[v] == -1) { q.add(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx = 0; // get farthest node distance and its index for(int i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair<Integer, Integer>(nodeIdx, maxDis); } // method prints longest path of given tree void longestPathLength() { Pair<Integer, Integer> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); System.out.println("Longest path is from "+ t1.first + " to "+ t2.first +" of length "+t2.second); } } // Driver code to test above methods public static void main(String[] args){ // Create a graph given in the example Graph graph = new Graph(10); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(2, 9); graph.addEdge(2, 4); graph.addEdge(4, 5); graph.addEdge(1, 6); graph.addEdge(6, 7); graph.addEdge(6, 8); graph.longestPathLength(); } }// Added By Brij Raj Kishore // C# program to find longest path of the treeusing System;using System.Collections.Generic; class GFG{ // Utility Pair class for storing// maximum distance Node with its distancepublic class Pair<T, V>{ // maximum distance Node public T first; // distance of maximum distance node public V second; // Constructor public Pair(T first, V second) { this.first = first; this.second = second; }} // This class represents a undirected graph// using adjacency listclass Graph{ int V; // No. of vertices List<int>[] adj; //Adjacency List // Constructor public Graph(int V) { this.V = V; // Initializing Adjacency List adj = new List<int>[V]; for(int i = 0; i < V; ++i) { adj[i] = new List<int>(); } } // function to add an edge to graph public void addEdge(int s, int d) { adj[s].Add(d); // Add d to s's list. adj[d].Add(s); // Since the graph is undirected } // method returns farthest node and // its distance from node u public Pair<int, int> bfs(int u) { int[] dis = new int[V]; // mark all distance with -1 for(int i = 0; i < V; i++) dis[i] = -1; Queue<int> q = new Queue<int>(); q.Enqueue(u); // distance of u from u will be 0 dis[u] = 0; while (q.Count != 0) { int t = q.Dequeue(); // loop for all adjacent nodes of node-t for(int i = 0; i < adj[t].Count; ++i) { int v = adj[t][i]; // push node into queue only if // it is not visited already if(dis[v] == -1) { q.Enqueue(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx = 0; // get farthest node distance and its index for(int i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair<int, int>(nodeIdx, maxDis); } // method prints longest path of given tree public void longestPathLength() { Pair<int, int> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); Console.WriteLine("longest path is from " + t1.first + " to " + t2.first + " of length " + t2.second); }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the example Graph graph = new Graph(10); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(2, 9); graph.addEdge(2, 4); graph.addEdge(4, 5); graph.addEdge(1, 6); graph.addEdge(6, 7); graph.addEdge(6, 8); graph.longestPathLength();}} // This code is contributed by Rajput-Ji # Python program to find the Longest Path of the Tree# By Aaditya Upadhyay from collections import deque class Graph: # Initialisation of graph def __init__(self, vertices): # No. of vertices self.vertices = vertices # adjacency list self.adj = {i: [] for i in range(self.vertices)} def addEdge(self, u, v): # add u to v's list self.adj[u].append(v) # since the graph is undirected self.adj[v].append(u) # method return farthest node and its distance from node u def BFS(self, u): # marking all nodes as unvisited visited = [False for i in range(self.vertices + 1)] # mark all distance with -1 distance = [-1 for i in range(self.vertices + 1)] # distance of u from u will be 0 distance[u] = 0 # in-built library for queue which performs fast operations on both the ends queue = deque() queue.append(u) # mark node u as visited visited[u] = True while queue: # pop the front of the queue(0th element) front = queue.popleft() # loop for all adjacent nodes of node front for i in self.adj[front]: if not visited[i]: # mark the ith node as visited visited[i] = True # make distance of i , one more than distance of front distance[i] = distance[front]+1 # Push node into the stack only if it is not visited already queue.append(i) maxDis = 0 # get farthest node distance and its index for i in range(self.vertices): if distance[i] > maxDis: maxDis = distance[i] nodeIdx = i return nodeIdx, maxDis # method prints longest path of given tree def LongestPathLength(self): # first DFS to find one end point of longest path node, Dis = self.BFS(0) # second DFS to find the actual longest path node_2, LongDis = self.BFS(node) print('Longest path is from', node, 'to', node_2, 'of length', LongDis) # create a graph given in the example G = Graph(10)G.addEdge(0, 1)G.addEdge(1, 2)G.addEdge(2, 3)G.addEdge(2, 9)G.addEdge(2, 4)G.addEdge(4, 5)G.addEdge(1, 6)G.addEdge(6, 7)G.addEdge(6, 8) G.LongestPathLength() <script> // Javascript program to find longest path of the tree // Utility Pair class for storing// maximum distance Node with its distanceclass Pair{ // Constructor constructor(first, second) { this.first = first; this.second = second; }} // This class represents a undirected graph// using adjacency listvar V; // No. of verticesvar adj; //Adjacency List // Constructorfunction initialize(V){ this.V = V; // Initializing Adjacency List adj = Array.from(Array(V), ()=>Array());} // function to add an edge to graphfunction addEdge(s, d){ adj[s].push(d); // push d to s's list. adj[d].push(s); // Since the graph is undirected} // method returns farthest node and// its distance from node ufunction bfs(u){ var dis = Array(V); // mark all distance with -1 for(var i = 0; i < V; i++) dis[i] = -1; var q = []; q.push(u); // distance of u from u will be 0 dis[u] = 0; while (q.length != 0) { var t = q.shift(); // loop for all adjacent nodes of node-t for(var i = 0; i < adj[t].length; ++i) { var v = adj[t][i]; // push node into queue only if // it is not visited already if(dis[v] == -1) { q.push(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } var maxDis = 0; var nodeIdx = 0; // get farthest node distance and its index for(var i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair(nodeIdx, maxDis);} // method prints longest path of given treefunction longestPathLength(){ var t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); document.write("longest path is from " + t1.first + " to " + t2.first + " of length " + t2.second);} // Create a graph given in the exampleinitialize(10)addEdge(0, 1);addEdge(1, 2);addEdge(2, 3);addEdge(2, 9);addEdge(2, 4);addEdge(4, 5);addEdge(1, 6);addEdge(6, 7);addEdge(6, 8);longestPathLength(); // This code is contributed by famously.</script> Longest path is from 5 to 7 of length 5 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Brij Raj Kishore Rajput-Ji aadiupadhyay gabaa406 saurabh1990aror famously hardikkoriintern BFS n-ary-tree Tree Tree BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure What is Data Structure: Types, Classifications and Applications Binary Tree | Set 2 (Properties) Lowest Common Ancestor in a Binary Tree | Set 1 Decision Tree Diagonal Traversal of Binary Tree Construct Tree from given Inorder and Preorder traversals Insertion in a Binary Tree in level order Print Left View of a Binary Tree
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 175, "s": 54, "text": "Given an undirected tree, we need to find the longest path of this tree where a path is defined as a sequence of nodes. " }, { "code": null, "e": 185, "s": 175, "text": "Example: " }, { "code": null, "e": 331, "s": 185, "text": "Input : Below shown Tree using adjacency list \n representation:\nOutput : 5\nIn below tree longest path is of length 5\nfrom node 5 to node 7" }, { "code": null, "e": 434, "s": 331, "text": "This problem is the same as the diameter of the n-ary tree. We have discussed a simple solution here. " }, { "code": null, "e": 897, "s": 434, "text": "In this post, an efficient solution is discussed. We can find the longest path using two BFSs. The idea is based on the following fact: If we start BFS from any node x and find a node with the longest distance from x, it must be an endpoint of the longest path. It can be proved using contradiction. So our algorithm reduces to simple two BFSs. First BFS to find an endpoint of the longest path and second BFS from this endpoint to find the actual longest path. " }, { "code": null, "e": 1054, "s": 897, "text": "For the proof of why does this algorithm works, there is a nice explanation here Proof of correctness: Algorithm for the diameter of a tree in graph theory " }, { "code": null, "e": 1341, "s": 1054, "text": "As we can see in the above diagram, if we start our BFS from node-0, the node at the farthest distance from it will be node-5, now if we start our BFS from node-5 the node at the farthest distance will be node-7, finally, the path from node-5 to node-7 will constitute our longest path." }, { "code": null, "e": 1357, "s": 1341, "text": "Implementation:" }, { "code": null, "e": 1361, "s": 1357, "text": "C++" }, { "code": null, "e": 1366, "s": 1361, "text": "Java" }, { "code": null, "e": 1369, "s": 1366, "text": "C#" }, { "code": null, "e": 1377, "s": 1369, "text": "Python3" }, { "code": null, "e": 1388, "s": 1377, "text": "Javascript" }, { "code": "// C++ program to find longest path of the tree#include <bits/stdc++.h>using namespace std; // This class represents a undirected graph using adjacency listclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w);// function to add an edge to graph void longestPathLength(); // prints longest path of the tree pair<int, int> bfs(int u); // function returns maximum distant // node from u with its distance}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Since the graph is undirected} // method returns farthest node and its distance from node upair<int, int> Graph::bfs(int u){ // mark all distance with -1 int dis[V]; memset(dis, -1, sizeof(dis)); queue<int> q; q.push(u); // distance of u from u will be 0 dis[u] = 0; while (!q.empty()) { int t = q.front(); q.pop(); // loop for all adjacent nodes of node-t for (auto it = adj[t].begin(); it != adj[t].end(); it++) { int v = *it; // push node into queue only if // it is not visited already if (dis[v] == -1) { q.push(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx; // get farthest node distance and its index for (int i = 0; i < V; i++) { if (dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return make_pair(nodeIdx, maxDis);} // method prints longest path of given treevoid Graph::longestPathLength(){ pair<int, int> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); cout << \"Longest path is from \" << t1.first << \" to \" << t2.first << \" of length \" << t2.second;} // Driver code to test above methodsint main(){ // Create a graph given in the example Graph g(10); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(2, 9); g.addEdge(2, 4); g.addEdge(4, 5); g.addEdge(1, 6); g.addEdge(6, 7); g.addEdge(6, 8); g.longestPathLength(); return 0;}", "e": 3950, "s": 1388, "text": null }, { "code": "// Java program to find longest path of the tree import java.util.Arrays;import java.util.LinkedList;import java.util.Queue; class LongestPathUndirectedTree { // Utility Pair class for storing maximum distance // Node with its distance static class Pair<T,V> { T first; // maximum distance Node V second; // distance of maximum distance node //Constructor Pair(T first, V second) { this.first = first; this.second = second; } } // This class represents a undirected graph using adjacency list static class Graph { int V; // No. of vertices LinkedList<Integer>[] adj; //Adjacency List // Constructor Graph(int V) { this.V = V; // Initializing Adjacency List adj = new LinkedList[V]; for(int i = 0; i < V; ++i) { adj[i] = new LinkedList<Integer>(); } } // function to add an edge to graph void addEdge(int s, int d) { adj[s].add(d); // Add d to s's list. adj[d].add(s); // Since the graph is undirected } // method returns farthest node and its distance from node u Pair<Integer, Integer> bfs(int u) { int[] dis = new int[V]; // mark all distance with -1 Arrays.fill(dis, -1); Queue<Integer> q = new LinkedList<>(); q.add(u); // distance of u from u will be 0 dis[u] = 0; while (!q.isEmpty()) { int t = q.poll(); // loop for all adjacent nodes of node-t for(int i = 0; i < adj[t].size(); ++i) { int v = adj[t].get(i); // push node into queue only if // it is not visited already if(dis[v] == -1) { q.add(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx = 0; // get farthest node distance and its index for(int i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair<Integer, Integer>(nodeIdx, maxDis); } // method prints longest path of given tree void longestPathLength() { Pair<Integer, Integer> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); System.out.println(\"Longest path is from \"+ t1.first + \" to \"+ t2.first +\" of length \"+t2.second); } } // Driver code to test above methods public static void main(String[] args){ // Create a graph given in the example Graph graph = new Graph(10); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(2, 9); graph.addEdge(2, 4); graph.addEdge(4, 5); graph.addEdge(1, 6); graph.addEdge(6, 7); graph.addEdge(6, 8); graph.longestPathLength(); } }// Added By Brij Raj Kishore", "e": 7497, "s": 3950, "text": null }, { "code": "// C# program to find longest path of the treeusing System;using System.Collections.Generic; class GFG{ // Utility Pair class for storing// maximum distance Node with its distancepublic class Pair<T, V>{ // maximum distance Node public T first; // distance of maximum distance node public V second; // Constructor public Pair(T first, V second) { this.first = first; this.second = second; }} // This class represents a undirected graph// using adjacency listclass Graph{ int V; // No. of vertices List<int>[] adj; //Adjacency List // Constructor public Graph(int V) { this.V = V; // Initializing Adjacency List adj = new List<int>[V]; for(int i = 0; i < V; ++i) { adj[i] = new List<int>(); } } // function to add an edge to graph public void addEdge(int s, int d) { adj[s].Add(d); // Add d to s's list. adj[d].Add(s); // Since the graph is undirected } // method returns farthest node and // its distance from node u public Pair<int, int> bfs(int u) { int[] dis = new int[V]; // mark all distance with -1 for(int i = 0; i < V; i++) dis[i] = -1; Queue<int> q = new Queue<int>(); q.Enqueue(u); // distance of u from u will be 0 dis[u] = 0; while (q.Count != 0) { int t = q.Dequeue(); // loop for all adjacent nodes of node-t for(int i = 0; i < adj[t].Count; ++i) { int v = adj[t][i]; // push node into queue only if // it is not visited already if(dis[v] == -1) { q.Enqueue(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } int maxDis = 0; int nodeIdx = 0; // get farthest node distance and its index for(int i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair<int, int>(nodeIdx, maxDis); } // method prints longest path of given tree public void longestPathLength() { Pair<int, int> t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); Console.WriteLine(\"longest path is from \" + t1.first + \" to \" + t2.first + \" of length \" + t2.second); }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the example Graph graph = new Graph(10); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(2, 9); graph.addEdge(2, 4); graph.addEdge(4, 5); graph.addEdge(1, 6); graph.addEdge(6, 7); graph.addEdge(6, 8); graph.longestPathLength();}} // This code is contributed by Rajput-Ji", "e": 10702, "s": 7497, "text": null }, { "code": "# Python program to find the Longest Path of the Tree# By Aaditya Upadhyay from collections import deque class Graph: # Initialisation of graph def __init__(self, vertices): # No. of vertices self.vertices = vertices # adjacency list self.adj = {i: [] for i in range(self.vertices)} def addEdge(self, u, v): # add u to v's list self.adj[u].append(v) # since the graph is undirected self.adj[v].append(u) # method return farthest node and its distance from node u def BFS(self, u): # marking all nodes as unvisited visited = [False for i in range(self.vertices + 1)] # mark all distance with -1 distance = [-1 for i in range(self.vertices + 1)] # distance of u from u will be 0 distance[u] = 0 # in-built library for queue which performs fast operations on both the ends queue = deque() queue.append(u) # mark node u as visited visited[u] = True while queue: # pop the front of the queue(0th element) front = queue.popleft() # loop for all adjacent nodes of node front for i in self.adj[front]: if not visited[i]: # mark the ith node as visited visited[i] = True # make distance of i , one more than distance of front distance[i] = distance[front]+1 # Push node into the stack only if it is not visited already queue.append(i) maxDis = 0 # get farthest node distance and its index for i in range(self.vertices): if distance[i] > maxDis: maxDis = distance[i] nodeIdx = i return nodeIdx, maxDis # method prints longest path of given tree def LongestPathLength(self): # first DFS to find one end point of longest path node, Dis = self.BFS(0) # second DFS to find the actual longest path node_2, LongDis = self.BFS(node) print('Longest path is from', node, 'to', node_2, 'of length', LongDis) # create a graph given in the example G = Graph(10)G.addEdge(0, 1)G.addEdge(1, 2)G.addEdge(2, 3)G.addEdge(2, 9)G.addEdge(2, 4)G.addEdge(4, 5)G.addEdge(1, 6)G.addEdge(6, 7)G.addEdge(6, 8) G.LongestPathLength()", "e": 13056, "s": 10702, "text": null }, { "code": "<script> // Javascript program to find longest path of the tree // Utility Pair class for storing// maximum distance Node with its distanceclass Pair{ // Constructor constructor(first, second) { this.first = first; this.second = second; }} // This class represents a undirected graph// using adjacency listvar V; // No. of verticesvar adj; //Adjacency List // Constructorfunction initialize(V){ this.V = V; // Initializing Adjacency List adj = Array.from(Array(V), ()=>Array());} // function to add an edge to graphfunction addEdge(s, d){ adj[s].push(d); // push d to s's list. adj[d].push(s); // Since the graph is undirected} // method returns farthest node and// its distance from node ufunction bfs(u){ var dis = Array(V); // mark all distance with -1 for(var i = 0; i < V; i++) dis[i] = -1; var q = []; q.push(u); // distance of u from u will be 0 dis[u] = 0; while (q.length != 0) { var t = q.shift(); // loop for all adjacent nodes of node-t for(var i = 0; i < adj[t].length; ++i) { var v = adj[t][i]; // push node into queue only if // it is not visited already if(dis[v] == -1) { q.push(v); // make distance of v, one more // than distance of t dis[v] = dis[t] + 1; } } } var maxDis = 0; var nodeIdx = 0; // get farthest node distance and its index for(var i = 0; i < V; ++i) { if(dis[i] > maxDis) { maxDis = dis[i]; nodeIdx = i; } } return new Pair(nodeIdx, maxDis);} // method prints longest path of given treefunction longestPathLength(){ var t1, t2; // first bfs to find one end point of // longest path t1 = bfs(0); // second bfs to find actual longest path t2 = bfs(t1.first); document.write(\"longest path is from \" + t1.first + \" to \" + t2.first + \" of length \" + t2.second);} // Create a graph given in the exampleinitialize(10)addEdge(0, 1);addEdge(1, 2);addEdge(2, 3);addEdge(2, 9);addEdge(2, 4);addEdge(4, 5);addEdge(1, 6);addEdge(6, 7);addEdge(6, 8);longestPathLength(); // This code is contributed by famously.</script>", "e": 15408, "s": 13056, "text": null }, { "code": null, "e": 15448, "s": 15408, "text": "Longest path is from 5 to 7 of length 5" }, { "code": null, "e": 15748, "s": 15448, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 15765, "s": 15748, "text": "Brij Raj Kishore" }, { "code": null, "e": 15775, "s": 15765, "text": "Rajput-Ji" }, { "code": null, "e": 15788, "s": 15775, "text": "aadiupadhyay" }, { "code": null, "e": 15797, "s": 15788, "text": "gabaa406" }, { "code": null, "e": 15813, "s": 15797, "text": "saurabh1990aror" }, { "code": null, "e": 15822, "s": 15813, "text": "famously" }, { "code": null, "e": 15839, "s": 15822, "text": "hardikkoriintern" }, { "code": null, "e": 15843, "s": 15839, "text": "BFS" }, { "code": null, "e": 15854, "s": 15843, "text": "n-ary-tree" }, { "code": null, "e": 15859, "s": 15854, "text": "Tree" }, { "code": null, "e": 15864, "s": 15859, "text": "Tree" }, { "code": null, "e": 15868, "s": 15864, "text": "BFS" }, { "code": null, "e": 15966, "s": 15868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15998, "s": 15966, "text": "Introduction to Data Structures" }, { "code": null, "e": 16034, "s": 15998, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 16098, "s": 16034, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 16131, "s": 16098, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 16179, "s": 16131, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 16193, "s": 16179, "text": "Decision Tree" }, { "code": null, "e": 16227, "s": 16193, "text": "Diagonal Traversal of Binary Tree" }, { "code": null, "e": 16285, "s": 16227, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 16327, "s": 16285, "text": "Insertion in a Binary Tree in level order" } ]
How to check if a MySQL database exists?
The schema_name command is used to check if a MySQL database exists or not. The syntax of this command is as follows − select schema_name from information_schema.schemata where schema_name = 'database name'; Now, the above command is used to check whether the database exists or not. The query for that is as follows − Case 1 − The database exists. mysql> select schema_name from information_schema.schemata where schema_name = 'business'; The output obtained is as follows − +-------------+ | SCHEMA_NAME | +-------------+ | business | +-------------+ 1 row in set (0.00 sec) Case 2 − The database does not exist. mysql> select schema_name from information_schema.schemata where schema_name = 'sample2'; Empty set (0.00 sec) Note: We can check how many databases are present in MySQL with the help of the show command. The syntax for the show command is as follows − show databases; The query using the above syntax is as follows − mysql> show databases; The following is the output +--------------------+ | Database | +--------------------+ | business | | hello | | information_schema | | mybusiness | | mysql | | performance_schema | | sample | | sys | | test | +--------------------+ 9 rows in set (0.00 sec) Now, we can choose the name of a particular database with the help of the use command. The query is given as follows − mysql> use business; Database changed We can also check the number of tables that are present in a particular database. This can be done using the show command. The query for this is as follows − mysql> show tables; After executing the above query, the following output is obtained − +----------------------+ | Tables_in_business | +----------------------+ | addcolumntable | | bookindexes | | chardemo | | demo | | demoascii | | demobcrypt | | demoint | | demoschema | | duplicatebookindexes | | existsrowdemo | | foreigntable | | groupdemo | | int1demo | | intdemo | | latandlangdemo | | modifycolumnnamedemo | | modifydatatype | | moviecollection | | mytable | | nthrecorddemo | | nulldemo | | primarytable | | primarytable1 | | smallintdemo | | student | | tblstudent | | tbluni | | textdemo | | texturl | | varchardemo | | varcharurl | +----------------------+ 31 rows in set (0.00 sec) A particular table can be described with the help of the desc command. The syntax for that is as follows − desc yourTableName; Now, the above syntax is used to describe the table. The query for that is − mysql> desc modifydatatype; The following is the output obtained − +----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | YourName | varchar(100) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1306, "s": 1187, "text": "The schema_name command is used to check if a MySQL database exists or not. The syntax of\nthis command is as follows −" }, { "code": null, "e": 1395, "s": 1306, "text": "select schema_name from information_schema.schemata where schema_name = 'database\nname';" }, { "code": null, "e": 1506, "s": 1395, "text": "Now, the above command is used to check whether the database exists or not. The query for\nthat is as follows −" }, { "code": null, "e": 1536, "s": 1506, "text": "Case 1 − The database exists." }, { "code": null, "e": 1628, "s": 1536, "text": "mysql> select schema_name from information_schema.schemata where schema_name = 'business';\n" }, { "code": null, "e": 1664, "s": 1628, "text": "The output obtained is as follows −" }, { "code": null, "e": 1768, "s": 1664, "text": "+-------------+\n| SCHEMA_NAME |\n+-------------+\n| business |\n+-------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1806, "s": 1768, "text": "Case 2 − The database does not exist." }, { "code": null, "e": 1917, "s": 1806, "text": "mysql> select schema_name from information_schema.schemata where schema_name = 'sample2';\nEmpty set (0.00 sec)" }, { "code": null, "e": 2011, "s": 1917, "text": "Note: We can check how many databases are present in MySQL with the help of the show\ncommand." }, { "code": null, "e": 2059, "s": 2011, "text": "The syntax for the show command is as follows −" }, { "code": null, "e": 2076, "s": 2059, "text": "show databases;\n" }, { "code": null, "e": 2125, "s": 2076, "text": "The query using the above syntax is as follows −" }, { "code": null, "e": 2148, "s": 2125, "text": "mysql> show databases;" }, { "code": null, "e": 2176, "s": 2148, "text": "The following is the output" }, { "code": null, "e": 2500, "s": 2176, "text": "+--------------------+\n| Database |\n+--------------------+\n| business |\n| hello |\n| information_schema |\n| mybusiness |\n| mysql |\n| performance_schema |\n| sample |\n| sys |\n| test |\n+--------------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2619, "s": 2500, "text": "Now, we can choose the name of a particular database with the help of the use command.\nThe query is given as follows −" }, { "code": null, "e": 2657, "s": 2619, "text": "mysql> use business;\nDatabase changed" }, { "code": null, "e": 2815, "s": 2657, "text": "We can also check the number of tables that are present in a particular database. This can be\ndone using the show command. The query for this is as follows −" }, { "code": null, "e": 2836, "s": 2815, "text": "mysql> show tables;\n" }, { "code": null, "e": 2904, "s": 2836, "text": "After executing the above query, the following output is obtained −" }, { "code": null, "e": 3805, "s": 2904, "text": "+----------------------+\n| Tables_in_business |\n+----------------------+\n| addcolumntable |\n| bookindexes |\n| chardemo |\n| demo |\n| demoascii |\n| demobcrypt |\n| demoint |\n| demoschema |\n| duplicatebookindexes |\n| existsrowdemo |\n| foreigntable |\n| groupdemo |\n| int1demo |\n| intdemo |\n| latandlangdemo |\n| modifycolumnnamedemo |\n| modifydatatype |\n| moviecollection |\n| mytable |\n| nthrecorddemo |\n| nulldemo |\n| primarytable |\n| primarytable1 |\n| smallintdemo |\n| student |\n| tblstudent |\n| tbluni |\n| textdemo |\n| texturl |\n| varchardemo |\n| varcharurl |\n+----------------------+\n31 rows in set (0.00 sec)" }, { "code": null, "e": 3912, "s": 3805, "text": "A particular table can be described with the help of the desc command. The syntax for that is as\nfollows −" }, { "code": null, "e": 3933, "s": 3912, "text": "desc yourTableName;\n" }, { "code": null, "e": 4010, "s": 3933, "text": "Now, the above syntax is used to describe the table. The query for that is −" }, { "code": null, "e": 4038, "s": 4010, "text": "mysql> desc modifydatatype;" }, { "code": null, "e": 4077, "s": 4038, "text": "The following is the output obtained −" }, { "code": null, "e": 4456, "s": 4077, "text": "+----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------+------+-----+---------+-------+\n| id | int(11) | YES | | NULL | |\n| YourName | varchar(100) | YES | | NULL | |\n+----------+--------------+------+-----+---------+-------+\n2 rows in set (0.00 sec)" } ]
CSS | column-rule Property
29 Apr, 2021 The column-rule property in CSS is used to specify the width, style, and color of the rules between the columns.Syntax: column-rule: column-rule-width column-rule-style column-rule-color| initial|inherit; Property Values: column-rule-width: This value is used to set the width of the rule between the columns. The default value of this property-value is medium. column-rule-style: This value is used to set the style of the rule between columns. The default value of this property-value is none. column-rule-color: This value is used to set the color of the rule between columns. The default value of this property value is the color of the element. initial: This value is used to set default value of this column-rule property. inherit: This value tells the column-rule property to inherit the property from its parent. Example: html <!DOCTYPE html><html><head> <title>The column-rule Property</title> <style> .gfg { -webkit-column-count: 3; -moz-column-count: 3 column-count: 3; -webkit-column-gap: 40px; -moz-column-gap: 40px; column-gap: 40px; -webkit-column-rule: 4px double #ff00ff; -moz-column-rule: 4px double #ff00ff; column-rule: 4px double #ff00ff; } h1 { color:green; } h1, h2 { text-align:center; } </style></head><body> <h1> GeeksforGeeks </h1> <h2> The column-rule Property </h2> <p> The column-rule property sets the width, style, and color of the rule between the columns of the element: </p> <div class="gfg"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div></body></html> Output: Supported Browsers: The browsers supported by column-rule Property are listed below; Google Chrome: 50.0, 4.0 -webkit- Internet Explorer: 10.0 Firefox: 52.0, 2.0 -moz- Opera: 37.0, 15.0 -webkit-, 11.1 Safari: 9.0, 3.1 -webkit- arorakashish0911 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form 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": "\n29 Apr, 2021" }, { "code": null, "e": 150, "s": 28, "text": "The column-rule property in CSS is used to specify the width, style, and color of the rules between the columns.Syntax: " }, { "code": null, "e": 235, "s": 150, "text": "column-rule: column-rule-width column-rule-style column-rule-color|\ninitial|inherit;" }, { "code": null, "e": 254, "s": 235, "text": "Property Values: " }, { "code": null, "e": 394, "s": 254, "text": "column-rule-width: This value is used to set the width of the rule between the columns. The default value of this property-value is medium." }, { "code": null, "e": 528, "s": 394, "text": "column-rule-style: This value is used to set the style of the rule between columns. The default value of this property-value is none." }, { "code": null, "e": 682, "s": 528, "text": "column-rule-color: This value is used to set the color of the rule between columns. The default value of this property value is the color of the element." }, { "code": null, "e": 761, "s": 682, "text": "initial: This value is used to set default value of this column-rule property." }, { "code": null, "e": 853, "s": 761, "text": "inherit: This value tells the column-rule property to inherit the property from its parent." }, { "code": null, "e": 864, "s": 853, "text": "Example: " }, { "code": null, "e": 869, "s": 864, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>The column-rule Property</title> <style> .gfg { -webkit-column-count: 3; -moz-column-count: 3 column-count: 3; -webkit-column-gap: 40px; -moz-column-gap: 40px; column-gap: 40px; -webkit-column-rule: 4px double #ff00ff; -moz-column-rule: 4px double #ff00ff; column-rule: 4px double #ff00ff; } h1 { color:green; } h1, h2 { text-align:center; } </style></head><body> <h1> GeeksforGeeks </h1> <h2> The column-rule Property </h2> <p> The column-rule property sets the width, style, and color of the rule between the columns of the element: </p> <div class=\"gfg\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div></body></html> ", "e": 1998, "s": 869, "text": null }, { "code": null, "e": 2008, "s": 1998, "text": "Output: " }, { "code": null, "e": 2094, "s": 2008, "text": "Supported Browsers: The browsers supported by column-rule Property are listed below; " }, { "code": null, "e": 2128, "s": 2094, "text": "Google Chrome: 50.0, 4.0 -webkit-" }, { "code": null, "e": 2152, "s": 2128, "text": "Internet Explorer: 10.0" }, { "code": null, "e": 2177, "s": 2152, "text": "Firefox: 52.0, 2.0 -moz-" }, { "code": null, "e": 2210, "s": 2177, "text": "Opera: 37.0, 15.0 -webkit-, 11.1" }, { "code": null, "e": 2236, "s": 2210, "text": "Safari: 9.0, 3.1 -webkit-" }, { "code": null, "e": 2255, "s": 2238, "text": "arorakashish0911" }, { "code": null, "e": 2270, "s": 2255, "text": "CSS-Properties" }, { "code": null, "e": 2277, "s": 2270, "text": "Picked" }, { "code": null, "e": 2281, "s": 2277, "text": "CSS" }, { "code": null, "e": 2298, "s": 2281, "text": "Web Technologies" }, { "code": null, "e": 2396, "s": 2298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2444, "s": 2396, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2506, "s": 2444, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2556, "s": 2506, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2614, "s": 2556, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2664, "s": 2614, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2697, "s": 2664, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2759, "s": 2697, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2820, "s": 2759, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2870, "s": 2820, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
StringJoiner toString() method in Java
12 Dec, 2021 The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returnedSyntax: public String toString() Returns: This method returns the string representation of this StringJoinerBelow programs illustrate the toString() method:Example 1: To demonstrate toString() with delimiter ” ” Java // Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG { public static void main(String[] args) { // Creating StringJoiner with delimiter " " StringJoiner str = new StringJoiner(" "); // Adding elements in the StringJoiner str.add("Geeks"); str.add("for"); str.add("Geeks"); // Print the StringJoiner // using toString() method System.out.println("StringJoiner: " + str.toString()); }} StringJoiner: Geeks for Geeks Example 2: To demonstrate toString() with delimiter “, “ Java // Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG { public static void main(String[] args) { // Creating StringJoiner with delimiter "" StringJoiner str = new StringJoiner(", "); // Adding elements in the StringJoiner str.add("Geeks"); str.add("for"); str.add("Geeks"); str.add("A"); str.add("Computer"); str.add("Portal"); // Print the StringJoiner // using toString() method System.out.println("StringJoiner: " + str.toString()); }} StringJoiner: Geeks, for, Geeks, A, Computer, Portal akshaysingh98088 Java - util package Java-Functions Java-StringJoiner Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Dec, 2021" }, { "code": null, "e": 371, "s": 53, "text": "The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returnedSyntax: " }, { "code": null, "e": 396, "s": 371, "text": "public String toString()" }, { "code": null, "e": 576, "s": 396, "text": "Returns: This method returns the string representation of this StringJoinerBelow programs illustrate the toString() method:Example 1: To demonstrate toString() with delimiter ” ” " }, { "code": null, "e": 581, "s": 576, "text": "Java" }, { "code": "// Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG { public static void main(String[] args) { // Creating StringJoiner with delimiter \" \" StringJoiner str = new StringJoiner(\" \"); // Adding elements in the StringJoiner str.add(\"Geeks\"); str.add(\"for\"); str.add(\"Geeks\"); // Print the StringJoiner // using toString() method System.out.println(\"StringJoiner: \" + str.toString()); }}", "e": 1128, "s": 581, "text": null }, { "code": null, "e": 1158, "s": 1128, "text": "StringJoiner: Geeks for Geeks" }, { "code": null, "e": 1217, "s": 1160, "text": "Example 2: To demonstrate toString() with delimiter “, “" }, { "code": null, "e": 1222, "s": 1217, "text": "Java" }, { "code": "// Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG { public static void main(String[] args) { // Creating StringJoiner with delimiter \"\" StringJoiner str = new StringJoiner(\", \"); // Adding elements in the StringJoiner str.add(\"Geeks\"); str.add(\"for\"); str.add(\"Geeks\"); str.add(\"A\"); str.add(\"Computer\"); str.add(\"Portal\"); // Print the StringJoiner // using toString() method System.out.println(\"StringJoiner: \" + str.toString()); }}", "e": 1844, "s": 1222, "text": null }, { "code": null, "e": 1897, "s": 1844, "text": "StringJoiner: Geeks, for, Geeks, A, Computer, Portal" }, { "code": null, "e": 1916, "s": 1899, "text": "akshaysingh98088" }, { "code": null, "e": 1936, "s": 1916, "text": "Java - util package" }, { "code": null, "e": 1951, "s": 1936, "text": "Java-Functions" }, { "code": null, "e": 1969, "s": 1951, "text": "Java-StringJoiner" }, { "code": null, "e": 1974, "s": 1969, "text": "Java" }, { "code": null, "e": 1979, "s": 1974, "text": "Java" }, { "code": null, "e": 2077, "s": 1979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2128, "s": 2077, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2159, "s": 2128, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2178, "s": 2159, "text": "Interfaces in Java" }, { "code": null, "e": 2208, "s": 2178, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2223, "s": 2208, "text": "Stream In Java" }, { "code": null, "e": 2241, "s": 2223, "text": "ArrayList in Java" }, { "code": null, "e": 2261, "s": 2241, "text": "Collections in Java" }, { "code": null, "e": 2285, "s": 2261, "text": "Singleton Class in Java" }, { "code": null, "e": 2317, "s": 2285, "text": "Multidimensional Arrays in Java" } ]
How to use Iterator in Java?
18 Jul, 2018 ‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.java.util package has public interface Iterator and contains three methods: boolean hasNext(): It returns true if Iterator has more element to iterate.Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked. boolean hasNext(): It returns true if Iterator has more element to iterate. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element. void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked. // Java code to illustrate the use of iteratorimport java.io.*;import java.util.*; class Test { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); // Iterator to traverse the list Iterator iterator = list.iterator(); System.out.println("List elements : "); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println(); }} Output: List elements : A B C D E ListIterator ‘ListIterator’ in Java is an Iterator which allows users to traverse Collection in both direction. It contains the following methods: void add(Object object): It inserts object immediately before the element that is returned by the next( ) function.boolean hasNext( ): It returns true if the list has a next element.boolean hasPrevious( ): It returns true if the list has a previous element.Object next( ): It returns the next element of the list. It throws ‘NoSuchElementException’ if there is no next element in the list.Object previous( ): It returns the previous element of the list. It throws ‘NoSuchElementException’ if there is no previous element.void remove( ): It removes the current element from the list. It throws ‘IllegalStateException’ if this function is called before next( ) or previous( ) is invoked. void add(Object object): It inserts object immediately before the element that is returned by the next( ) function. boolean hasNext( ): It returns true if the list has a next element. boolean hasPrevious( ): It returns true if the list has a previous element. Object next( ): It returns the next element of the list. It throws ‘NoSuchElementException’ if there is no next element in the list. Object previous( ): It returns the previous element of the list. It throws ‘NoSuchElementException’ if there is no previous element. void remove( ): It removes the current element from the list. It throws ‘IllegalStateException’ if this function is called before next( ) or previous( ) is invoked. // Java code to illustrate the use of ListIteratorimport java.io.*;import java.util.*; class Test { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); // ListIterator to traverse the list ListIterator iterator = list.listIterator(); // Traversing the list in forward direction System.out.println("Displaying list elements in forward direction : "); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println(); // Traversing the list in backward direction System.out.println("Displaying list elements in backward direction : "); while (iterator.hasPrevious()) System.out.print(iterator.previous() + " "); System.out.println(); }} Output: Displaying list elements in forward direction : A B C D E Displaying list elements in backward direction : E D C B A Related Articles: Iterators in Java Iterator vs Foreach In Java Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator) This article is contributed by Mehak Narang. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ShreyasWaghmare Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jul, 2018" }, { "code": null, "e": 306, "s": 52, "text": "‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.java.util package has public interface Iterator and contains three methods:" }, { "code": null, "e": 715, "s": 306, "text": "boolean hasNext(): It returns true if Iterator has more element to iterate.Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked." }, { "code": null, "e": 791, "s": 715, "text": "boolean hasNext(): It returns true if Iterator has more element to iterate." }, { "code": null, "e": 964, "s": 791, "text": "Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element." }, { "code": null, "e": 1126, "s": 964, "text": "void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked." }, { "code": "// Java code to illustrate the use of iteratorimport java.io.*;import java.util.*; class Test { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); list.add(\"E\"); // Iterator to traverse the list Iterator iterator = list.iterator(); System.out.println(\"List elements : \"); while (iterator.hasNext()) System.out.print(iterator.next() + \" \"); System.out.println(); }}", "e": 1699, "s": 1126, "text": null }, { "code": null, "e": 1707, "s": 1699, "text": "Output:" }, { "code": null, "e": 1735, "s": 1707, "text": "List elements : \nA B C D E " }, { "code": null, "e": 1748, "s": 1735, "text": "ListIterator" }, { "code": null, "e": 1882, "s": 1748, "text": "‘ListIterator’ in Java is an Iterator which allows users to traverse Collection in both direction. It contains the following methods:" }, { "code": null, "e": 2568, "s": 1882, "text": "void add(Object object): It inserts object immediately before the element that is returned by the next( ) function.boolean hasNext( ): It returns true if the list has a next element.boolean hasPrevious( ): It returns true if the list has a previous element.Object next( ): It returns the next element of the list. It throws ‘NoSuchElementException’ if there is no next element in the list.Object previous( ): It returns the previous element of the list. It throws ‘NoSuchElementException’ if there is no previous element.void remove( ): It removes the current element from the list. It throws ‘IllegalStateException’ if this function is called before next( ) or previous( ) is invoked." }, { "code": null, "e": 2684, "s": 2568, "text": "void add(Object object): It inserts object immediately before the element that is returned by the next( ) function." }, { "code": null, "e": 2752, "s": 2684, "text": "boolean hasNext( ): It returns true if the list has a next element." }, { "code": null, "e": 2828, "s": 2752, "text": "boolean hasPrevious( ): It returns true if the list has a previous element." }, { "code": null, "e": 2961, "s": 2828, "text": "Object next( ): It returns the next element of the list. It throws ‘NoSuchElementException’ if there is no next element in the list." }, { "code": null, "e": 3094, "s": 2961, "text": "Object previous( ): It returns the previous element of the list. It throws ‘NoSuchElementException’ if there is no previous element." }, { "code": null, "e": 3259, "s": 3094, "text": "void remove( ): It removes the current element from the list. It throws ‘IllegalStateException’ if this function is called before next( ) or previous( ) is invoked." }, { "code": "// Java code to illustrate the use of ListIteratorimport java.io.*;import java.util.*; class Test { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); list.add(\"E\"); // ListIterator to traverse the list ListIterator iterator = list.listIterator(); // Traversing the list in forward direction System.out.println(\"Displaying list elements in forward direction : \"); while (iterator.hasNext()) System.out.print(iterator.next() + \" \"); System.out.println(); // Traversing the list in backward direction System.out.println(\"Displaying list elements in backward direction : \"); while (iterator.hasPrevious()) System.out.print(iterator.previous() + \" \"); System.out.println(); }}", "e": 4192, "s": 3259, "text": null }, { "code": null, "e": 4200, "s": 4192, "text": "Output:" }, { "code": null, "e": 4321, "s": 4200, "text": "Displaying list elements in forward direction : \nA B C D E \nDisplaying list elements in backward direction : \nE D C B A " }, { "code": null, "e": 4340, "s": 4321, "text": " Related Articles:" }, { "code": null, "e": 4358, "s": 4340, "text": "Iterators in Java" }, { "code": null, "e": 4386, "s": 4358, "text": "Iterator vs Foreach In Java" }, { "code": null, "e": 4487, "s": 4386, "text": "Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator)" }, { "code": null, "e": 4656, "s": 4487, "text": "This article is contributed by Mehak Narang. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4672, "s": 4656, "text": "ShreyasWaghmare" }, { "code": null, "e": 4689, "s": 4672, "text": "Java-Collections" }, { "code": null, "e": 4694, "s": 4689, "text": "Java" }, { "code": null, "e": 4699, "s": 4694, "text": "Java" }, { "code": null, "e": 4716, "s": 4699, "text": "Java-Collections" }, { "code": null, "e": 4814, "s": 4716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4865, "s": 4814, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4896, "s": 4865, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4915, "s": 4896, "text": "Interfaces in Java" }, { "code": null, "e": 4945, "s": 4915, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4960, "s": 4945, "text": "Stream In Java" }, { "code": null, "e": 4978, "s": 4960, "text": "ArrayList in Java" }, { "code": null, "e": 4998, "s": 4978, "text": "Collections in Java" }, { "code": null, "e": 5022, "s": 4998, "text": "Singleton Class in Java" }, { "code": null, "e": 5054, "s": 5022, "text": "Multidimensional Arrays in Java" } ]
MATLAB - Inverse of a Matrix
The inverse of a matrix A is denoted by A−1 such that the following relationship holds − AA−1 = A−1A = 1 The inverse of a matrix does not always exist. If the determinant of the matrix is zero, then the inverse does not exist and the matrix is singular. Inverse of a matrix in MATLAB is calculated using the inv function. Inverse of a matrix A is given by inv(A). Create a script file and type the following code − a = [ 1 2 3; 2 3 4; 1 2 5] inv(a) When you run the file, it displays the following result − a = 1 2 3 2 3 4 1 2 5 ans = -3.5000 2.0000 0.5000 3.0000 -1.0000 -1.0000 -0.5000 0 0.5000
[ { "code": null, "e": 2364, "s": 2275, "text": "The inverse of a matrix A is denoted by A−1 such that the following relationship holds −" }, { "code": null, "e": 2380, "s": 2364, "text": "AA−1 = A−1A = 1" }, { "code": null, "e": 2529, "s": 2380, "text": "The inverse of a matrix does not always exist. If the determinant of the matrix is zero, then the inverse does not exist and the matrix is singular." }, { "code": null, "e": 2639, "s": 2529, "text": "Inverse of a matrix in MATLAB is calculated using the inv function. Inverse of a matrix A is given by inv(A)." }, { "code": null, "e": 2690, "s": 2639, "text": "Create a script file and type the following code −" }, { "code": null, "e": 2724, "s": 2690, "text": "a = [ 1 2 3; 2 3 4; 1 2 5]\ninv(a)" }, { "code": null, "e": 2782, "s": 2724, "text": "When you run the file, it displays the following result −" } ]
JavaScript String substring() Method
07 Oct, 2021 The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). Syntax: string.substring(Startindex, Endindex) Parameters: Here the Startindex and Endindex describes the part of the string to be taken as substring. Here the Endindex is optional. Return value: It returns a new string which is part of the given string. JavaScript code to show the working of string.substring() function: Code #1: javascript <script> // Taking a string as variable var string = "geeksforgeeks"; a = string.substring(0, 4) b = string.substring(1, 6) c = string.substring(5) d = string.substring(0) // Printing new string which are // the part of the given string document.write(a + "<br>"); document.write(b + "<br>"); document.write(c + "<br>"); document.write(d + "<br>"); </script> Output: geek eeksf forgeeks geeksforgeeks Code #2: Index always start with 0. If still we take index as negative, it will be considered as zero and index can’t be in fraction if it found so, it will be converted into its just lesser whole number. javascript <script> // Taking a string as variable var string = "geeksforgeeks"; a = string.substring(-1) b = string.substring(2.5) c = string.substring(2.9) // Printing new string which are // the part of the given string document.write(a + "<br>"); document.write(b + "<br>"); document.write(c + "<br>"); </script> Output: geeksforgeeks eksforgeeks eksforgeeks Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Opera 3 and above Safari 1 and above arorakashish0911 ysachin2314 javascript-string JavaScript 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 Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? Node.js | fs.writeFileSync() Method JavaScript | Promises How to filter object array based on attributes? How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Oct, 2021" }, { "code": null, "e": 236, "s": 52, "text": "The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). Syntax: " }, { "code": null, "e": 275, "s": 236, "text": "string.substring(Startindex, Endindex)" }, { "code": null, "e": 562, "s": 275, "text": "Parameters: Here the Startindex and Endindex describes the part of the string to be taken as substring. Here the Endindex is optional. Return value: It returns a new string which is part of the given string. JavaScript code to show the working of string.substring() function: Code #1: " }, { "code": null, "e": 573, "s": 562, "text": "javascript" }, { "code": "<script> // Taking a string as variable var string = \"geeksforgeeks\"; a = string.substring(0, 4) b = string.substring(1, 6) c = string.substring(5) d = string.substring(0) // Printing new string which are // the part of the given string document.write(a + \"<br>\"); document.write(b + \"<br>\"); document.write(c + \"<br>\"); document.write(d + \"<br>\"); </script> ", "e": 989, "s": 573, "text": null }, { "code": null, "e": 999, "s": 989, "text": "Output: " }, { "code": null, "e": 1033, "s": 999, "text": "geek\neeksf\nforgeeks\ngeeksforgeeks" }, { "code": null, "e": 1240, "s": 1033, "text": "Code #2: Index always start with 0. If still we take index as negative, it will be considered as zero and index can’t be in fraction if it found so, it will be converted into its just lesser whole number. " }, { "code": null, "e": 1251, "s": 1240, "text": "javascript" }, { "code": "<script> // Taking a string as variable var string = \"geeksforgeeks\"; a = string.substring(-1) b = string.substring(2.5) c = string.substring(2.9) // Printing new string which are // the part of the given string document.write(a + \"<br>\"); document.write(b + \"<br>\"); document.write(c + \"<br>\"); </script> ", "e": 1608, "s": 1251, "text": null }, { "code": null, "e": 1618, "s": 1608, "text": "Output: " }, { "code": null, "e": 1656, "s": 1618, "text": "geeksforgeeks\neksforgeeks\neksforgeeks" }, { "code": null, "e": 1677, "s": 1658, "text": "Supported Browser:" }, { "code": null, "e": 1696, "s": 1677, "text": "Chrome 1 and above" }, { "code": null, "e": 1714, "s": 1696, "text": "Edge 12 and above" }, { "code": null, "e": 1734, "s": 1714, "text": "Firefox 1 and above" }, { "code": null, "e": 1764, "s": 1734, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 1782, "s": 1764, "text": "Opera 3 and above" }, { "code": null, "e": 1801, "s": 1782, "text": "Safari 1 and above" }, { "code": null, "e": 1818, "s": 1801, "text": "arorakashish0911" }, { "code": null, "e": 1830, "s": 1818, "text": "ysachin2314" }, { "code": null, "e": 1848, "s": 1830, "text": "javascript-string" }, { "code": null, "e": 1859, "s": 1848, "text": "JavaScript" }, { "code": null, "e": 1957, "s": 1859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2018, "s": 1957, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2090, "s": 2018, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2130, "s": 2090, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2171, "s": 2130, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2213, "s": 2171, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2267, "s": 2213, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 2303, "s": 2267, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 2325, "s": 2303, "text": "JavaScript | Promises" }, { "code": null, "e": 2373, "s": 2325, "text": "How to filter object array based on attributes?" } ]
Python | Word Embedding using Word2Vec
16 May, 2022 Word Embedding is a language modeling technique used for mapping words to vectors of real numbers. It represents words or phrases in vector space with several dimensions. Word embeddings can be generated using various methods like neural networks, co-occurrence matrix, probabilistic models, etc. Word2Vec consists of models for generating word embedding. These models are shallow two-layer neural networks having one input layer, one hidden layer, and one output layer. Word2Vec utilizes two architectures : CBOW (Continuous Bag of Words): CBOW model predicts the current word given context words within a specific window. The input layer contains the context words and the output layer contains the current word. The hidden layer contains the number of dimensions in which we want to represent the current word present at the output layer. Skip Gram : Skip gram predicts the surrounding context words within specific window given current word. The input layer contains the current word and the output layer contains the context words. The hidden layer contains the number of dimensions in which we want to represent current word present at the input layer. The basic idea of word embedding is words that occur in similar context tend to be closer to each other in vector space. For generating word vectors in Python, modules needed are nltk and gensim. Run these commands in terminal to install nltk and gensim : pip install nltk pip install gensim Download the text file used for generating word vectors from here . Below is the implementation : Python # Python program to generate word vectors using Word2Vec # importing all necessary modulesfrom nltk.tokenize import sent_tokenize, word_tokenizeimport warnings warnings.filterwarnings(action = 'ignore') import gensimfrom gensim.models import Word2Vec # Reads ‘alice.txt’ filesample = open("C:\\Users\\Admin\\Desktop\\alice.txt", "utf8")s = sample.read() # Replaces escape character with spacef = s.replace("\n", " ") data = [] # iterate through each sentence in the filefor i in sent_tokenize(f): temp = [] # tokenize the sentence into words for j in word_tokenize(i): temp.append(j.lower()) data.append(temp) # Create CBOW modelmodel1 = gensim.models.Word2Vec(data, min_count = 1, vector_size = 100, window = 5) # Print resultsprint("Cosine similarity between 'alice' " + "and 'wonderland' - CBOW : ", model1.wv.similarity('alice', 'wonderland')) print("Cosine similarity between 'alice' " + "and 'machines' - CBOW : ", model1.wv.similarity('alice', 'machines')) # Create Skip Gram modelmodel2 = gensim.models.Word2Vec(data, min_count = 1, vector_size = 100, window = 5, sg = 1) # Print resultsprint("Cosine similarity between 'alice' " + "and 'wonderland' - Skip Gram : ", model2.wv.similarity('alice', 'wonderland')) print("Cosine similarity between 'alice' " + "and 'machines' - Skip Gram : ", model2.wv.similarity('alice', 'machines')) Output : Cosine similarity between 'alice' and 'wonderland' - CBOW : 0.999249298413 Cosine similarity between 'alice' and 'machines' - CBOW : 0.974911910445 Cosine similarity between 'alice' and 'wonderland' - Skip Gram : 0.885471373104 Cosine similarity between 'alice' and 'machines' - Skip Gram : 0.856892599521 Output indicates the cosine similarities between word vectors ‘alice’, ‘wonderland’ and ‘machines’ for different models. One interesting task might be to change the parameter values of ‘size’ and ‘window’ to observe the variations in the cosine similarities. Applications of Word Embedding : >> Sentiment Analysis >> Speech Recognition >> Information Retrieval >> Question Answering References : https://en.wikipedia.org/wiki/Word_embedding https://en.wikipedia.org/wiki/Word2vec crigsby Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2022" }, { "code": null, "e": 537, "s": 28, "text": "Word Embedding is a language modeling technique used for mapping words to vectors of real numbers. It represents words or phrases in vector space with several dimensions. Word embeddings can be generated using various methods like neural networks, co-occurrence matrix, probabilistic models, etc. Word2Vec consists of models for generating word embedding. These models are shallow two-layer neural networks having one input layer, one hidden layer, and one output layer. Word2Vec utilizes two architectures :" }, { "code": null, "e": 871, "s": 537, "text": "CBOW (Continuous Bag of Words): CBOW model predicts the current word given context words within a specific window. The input layer contains the context words and the output layer contains the current word. The hidden layer contains the number of dimensions in which we want to represent the current word present at the output layer. " }, { "code": null, "e": 932, "s": 871, "text": "Skip Gram : Skip gram predicts the surrounding context words" }, { "code": null, "e": 1190, "s": 932, "text": " within specific window given current word. The input layer contains the current word and the output layer contains the context words. The hidden layer contains the number of dimensions in which we want to represent current word present at the input layer. " }, { "code": null, "e": 1446, "s": 1190, "text": "The basic idea of word embedding is words that occur in similar context tend to be closer to each other in vector space. For generating word vectors in Python, modules needed are nltk and gensim. Run these commands in terminal to install nltk and gensim :" }, { "code": null, "e": 1482, "s": 1446, "text": "pip install nltk\npip install gensim" }, { "code": null, "e": 1583, "s": 1482, "text": " Download the text file used for generating word vectors from here . Below is the implementation : " }, { "code": null, "e": 1590, "s": 1583, "text": "Python" }, { "code": "# Python program to generate word vectors using Word2Vec # importing all necessary modulesfrom nltk.tokenize import sent_tokenize, word_tokenizeimport warnings warnings.filterwarnings(action = 'ignore') import gensimfrom gensim.models import Word2Vec # Reads ‘alice.txt’ filesample = open(\"C:\\\\Users\\\\Admin\\\\Desktop\\\\alice.txt\", \"utf8\")s = sample.read() # Replaces escape character with spacef = s.replace(\"\\n\", \" \") data = [] # iterate through each sentence in the filefor i in sent_tokenize(f): temp = [] # tokenize the sentence into words for j in word_tokenize(i): temp.append(j.lower()) data.append(temp) # Create CBOW modelmodel1 = gensim.models.Word2Vec(data, min_count = 1, vector_size = 100, window = 5) # Print resultsprint(\"Cosine similarity between 'alice' \" + \"and 'wonderland' - CBOW : \", model1.wv.similarity('alice', 'wonderland')) print(\"Cosine similarity between 'alice' \" + \"and 'machines' - CBOW : \", model1.wv.similarity('alice', 'machines')) # Create Skip Gram modelmodel2 = gensim.models.Word2Vec(data, min_count = 1, vector_size = 100, window = 5, sg = 1) # Print resultsprint(\"Cosine similarity between 'alice' \" + \"and 'wonderland' - Skip Gram : \", model2.wv.similarity('alice', 'wonderland')) print(\"Cosine similarity between 'alice' \" + \"and 'machines' - Skip Gram : \", model2.wv.similarity('alice', 'machines'))", "e": 3104, "s": 1590, "text": null }, { "code": null, "e": 3113, "s": 3104, "text": "Output :" }, { "code": null, "e": 3423, "s": 3113, "text": "Cosine similarity between 'alice' and 'wonderland' - CBOW : 0.999249298413\nCosine similarity between 'alice' and 'machines' - CBOW : 0.974911910445\nCosine similarity between 'alice' and 'wonderland' - Skip Gram : 0.885471373104\nCosine similarity between 'alice' and 'machines' - Skip Gram : 0.856892599521" }, { "code": null, "e": 3684, "s": 3423, "text": "Output indicates the cosine similarities between word vectors ‘alice’, ‘wonderland’ and ‘machines’ for different models. One interesting task might be to change the parameter values of ‘size’ and ‘window’ to observe the variations in the cosine similarities. " }, { "code": null, "e": 3809, "s": 3684, "text": "Applications of Word Embedding :\n\n>> Sentiment Analysis\n>> Speech Recognition\n>> Information Retrieval\n>> Question Answering" }, { "code": null, "e": 3822, "s": 3809, "text": "References :" }, { "code": null, "e": 3867, "s": 3822, "text": "https://en.wikipedia.org/wiki/Word_embedding" }, { "code": null, "e": 3906, "s": 3867, "text": "https://en.wikipedia.org/wiki/Word2vec" }, { "code": null, "e": 3914, "s": 3906, "text": "crigsby" }, { "code": null, "e": 3935, "s": 3914, "text": "Python-Miscellaneous" }, { "code": null, "e": 3942, "s": 3935, "text": "Python" }, { "code": null, "e": 4040, "s": 3942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4058, "s": 4040, "text": "Python Dictionary" }, { "code": null, "e": 4100, "s": 4058, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4122, "s": 4100, "text": "Enumerate() in Python" }, { "code": null, "e": 4148, "s": 4122, "text": "Python String | replace()" }, { "code": null, "e": 4180, "s": 4148, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4209, "s": 4180, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4236, "s": 4209, "text": "Python Classes and Objects" }, { "code": null, "e": 4257, "s": 4236, "text": "Python OOPs Concepts" }, { "code": null, "e": 4293, "s": 4257, "text": "Convert integer to string in Python" } ]
Node.js Query String
07 Feb, 2022 The Query String module used to provides utilities for parsing and formatting URL query strings.It can be used to convert query string into JSON object and vice-versa. The Query String is the part of the URL that starts after the question mark(?). Requiring Module: You can include the module using the following code: const querystring = require('querystring'); Note: It’s not a global object, so need to install it explicitly. Install Module: npm install querystring Example 1: Using parse(): Javascript // Importing the modelsimport url from 'url'import querystring from 'querystring' // A URL is takenlet exampleUrl ='http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2'; //Parse the whole URLlet parsed_Url = url.parse(exampleUrl); // Parse only querystring.let parsed_queryString = querystring.parse(parsed_Url.query); // Print the result.console.log("This is parsed URL :",parsed_Url); console.log("This is parsed Query String :",parsed_queryString); Output: This is parsed URL : Url { protocol: 'http:', slashes: true, auth: null, host: 'www.company.com:81', port: '81', hostname: 'www.company.com', hash: '#p2', search: '?user=GEEKSFORGEEKS&year=2021', query: 'user=GEEKSFORGEEKS&year=2021', pathname: '/a/b/c.html', path: '/a/b/c.html?user=GEEKSFORGEEKS&year=2021', href: 'http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2' } This is parsed Query String : [Object: null prototype] { user: 'GEEKSFORGEEKS', year: '2021' } Example 2: Using stringify(): Javascript // Importing the modelimport querystring from 'querystring' // Specify the object// to be serializedconst q2=querystring.stringify({ name:'Testing', company:'GeeksforGeeks', content:'Article', date:'9thMarch2021' }); // Print the result.console.log(q2); Output: name=Testing&company=GeeksforGeeks& content=Article&date=9thMarch2021 Reference: https://nodejs.org/api/querystring.html varshagumber28 Node.js- querystring-Module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2022" }, { "code": null, "e": 197, "s": 28, "text": "The Query String module used to provides utilities for parsing and formatting URL query strings.It can be used to convert query string into JSON object and vice-versa. " }, { "code": null, "e": 277, "s": 197, "text": "The Query String is the part of the URL that starts after the question mark(?)." }, { "code": null, "e": 349, "s": 277, "text": "Requiring Module: You can include the module using the following code: " }, { "code": null, "e": 393, "s": 349, "text": "const querystring = require('querystring');" }, { "code": null, "e": 477, "s": 393, "text": "Note: It’s not a global object, so need to install it explicitly. Install Module: " }, { "code": null, "e": 501, "s": 477, "text": "npm install querystring" }, { "code": null, "e": 529, "s": 503, "text": "Example 1: Using parse():" }, { "code": null, "e": 542, "s": 531, "text": "Javascript" }, { "code": "// Importing the modelsimport url from 'url'import querystring from 'querystring' // A URL is takenlet exampleUrl ='http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2'; //Parse the whole URLlet parsed_Url = url.parse(exampleUrl); // Parse only querystring.let parsed_queryString = querystring.parse(parsed_Url.query); // Print the result.console.log(\"This is parsed URL :\",parsed_Url); console.log(\"This is parsed Query String :\",parsed_queryString);", "e": 1011, "s": 542, "text": null }, { "code": null, "e": 1020, "s": 1011, "text": "Output: " }, { "code": null, "e": 1545, "s": 1020, "text": "This is parsed URL : Url {\n protocol: 'http:',\n slashes: true,\n auth: null,\n host: 'www.company.com:81',\n port: '81',\n hostname: 'www.company.com',\n hash: '#p2',\n search: '?user=GEEKSFORGEEKS&year=2021',\n query: 'user=GEEKSFORGEEKS&year=2021',\n pathname: '/a/b/c.html',\n path: '/a/b/c.html?user=GEEKSFORGEEKS&year=2021',\n href: \n'http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2'\n}\nThis is parsed Query String : [Object: null prototype] \n { user: 'GEEKSFORGEEKS', year: '2021' }" }, { "code": null, "e": 1578, "s": 1547, "text": "Example 2: Using stringify(): " }, { "code": null, "e": 1591, "s": 1580, "text": "Javascript" }, { "code": "// Importing the modelimport querystring from 'querystring' // Specify the object// to be serializedconst q2=querystring.stringify({ name:'Testing', company:'GeeksforGeeks', content:'Article', date:'9thMarch2021' }); // Print the result.console.log(q2);", "e": 1981, "s": 1591, "text": null }, { "code": null, "e": 1991, "s": 1981, "text": "Output: " }, { "code": null, "e": 2061, "s": 1991, "text": "name=Testing&company=GeeksforGeeks&\ncontent=Article&date=9thMarch2021" }, { "code": null, "e": 2113, "s": 2061, "text": "Reference: https://nodejs.org/api/querystring.html " }, { "code": null, "e": 2128, "s": 2113, "text": "varshagumber28" }, { "code": null, "e": 2156, "s": 2128, "text": "Node.js- querystring-Module" }, { "code": null, "e": 2164, "s": 2156, "text": "Node.js" }, { "code": null, "e": 2181, "s": 2164, "text": "Web Technologies" } ]
Bootstrap - Button Dropdowns
This chapter will discuss about how to add dropdown menu to buttons using Bootstrap classes. To add a dropdown to a button, simply wrap the button and dropdown menu in a .btn-group. You can also use <span class = "caret"></span> to act as an indicator that the button is a dropdown. The following example demonstrates a basic single button dropdowns − <div class = "btn-group"> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown"> Default <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> <div class = "btn-group"> <button type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown"> Primary <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link Split button dropdowns use the same general style as the dropdown button but add a primary action along with the dropdown. Split buttons have the primary action on the left and a toggle on the right that displays the dropdown. <div class = "btn-group"> <button type = "button" class = "btn btn-default">Default</button> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown"> <span class = "caret"></span> <span class = "sr-only">Toggle Dropdown</span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> <div class = "btn-group"> <button type = "button" class = "btn btn-primary">Primary</button> <button type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown"> <span class = "caret"></span> <span class = "sr-only">Toggle Dropdown</span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link You can use the dropdowns with any button size − .btn-large, .btn-sm, or .btn-xs. <div class = "btn-group"> <button type = "button" class = "btn btn-default dropdown-toggle btn-lg" data-toggle = "dropdown"> Default <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> <div class = "btn-group"> <button type = "button" class = "btn btn-primary dropdown-toggle btn-sm" data-toggle = "dropdown"> Primary <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> <div class = "btn-group"> <button type = "button" class = "btn btn-success dropdown-toggle btn-xs" data-toggle = "dropdown"> Success <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link Action Another action Something else here Separated link Menus can also be built to drop up rather than down. To achieve this, simply add .dropup to the parent .btn-group container. <div class = "row" style = "margin-left:50px; margin-top:200px"> <div class = "btn-group dropup"> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown"> Default <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> <div class = "btn-group dropup"> <button type = "button" class = "btn btn-primary dropdown-toggle" data-toggle = "dropdown"> Primary <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3614, "s": 3331, "text": "This chapter will discuss about how to add dropdown menu to buttons using Bootstrap classes. To add a dropdown to a button, simply wrap the button and dropdown menu in a .btn-group. You can also use <span class = \"caret\"></span> to act as an indicator that the button is a dropdown." }, { "code": null, "e": 3683, "s": 3614, "text": "The following example demonstrates a basic single button dropdowns −" }, { "code": null, "e": 4654, "s": 3683, "text": "<div class = \"btn-group\">\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n Default \n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n</div>\n\n<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-primary dropdown-toggle\" data-toggle = \"dropdown\">\n Primary \n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n</div>" }, { "code": null, "e": 4661, "s": 4654, "text": "Action" }, { "code": null, "e": 4676, "s": 4661, "text": "Another action" }, { "code": null, "e": 4696, "s": 4676, "text": "Something else here" }, { "code": null, "e": 4711, "s": 4696, "text": "Separated link" }, { "code": null, "e": 4718, "s": 4711, "text": "Action" }, { "code": null, "e": 4733, "s": 4718, "text": "Another action" }, { "code": null, "e": 4753, "s": 4733, "text": "Something else here" }, { "code": null, "e": 4768, "s": 4753, "text": "Separated link" }, { "code": null, "e": 4995, "s": 4768, "text": "Split button dropdowns use the same general style as the dropdown button but add a primary action along with the dropdown. Split buttons have the primary action on the left and a toggle on the right that displays the dropdown." }, { "code": null, "e": 6182, "s": 4995, "text": "<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-default\">Default</button>\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n</div>\n\n<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-primary\">Primary</button>\n \n <button type = \"button\" class = \"btn btn-primary dropdown-toggle\" data-toggle = \"dropdown\">\n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n</div>" }, { "code": null, "e": 6189, "s": 6182, "text": "Action" }, { "code": null, "e": 6204, "s": 6189, "text": "Another action" }, { "code": null, "e": 6224, "s": 6204, "text": "Something else here" }, { "code": null, "e": 6239, "s": 6224, "text": "Separated link" }, { "code": null, "e": 6246, "s": 6239, "text": "Action" }, { "code": null, "e": 6261, "s": 6246, "text": "Another action" }, { "code": null, "e": 6281, "s": 6261, "text": "Something else here" }, { "code": null, "e": 6296, "s": 6281, "text": "Separated link" }, { "code": null, "e": 6378, "s": 6296, "text": "You can use the dropdowns with any button size − .btn-large, .btn-sm, or .btn-xs." }, { "code": null, "e": 7849, "s": 6378, "text": "<div class = \"btn-group\">\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle btn-lg\" data-toggle = \"dropdown\">\n Default\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n</div>\n\n<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-primary dropdown-toggle btn-sm\" data-toggle = \"dropdown\">\n Primary\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n</div>\n\n<div class = \"btn-group\">\n <button type = \"button\" class = \"btn btn-success dropdown-toggle btn-xs\" data-toggle = \"dropdown\">\n Success\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n</div>" }, { "code": null, "e": 7856, "s": 7849, "text": "Action" }, { "code": null, "e": 7871, "s": 7856, "text": "Another action" }, { "code": null, "e": 7891, "s": 7871, "text": "Something else here" }, { "code": null, "e": 7906, "s": 7891, "text": "Separated link" }, { "code": null, "e": 7913, "s": 7906, "text": "Action" }, { "code": null, "e": 7928, "s": 7913, "text": "Another action" }, { "code": null, "e": 7948, "s": 7928, "text": "Something else here" }, { "code": null, "e": 7963, "s": 7948, "text": "Separated link" }, { "code": null, "e": 7970, "s": 7963, "text": "Action" }, { "code": null, "e": 7985, "s": 7970, "text": "Another action" }, { "code": null, "e": 8005, "s": 7985, "text": "Something else here" }, { "code": null, "e": 8020, "s": 8005, "text": "Separated link" }, { "code": null, "e": 8145, "s": 8020, "text": "Menus can also be built to drop up rather than down. To achieve this, simply add .dropup to the parent .btn-group container." }, { "code": null, "e": 9293, "s": 8145, "text": "<div class = \"row\" style = \"margin-left:50px; margin-top:200px\">\n \n <div class = \"btn-group dropup\">\n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" data-toggle = \"dropdown\">\n Default\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n </div>\n \n <div class = \"btn-group dropup\">\n <button type = \"button\" class = \"btn btn-primary dropdown-toggle\" data-toggle = \"dropdown\">\n Primary\n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\" role = \"menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n </div>\n \n</div>" }, { "code": null, "e": 9300, "s": 9293, "text": "Action" }, { "code": null, "e": 9315, "s": 9300, "text": "Another action" }, { "code": null, "e": 9335, "s": 9315, "text": "Something else here" }, { "code": null, "e": 9350, "s": 9335, "text": "Separated link" }, { "code": null, "e": 9357, "s": 9350, "text": "Action" }, { "code": null, "e": 9372, "s": 9357, "text": "Another action" }, { "code": null, "e": 9392, "s": 9372, "text": "Something else here" }, { "code": null, "e": 9407, "s": 9392, "text": "Separated link" }, { "code": null, "e": 9440, "s": 9407, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 9454, "s": 9440, "text": " Anadi Sharma" }, { "code": null, "e": 9489, "s": 9454, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9506, "s": 9489, "text": " Frahaan Hussain" }, { "code": null, "e": 9543, "s": 9506, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 9571, "s": 9543, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9604, "s": 9571, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 9616, "s": 9604, "text": " Azaz Patel" }, { "code": null, "e": 9651, "s": 9616, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9668, "s": 9651, "text": " Muhammad Ismail" }, { "code": null, "e": 9701, "s": 9668, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 9721, "s": 9701, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 9728, "s": 9721, "text": " Print" }, { "code": null, "e": 9739, "s": 9728, "text": " Add Notes" } ]
C Program For Union And Intersection Of Two Linked Lists - GeeksforGeeks
20 Dec, 2021 Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example: Input: List1: 10->15->4->20 List2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10 Method 1 (Simple):The following are simple algorithms to get union and intersection lists respectively.1. Intersection (list1, list2):Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.2. Union (list1, list2):Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.This method assumes that there are no duplicates in the given lists.Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method. C // C program to find union// and intersection of two unsorted// linked lists#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list node struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element // of it in list2. If the element is // present in list 2, then insert the // element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); // Put in the data new_node->data = new_data; /* 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;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} // Driver codeint main(){ // Start with the empty list struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /* Create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /* Create a linked lits 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); printf("First list is "); printList(head1); printf("Second list is "); printList(head2); printf("Intersection list is "); printList(intersecn); printf("Union list is "); printList(unin); return 0;} Output: First list is 10 15 4 20 Second list is 8 4 2 10 Intersection list is 4 10 Union list is 2 8 20 4 15 10 Complexity Analysis: Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2. Auxiliary Space: O(1). No use of any data structure for storing values. Method 2 (Use Merge Sort):In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists. Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here. Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step. Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step. Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here. The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.Please refer complete article on Union and Intersection of two Linked Lists for more details! 24*7 Innovation Labs Accolite Amazon Flipkart Komli Media Microsoft Taxi4Sure VMWare Walmart C Programs Hash Linked List Sorting VMWare Flipkart Accolite Amazon Microsoft 24*7 Innovation Labs Walmart Komli Media Taxi4Sure Linked List Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string Handling multiple clients on server with multithreading using Socket Programming in C/C++ Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 26363, "s": 26335, "text": "\n20 Dec, 2021" }, { "code": null, "e": 26565, "s": 26363, "text": "Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example:" }, { "code": null, "e": 26678, "s": 26565, "text": "Input:\nList1: 10->15->4->20\nList2: 8->4->2->10\nOutput:\nIntersection List: 4->10\nUnion List: 2->8->20->4->15->10" }, { "code": null, "e": 27384, "s": 26678, "text": "Method 1 (Simple):The following are simple algorithms to get union and intersection lists respectively.1. Intersection (list1, list2):Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.2. Union (list1, list2):Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.This method assumes that there are no duplicates in the given lists.Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method." }, { "code": null, "e": 27386, "s": 27384, "text": "C" }, { "code": "// C program to find union// and intersection of two unsorted// linked lists#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list node struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element // of it in list2. If the element is // present in list 2, then insert the // element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); // Put in the data new_node->data = new_data; /* 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;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} // Driver codeint main(){ // Start with the empty list struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /* Create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /* Create a linked lits 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); printf(\"First list is \"); printList(head1); printf(\"Second list is \"); printList(head2); printf(\"Intersection list is \"); printList(intersecn); printf(\"Union list is \"); printList(unin); return 0;}", "e": 30748, "s": 27386, "text": null }, { "code": null, "e": 30756, "s": 30748, "text": "Output:" }, { "code": null, "e": 30867, "s": 30756, "text": "First list is \n10 15 4 20 \nSecond list is \n8 4 2 10 \nIntersection list is \n4 10 \nUnion list is \n2 8 20 4 15 10" }, { "code": null, "e": 30888, "s": 30867, "text": "Complexity Analysis:" }, { "code": null, "e": 31225, "s": 30888, "text": "Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2." }, { "code": null, "e": 31297, "s": 31225, "text": "Auxiliary Space: O(1). No use of any data structure for storing values." }, { "code": null, "e": 31572, "s": 31297, "text": "Method 2 (Use Merge Sort):In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists." }, { "code": null, "e": 32002, "s": 31572, "text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here." }, { "code": null, "e": 32120, "s": 32002, "text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step." }, { "code": null, "e": 32239, "s": 32120, "text": "Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step." }, { "code": null, "e": 32434, "s": 32239, "text": "Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here." }, { "code": null, "e": 32631, "s": 32434, "text": "The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.Please refer complete article on Union and Intersection of two Linked Lists for more details!" }, { "code": null, "e": 32652, "s": 32631, "text": "24*7 Innovation Labs" }, { "code": null, "e": 32661, "s": 32652, "text": "Accolite" }, { "code": null, "e": 32668, "s": 32661, "text": "Amazon" }, { "code": null, "e": 32677, "s": 32668, "text": "Flipkart" }, { "code": null, "e": 32689, "s": 32677, "text": "Komli Media" }, { "code": null, "e": 32699, "s": 32689, "text": "Microsoft" }, { "code": null, "e": 32709, "s": 32699, "text": "Taxi4Sure" }, { "code": null, "e": 32716, "s": 32709, "text": "VMWare" }, { "code": null, "e": 32724, "s": 32716, "text": "Walmart" }, { "code": null, "e": 32735, "s": 32724, "text": "C Programs" }, { "code": null, "e": 32740, "s": 32735, "text": "Hash" }, { "code": null, "e": 32752, "s": 32740, "text": "Linked List" }, { "code": null, "e": 32760, "s": 32752, "text": "Sorting" }, { "code": null, "e": 32767, "s": 32760, "text": "VMWare" }, { "code": null, "e": 32776, "s": 32767, "text": "Flipkart" }, { "code": null, "e": 32785, "s": 32776, "text": "Accolite" }, { "code": null, "e": 32792, "s": 32785, "text": "Amazon" }, { "code": null, "e": 32802, "s": 32792, "text": "Microsoft" }, { "code": null, "e": 32823, "s": 32802, "text": "24*7 Innovation Labs" }, { "code": null, "e": 32831, "s": 32823, "text": "Walmart" }, { "code": null, "e": 32843, "s": 32831, "text": "Komli Media" }, { "code": null, "e": 32853, "s": 32843, "text": "Taxi4Sure" }, { "code": null, "e": 32865, "s": 32853, "text": "Linked List" }, { "code": null, "e": 32870, "s": 32865, "text": "Hash" }, { "code": null, "e": 32878, "s": 32870, "text": "Sorting" }, { "code": null, "e": 32976, "s": 32878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33017, "s": 32976, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 33048, "s": 33017, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 33082, "s": 33048, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 33123, "s": 33082, "text": "C program to find the length of a string" }, { "code": null, "e": 33213, "s": 33123, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 33298, "s": 33213, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33334, "s": 33298, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33365, "s": 33334, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 33399, "s": 33365, "text": "Hashing | Set 3 (Open Addressing)" } ]
Infix to Prefix conversion using two stacks - GeeksforGeeks
30 Aug, 2021 Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (A+B) * (C-D)Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) )Given an Infix expression, convert it into a Prefix expression using two stacks.Examples: Input : A * B + C / D Output : + * A B/ C D Input : (A - B/C) * (A/K-L) Output : *-A/BC-/AKL The idea is to use one stack for storing operators and other to store operands. The stepwise algo is: Traverse the infix expression and check if given character is an operator or an operand.If it is an operand, then push it into operand stack.If it is an operator, then check if priority of current operator is greater than or less than or equal to the operator at top of the stack. If priority is greater, then push operator into operator stack. Otherwise pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until priority of current operator is less than or equal to operator at top of the operator stack.If current character is ‘(‘, then push it into operator stack.If current character is ‘)’, then check if top of operator stack is opening bracket or not. If not pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until top of operator stack is an opening bracket.The final prefix expression is present at top of operand stack. Traverse the infix expression and check if given character is an operator or an operand. If it is an operand, then push it into operand stack. If it is an operator, then check if priority of current operator is greater than or less than or equal to the operator at top of the stack. If priority is greater, then push operator into operator stack. Otherwise pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until priority of current operator is less than or equal to operator at top of the operator stack. If current character is ‘(‘, then push it into operator stack. If current character is ‘)’, then check if top of operator stack is opening bracket or not. If not pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until top of operator stack is an opening bracket. The final prefix expression is present at top of operand stack. Below is the implementation of above algorithm: C++ Java Python3 C# Javascript // CPP program to convert infix to prefix.#include <bits/stdc++.h>using namespace std; // Function to check if given character is// an operator or not.bool isOperator(char c){ return (!isalpha(c) && !isdigit(c));} // Function to find priority of given// operator.int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.string infixToPrefix(string infix){ // stack for operators. stack<char> operators; // stack for operands. stack<string> operands; for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (!operators.empty() && operators.top() != '(') { // operand 1 string op1 = operands.top(); operands.pop(); // operand 2 string op2 = operands.top(); operands.pop(); // operator char op = operators.top(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. string tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket from // stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.push(string(1, infix[i])); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } // Pop operators from operators stack // until it is empty and add result // of each pop operation in // operands stack. while (!operators.empty()) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.top();} // Driver codeint main(){ string s = "(A-B/C)*(A/K-L)"; cout << infixToPrefix(s); return 0;} // Java program to convert// infix to prefix.import java.util.*;class GFG{// Function to check if// given character is// an operator or not.static boolean isOperator(char c){ return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z'));} // Function to find priority// of given operator.static int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.static String infixToPrefix(String infix){ // stack for operators. Stack<Character> operators = new Stack<Character>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix.charAt(i) == '(') { operators.push(infix.charAt(i)); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix.charAt(i) == ')') { while (!operators.empty() && operators.peek() != '(') { // operand 1 String op1 = operands.peek(); operands.pop(); // operand 2 String op2 = operands.peek(); operands.pop(); // operator char op = operators.peek(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix.charAt(i))) { operands.push(infix.charAt(i) + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix.charAt(i)) <= getPriority(operators.peek())) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix.charAt(i)); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (!operators.empty()) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.peek();} // Driver codepublic static void main(String args[]){ String s = "(A-B/C)*(A/K-L)"; System.out.println( infixToPrefix(s));}} // This code is contributed// by Arnab Kundu # Python3 program to convert infix to prefix. # Function to check if# given character is# an operator or not.def isOperator(c): return (not (c >= 'a' and c <= 'z') and not(c >= '0' and c <= '9') and not(c >= 'A' and c <= 'Z')) # Function to find priority# of given operator.def getPriority(C): if (C == '-' or C == '+'): return 1 elif (C == '*' or C == '/'): return 2 elif (C == '^'): return 3 return 0 # Function that converts infix# expression to prefix expression.def infixToPrefix(infix): # stack for operators. operators = [] # stack for operands. operands = [] for i in range(len(infix)): # If current character is an # opening bracket, then # push into the operators stack. if (infix[i] == '('): operators.append(infix[i]) # If current character is a # closing bracket, then pop from # both stacks and push result # in operands stack until # matching opening bracket is # not found. elif (infix[i] == ')'): while (len(operators)!=0 and operators[-1] != '('): # operand 1 op1 = operands[-1] operands.pop() # operand 2 op2 = operands[-1] operands.pop() # operator op = operators[-1] operators.pop() # Add operands and operator # in form operator + # operand1 + operand2. tmp = op + op2 + op1 operands.append(tmp) # Pop opening bracket # from stack. operators.pop() # If current character is an # operand then push it into # operands stack. elif (not isOperator(infix[i])): operands.append(infix[i] + "") # If current character is an # operator, then push it into # operators stack after popping # high priority operators from # operators stack and pushing # result in operands stack. else: while (len(operators)!=0 and getPriority(infix[i]) <= getPriority(operators[-1])): op1 = operands[-1] operands.pop() op2 = operands[-1] operands.pop() op = operators[-1] operators.pop() tmp = op + op2 + op1 operands.append(tmp) operators.append(infix[i]) # Pop operators from operators # stack until it is empty and # operation in add result of # each pop operands stack. while (len(operators)!=0): op1 = operands[-1] operands.pop() op2 = operands[-1] operands.pop() op = operators[-1] operators.pop() tmp = op + op2 + op1 operands.append(tmp) # Final prefix expression is # present in operands stack. return operands[-1] s = "(A-B/C)*(A/K-L)"print( infixToPrefix(s)) # This code is contributed by decode2207. // C# program to convert// infix to prefix.using System;using System.Collections.Generic;public class GFG { // Function to check if // given character is // an operator or not. static bool isOperator(char c) { return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z')); } // Function to find priority // of given operator. static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Function that converts infix // expression to prefix expression. static String infixToPrefix(String infix) { // stack for operators. Stack<char> operators = new Stack<char>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.Length; i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.Push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (operators.Count!=0 && operators.Peek() != '(') { // operand 1 String op1 = operands.Peek(); operands.Pop(); // operand 2 String op2 = operands.Peek(); operands.Pop(); // operator char op = operators.Peek(); operators.Pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.Push(tmp); } // Pop opening bracket // from stack. operators.Pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.Push(infix[i] + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (operators.Count!=0 && getPriority(infix[i]) <= getPriority(operators.Peek())) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } operators.Push(infix[i]); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (operators.Count!=0) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } // Final prefix expression is // present in operands stack. return operands.Peek(); } // Driver code public static void Main() { String s = "(A-B/C)*(A/K-L)"; Console.WriteLine( infixToPrefix(s)); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to convert// infix to prefix. // Function to check if// given character is// an operator or not.function isOperator(c){ return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z'));} // Function to find priority// of given operator.function getPriority(C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.function infixToPrefix(infix){ // stack for operators. let operators = []; // stack for operands. let operands = []; for (let i = 0; i < infix.length; i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (operators.length!=0 && operators[operators.length-1] != '(') { // operand 1 let op1 = operands.pop(); // operand 2 let op2 = operands.pop(); // operator let op = operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. let tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.push(infix[i] + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (operators.length && getPriority(infix[i]) <= getPriority(operators[operators.length-1])) { let op1 = operands.pop(); let op2 = operands.pop(); let op = operators.pop(); let tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (operators.length!=0) { let op1 = operands.pop(); let op2 = operands.pop(); let op = operators.pop(); let tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands[operands.length-1];} // Driver codelet s = "(A-B/C)*(A/K-L)";document.write( infixToPrefix(s)); // This code is contributed by avanitrachhadiya2155 </script> *-A/BC-/AKL Time Complexity: O(n) Auxiliary Space: O(n) andrew1234 29AjayKumar utkarshsrmcem111 avanitrachhadiya2155 decode2207 expression-evaluation Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Real-time application of Data Structures ZigZag Tree Traversal Reverse individual words Length of the longest valid substring Sort a stack using a temporary stack Evaluation of Prefix Expressions Next Smaller Element Postfix to Infix Iterative Tower of Hanoi Design a stack with operations on middle element
[ { "code": null, "e": 26043, "s": 26015, "text": "\n30 Aug, 2021" }, { "code": null, "e": 26535, "s": 26043, "text": "Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (A+B) * (C-D)Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) )Given an Infix expression, convert it into a Prefix expression using two stacks.Examples: " }, { "code": null, "e": 26630, "s": 26535, "text": "Input : A * B + C / D\nOutput : + * A B/ C D \n\nInput : (A - B/C) * (A/K-L)\nOutput : *-A/BC-/AKL" }, { "code": null, "e": 26733, "s": 26630, "text": "The idea is to use one stack for storing operators and other to store operands. The stepwise algo is: " }, { "code": null, "e": 27875, "s": 26733, "text": "Traverse the infix expression and check if given character is an operator or an operand.If it is an operand, then push it into operand stack.If it is an operator, then check if priority of current operator is greater than or less than or equal to the operator at top of the stack. If priority is greater, then push operator into operator stack. Otherwise pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until priority of current operator is less than or equal to operator at top of the operator stack.If current character is ‘(‘, then push it into operator stack.If current character is ‘)’, then check if top of operator stack is opening bracket or not. If not pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until top of operator stack is an opening bracket.The final prefix expression is present at top of operand stack." }, { "code": null, "e": 27964, "s": 27875, "text": "Traverse the infix expression and check if given character is an operator or an operand." }, { "code": null, "e": 28018, "s": 27964, "text": "If it is an operand, then push it into operand stack." }, { "code": null, "e": 28538, "s": 28018, "text": "If it is an operator, then check if priority of current operator is greater than or less than or equal to the operator at top of the stack. If priority is greater, then push operator into operator stack. Otherwise pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until priority of current operator is less than or equal to operator at top of the operator stack." }, { "code": null, "e": 28601, "s": 28538, "text": "If current character is ‘(‘, then push it into operator stack." }, { "code": null, "e": 28958, "s": 28601, "text": "If current character is ‘)’, then check if top of operator stack is opening bracket or not. If not pop two operands from operand stack, pop operator from operator stack and push string operator + operand 2 + operand 1 into operand stack. Keep popping from both stacks and pushing result into operand stack until top of operator stack is an opening bracket." }, { "code": null, "e": 29022, "s": 28958, "text": "The final prefix expression is present at top of operand stack." }, { "code": null, "e": 29072, "s": 29022, "text": "Below is the implementation of above algorithm: " }, { "code": null, "e": 29076, "s": 29072, "text": "C++" }, { "code": null, "e": 29081, "s": 29076, "text": "Java" }, { "code": null, "e": 29089, "s": 29081, "text": "Python3" }, { "code": null, "e": 29092, "s": 29089, "text": "C#" }, { "code": null, "e": 29103, "s": 29092, "text": "Javascript" }, { "code": "// CPP program to convert infix to prefix.#include <bits/stdc++.h>using namespace std; // Function to check if given character is// an operator or not.bool isOperator(char c){ return (!isalpha(c) && !isdigit(c));} // Function to find priority of given// operator.int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.string infixToPrefix(string infix){ // stack for operators. stack<char> operators; // stack for operands. stack<string> operands; for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (!operators.empty() && operators.top() != '(') { // operand 1 string op1 = operands.top(); operands.pop(); // operand 2 string op2 = operands.top(); operands.pop(); // operator char op = operators.top(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. string tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket from // stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.push(string(1, infix[i])); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } // Pop operators from operators stack // until it is empty and add result // of each pop operation in // operands stack. while (!operators.empty()) { string op1 = operands.top(); operands.pop(); string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); string tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.top();} // Driver codeint main(){ string s = \"(A-B/C)*(A/K-L)\"; cout << infixToPrefix(s); return 0;}", "e": 32492, "s": 29103, "text": null }, { "code": "// Java program to convert// infix to prefix.import java.util.*;class GFG{// Function to check if// given character is// an operator or not.static boolean isOperator(char c){ return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z'));} // Function to find priority// of given operator.static int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.static String infixToPrefix(String infix){ // stack for operators. Stack<Character> operators = new Stack<Character>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix.charAt(i) == '(') { operators.push(infix.charAt(i)); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix.charAt(i) == ')') { while (!operators.empty() && operators.peek() != '(') { // operand 1 String op1 = operands.peek(); operands.pop(); // operand 2 String op2 = operands.peek(); operands.pop(); // operator char op = operators.peek(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix.charAt(i))) { operands.push(infix.charAt(i) + \"\"); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix.charAt(i)) <= getPriority(operators.peek())) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix.charAt(i)); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (!operators.empty()) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.peek();} // Driver codepublic static void main(String args[]){ String s = \"(A-B/C)*(A/K-L)\"; System.out.println( infixToPrefix(s));}} // This code is contributed// by Arnab Kundu", "e": 36205, "s": 32492, "text": null }, { "code": "# Python3 program to convert infix to prefix. # Function to check if# given character is# an operator or not.def isOperator(c): return (not (c >= 'a' and c <= 'z') and not(c >= '0' and c <= '9') and not(c >= 'A' and c <= 'Z')) # Function to find priority# of given operator.def getPriority(C): if (C == '-' or C == '+'): return 1 elif (C == '*' or C == '/'): return 2 elif (C == '^'): return 3 return 0 # Function that converts infix# expression to prefix expression.def infixToPrefix(infix): # stack for operators. operators = [] # stack for operands. operands = [] for i in range(len(infix)): # If current character is an # opening bracket, then # push into the operators stack. if (infix[i] == '('): operators.append(infix[i]) # If current character is a # closing bracket, then pop from # both stacks and push result # in operands stack until # matching opening bracket is # not found. elif (infix[i] == ')'): while (len(operators)!=0 and operators[-1] != '('): # operand 1 op1 = operands[-1] operands.pop() # operand 2 op2 = operands[-1] operands.pop() # operator op = operators[-1] operators.pop() # Add operands and operator # in form operator + # operand1 + operand2. tmp = op + op2 + op1 operands.append(tmp) # Pop opening bracket # from stack. operators.pop() # If current character is an # operand then push it into # operands stack. elif (not isOperator(infix[i])): operands.append(infix[i] + \"\") # If current character is an # operator, then push it into # operators stack after popping # high priority operators from # operators stack and pushing # result in operands stack. else: while (len(operators)!=0 and getPriority(infix[i]) <= getPriority(operators[-1])): op1 = operands[-1] operands.pop() op2 = operands[-1] operands.pop() op = operators[-1] operators.pop() tmp = op + op2 + op1 operands.append(tmp) operators.append(infix[i]) # Pop operators from operators # stack until it is empty and # operation in add result of # each pop operands stack. while (len(operators)!=0): op1 = operands[-1] operands.pop() op2 = operands[-1] operands.pop() op = operators[-1] operators.pop() tmp = op + op2 + op1 operands.append(tmp) # Final prefix expression is # present in operands stack. return operands[-1] s = \"(A-B/C)*(A/K-L)\"print( infixToPrefix(s)) # This code is contributed by decode2207.", "e": 39230, "s": 36205, "text": null }, { "code": "// C# program to convert// infix to prefix.using System;using System.Collections.Generic;public class GFG { // Function to check if // given character is // an operator or not. static bool isOperator(char c) { return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z')); } // Function to find priority // of given operator. static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Function that converts infix // expression to prefix expression. static String infixToPrefix(String infix) { // stack for operators. Stack<char> operators = new Stack<char>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.Length; i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.Push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (operators.Count!=0 && operators.Peek() != '(') { // operand 1 String op1 = operands.Peek(); operands.Pop(); // operand 2 String op2 = operands.Peek(); operands.Pop(); // operator char op = operators.Peek(); operators.Pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.Push(tmp); } // Pop opening bracket // from stack. operators.Pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.Push(infix[i] + \"\"); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (operators.Count!=0 && getPriority(infix[i]) <= getPriority(operators.Peek())) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } operators.Push(infix[i]); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (operators.Count!=0) { String op1 = operands.Peek(); operands.Pop(); String op2 = operands.Peek(); operands.Pop(); char op = operators.Peek(); operators.Pop(); String tmp = op + op2 + op1; operands.Push(tmp); } // Final prefix expression is // present in operands stack. return operands.Peek(); } // Driver code public static void Main() { String s = \"(A-B/C)*(A/K-L)\"; Console.WriteLine( infixToPrefix(s)); }} // This code is contributed by 29AjayKumar", "e": 43395, "s": 39230, "text": null }, { "code": "<script> // JavaScript program to convert// infix to prefix. // Function to check if// given character is// an operator or not.function isOperator(c){ return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z'));} // Function to find priority// of given operator.function getPriority(C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} // Function that converts infix// expression to prefix expression.function infixToPrefix(infix){ // stack for operators. let operators = []; // stack for operands. let operands = []; for (let i = 0; i < infix.length; i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix[i] == '(') { operators.push(infix[i]); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix[i] == ')') { while (operators.length!=0 && operators[operators.length-1] != '(') { // operand 1 let op1 = operands.pop(); // operand 2 let op2 = operands.pop(); // operator let op = operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. let tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix[i])) { operands.push(infix[i] + \"\"); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (operators.length && getPriority(infix[i]) <= getPriority(operators[operators.length-1])) { let op1 = operands.pop(); let op2 = operands.pop(); let op = operators.pop(); let tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (operators.length!=0) { let op1 = operands.pop(); let op2 = operands.pop(); let op = operators.pop(); let tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands[operands.length-1];} // Driver codelet s = \"(A-B/C)*(A/K-L)\";document.write( infixToPrefix(s)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 46807, "s": 43395, "text": null }, { "code": null, "e": 46819, "s": 46807, "text": "*-A/BC-/AKL" }, { "code": null, "e": 46865, "s": 46821, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 46876, "s": 46865, "text": "andrew1234" }, { "code": null, "e": 46888, "s": 46876, "text": "29AjayKumar" }, { "code": null, "e": 46905, "s": 46888, "text": "utkarshsrmcem111" }, { "code": null, "e": 46926, "s": 46905, "text": "avanitrachhadiya2155" }, { "code": null, "e": 46937, "s": 46926, "text": "decode2207" }, { "code": null, "e": 46959, "s": 46937, "text": "expression-evaluation" }, { "code": null, "e": 46965, "s": 46959, "text": "Stack" }, { "code": null, "e": 46971, "s": 46965, "text": "Stack" }, { "code": null, "e": 47069, "s": 46971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47110, "s": 47069, "text": "Real-time application of Data Structures" }, { "code": null, "e": 47132, "s": 47110, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 47157, "s": 47132, "text": "Reverse individual words" }, { "code": null, "e": 47195, "s": 47157, "text": "Length of the longest valid substring" }, { "code": null, "e": 47232, "s": 47195, "text": "Sort a stack using a temporary stack" }, { "code": null, "e": 47265, "s": 47232, "text": "Evaluation of Prefix Expressions" }, { "code": null, "e": 47286, "s": 47265, "text": "Next Smaller Element" }, { "code": null, "e": 47303, "s": 47286, "text": "Postfix to Infix" }, { "code": null, "e": 47328, "s": 47303, "text": "Iterative Tower of Hanoi" } ]
DeepFool — A simple and accurate method to fool Deep Neural Networks. | by Arc | Towards Data Science
Summary of the paperDeepFool: A Simple and Accurate Method to Fool Deep Neural Networksby Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal FrossardLink to the paper: https://arxiv.org/pdf/1511.04599.pdf Deep Neural Networks achieve state of the art performances in many tasks but fail miserably on slightly perturbed images, perturbed in a meaningful way (and not randomly). The DeepFool paper have the following major contributions: Simple and accurate method for computing the robustness of different classifiers to adversarial perturbations.Experiments showing- DeepFool computes a more optimal adversarial perturbation- Adversarial Training significantly increases the robustness. Simple and accurate method for computing the robustness of different classifiers to adversarial perturbations. Experiments showing- DeepFool computes a more optimal adversarial perturbation- Adversarial Training significantly increases the robustness. It can be easily seen using a linear binary classifier, that the robustness of the model (`f`) for an input x_{0}is equal to the distance of x_{0} to the hyperparameter plane (which seperates the 2 classes). Minimal perturbation to change the classifier’s decision corresponds to the orthogonal projection of x_{0} onto the hyperparameter plane. Given by: Below is the algorithm for DeepFool for binary classifiers: Let’s go over the Algorithm:1. The algorithm takes an input x and a classifier f .2. Outputs the minimal perturbation required to miclassify the image.3. Initialize the adversarial image with the original input. And the loop variable to 1.4. Start and continue loop while the true label and the label of the adversarially perturbed image is the same.5. Calculate the projection of the input onto the closest hyperplane. (minimal perturbation)6. Add that perturbation to the image and test.7–8. Increment Loop Variable; End Loop9. Return the minimal perturbation With multiclass classifiers, let’s say the input is x and for each class there is a hyperplane (straight plane that divides one class from the others) and based on the place in the space where x lies it is classified into a class. Now, all this algorithm does is, it finds the closest hyperplane, and then projects x onto that hyperplane and pushes it a bit beyond, thus misclassifying it with the minimal perturbation possible. That’s it. (Go through the section 3 in the paper to get a in-depth understanding) Let’s take a look at the algorithm Let’s quickly walkthrough each step of the algorithm:1. Input is an image x and the classifier f which is the model.2. The output which is the perturbation3. [Blank]4. We initialize the perturbed image with the original image and the loop variable.5. We start the iteration and continue for uptil the original label and the perturbed label are not equal.6–9. We consider n classes that had a the most probability after the original class and we store the minimum difference between the original gradients and the gradients of each of these class (w_{k}) and the difference in the labels (f_{k}).10. The inner loop stores the minimum w_{k} and f_{k}, and using this we calculate the closest hyperplane for the input x(See Fig 6. for the formula of calculating the closest hyperplane)11. We calculate the minimal vector that projects x onto the closest hyperplane that we calculated in 10.12. We add the minimal perturbation to the image and check if its miclassified.13–14. Loop variable increased; End Loop15. Return the total perturbation, which is a sum over all the calculated perturbations. Below is the equation to calculate the closest hyperplane: where,variables starting with f are the class labelsvariables starting with w are the gradientswhere, the varibles with k as subscript are for the classes with the most probability after the true class and the variables with subscript \hat{k}(x+{0}) is for the true class. Below is the equation to calculate the minimal perturbation (the vector which projects the input on the closest hyperplane) The DeepFool algorithm also provides a way to measure the adversarial robustness of an algorithm. It is proided by # For images with a batch size of 1num_images = len(tloader))adversarial_robustness = (1 / num_images) * ((torch.norm(rt.flatten()) / (torch.norm(x.flatten())) where,4 — is the fast gradient sign method.18 — is the attack from the paper titled Intriguing properties of neural networks by Szegedy et al. Graphs showing the effect of adversarial training using adversarial images generated with the Fast Gradient Sign Method and DeepFool. These graphs demonstrates the importance of training with adversarial examples that are minimally perturbed (and not overly perturbed as in case of the Fast Gradient Sign Method.) Graph which proves that training with overly perturbed images reduces the robustness of the model. In this experiment, the authors use DeepFool only with a gradually increasing value of alpha (where alpha is the value which is multiplied with the produced perturbation) Table showing the test error rate after fine-tuning the network with different methods. This table shows that tuning the network with overly perturbed images leads to higher test error rates (adversarial images produced by Fast Gradient Sign Method.) Graph showing the importance of using an accurate metric for calculating the adversarial robustness of a model. In this experiment they calculate the robustness of the NIN(Network-in-Network) model using the p_adv of the FGM attack and the DeepFool attack. The graph shows how the robustness calculated using the FGM attack gives a wrong measure as it really isn’t that robust as the previous examples show (and also the blue line which is for the robustness calculated using the DeepFool attack). Also, do note, how on the first extra epoch (the networks are trained for 5 extra epochs with adversarially perturbed images after original training with normal imges) the red-line (FGM) is not sensitive enough to demonstrate the loss of robustness. Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal Frossard; The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, pp. 2574–2582 Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal Frossard; The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, pp. 2574–2582 Hope the article was clear enough to give a good understanding of what the DeepFool Algorithm is and how it works. I wish to update this article in future if I find more intuitive explanations or areas that needs more focus. Do please read the paper to get a better understanding. Thanks for reading!
[ { "code": null, "e": 381, "s": 172, "text": "Summary of the paperDeepFool: A Simple and Accurate Method to Fool Deep Neural Networksby Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal FrossardLink to the paper: https://arxiv.org/pdf/1511.04599.pdf" }, { "code": null, "e": 553, "s": 381, "text": "Deep Neural Networks achieve state of the art performances in many tasks but fail miserably on slightly perturbed images, perturbed in a meaningful way (and not randomly)." }, { "code": null, "e": 612, "s": 553, "text": "The DeepFool paper have the following major contributions:" }, { "code": null, "e": 863, "s": 612, "text": "Simple and accurate method for computing the robustness of different classifiers to adversarial perturbations.Experiments showing- DeepFool computes a more optimal adversarial perturbation- Adversarial Training significantly increases the robustness." }, { "code": null, "e": 974, "s": 863, "text": "Simple and accurate method for computing the robustness of different classifiers to adversarial perturbations." }, { "code": null, "e": 1115, "s": 974, "text": "Experiments showing- DeepFool computes a more optimal adversarial perturbation- Adversarial Training significantly increases the robustness." }, { "code": null, "e": 1323, "s": 1115, "text": "It can be easily seen using a linear binary classifier, that the robustness of the model (`f`) for an input x_{0}is equal to the distance of x_{0} to the hyperparameter plane (which seperates the 2 classes)." }, { "code": null, "e": 1471, "s": 1323, "text": "Minimal perturbation to change the classifier’s decision corresponds to the orthogonal projection of x_{0} onto the hyperparameter plane. Given by:" }, { "code": null, "e": 1531, "s": 1471, "text": "Below is the algorithm for DeepFool for binary classifiers:" }, { "code": null, "e": 2093, "s": 1531, "text": "Let’s go over the Algorithm:1. The algorithm takes an input x and a classifier f .2. Outputs the minimal perturbation required to miclassify the image.3. Initialize the adversarial image with the original input. And the loop variable to 1.4. Start and continue loop while the true label and the label of the adversarially perturbed image is the same.5. Calculate the projection of the input onto the closest hyperplane. (minimal perturbation)6. Add that perturbation to the image and test.7–8. Increment Loop Variable; End Loop9. Return the minimal perturbation" }, { "code": null, "e": 2605, "s": 2093, "text": "With multiclass classifiers, let’s say the input is x and for each class there is a hyperplane (straight plane that divides one class from the others) and based on the place in the space where x lies it is classified into a class. Now, all this algorithm does is, it finds the closest hyperplane, and then projects x onto that hyperplane and pushes it a bit beyond, thus misclassifying it with the minimal perturbation possible. That’s it. (Go through the section 3 in the paper to get a in-depth understanding)" }, { "code": null, "e": 2640, "s": 2605, "text": "Let’s take a look at the algorithm" }, { "code": null, "e": 3735, "s": 2640, "text": "Let’s quickly walkthrough each step of the algorithm:1. Input is an image x and the classifier f which is the model.2. The output which is the perturbation3. [Blank]4. We initialize the perturbed image with the original image and the loop variable.5. We start the iteration and continue for uptil the original label and the perturbed label are not equal.6–9. We consider n classes that had a the most probability after the original class and we store the minimum difference between the original gradients and the gradients of each of these class (w_{k}) and the difference in the labels (f_{k}).10. The inner loop stores the minimum w_{k} and f_{k}, and using this we calculate the closest hyperplane for the input x(See Fig 6. for the formula of calculating the closest hyperplane)11. We calculate the minimal vector that projects x onto the closest hyperplane that we calculated in 10.12. We add the minimal perturbation to the image and check if its miclassified.13–14. Loop variable increased; End Loop15. Return the total perturbation, which is a sum over all the calculated perturbations." }, { "code": null, "e": 3794, "s": 3735, "text": "Below is the equation to calculate the closest hyperplane:" }, { "code": null, "e": 4067, "s": 3794, "text": "where,variables starting with f are the class labelsvariables starting with w are the gradientswhere, the varibles with k as subscript are for the classes with the most probability after the true class and the variables with subscript \\hat{k}(x+{0}) is for the true class." }, { "code": null, "e": 4191, "s": 4067, "text": "Below is the equation to calculate the minimal perturbation (the vector which projects the input on the closest hyperplane)" }, { "code": null, "e": 4306, "s": 4191, "text": "The DeepFool algorithm also provides a way to measure the adversarial robustness of an algorithm. It is proided by" }, { "code": null, "e": 4466, "s": 4306, "text": "# For images with a batch size of 1num_images = len(tloader))adversarial_robustness = (1 / num_images) * ((torch.norm(rt.flatten()) / (torch.norm(x.flatten()))" }, { "code": null, "e": 4609, "s": 4466, "text": "where,4 — is the fast gradient sign method.18 — is the attack from the paper titled Intriguing properties of neural networks by Szegedy et al." }, { "code": null, "e": 4923, "s": 4609, "text": "Graphs showing the effect of adversarial training using adversarial images generated with the Fast Gradient Sign Method and DeepFool. These graphs demonstrates the importance of training with adversarial examples that are minimally perturbed (and not overly perturbed as in case of the Fast Gradient Sign Method.)" }, { "code": null, "e": 5193, "s": 4923, "text": "Graph which proves that training with overly perturbed images reduces the robustness of the model. In this experiment, the authors use DeepFool only with a gradually increasing value of alpha (where alpha is the value which is multiplied with the produced perturbation)" }, { "code": null, "e": 5444, "s": 5193, "text": "Table showing the test error rate after fine-tuning the network with different methods. This table shows that tuning the network with overly perturbed images leads to higher test error rates (adversarial images produced by Fast Gradient Sign Method.)" }, { "code": null, "e": 6192, "s": 5444, "text": "Graph showing the importance of using an accurate metric for calculating the adversarial robustness of a model. In this experiment they calculate the robustness of the NIN(Network-in-Network) model using the p_adv of the FGM attack and the DeepFool attack. The graph shows how the robustness calculated using the FGM attack gives a wrong measure as it really isn’t that robust as the previous examples show (and also the blue line which is for the robustness calculated using the DeepFool attack). Also, do note, how on the first extra epoch (the networks are trained for 5 extra epochs with adversarially perturbed images after original training with normal imges) the red-line (FGM) is not sensitive enough to demonstrate the loss of robustness." }, { "code": null, "e": 6348, "s": 6192, "text": "Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal Frossard; The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, pp. 2574–2582" }, { "code": null, "e": 6504, "s": 6348, "text": "Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Pascal Frossard; The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016, pp. 2574–2582" } ]
How to wait for iFrames to load completely in Selenium webdriver?
We can wait for the iframe to load completely with Selenium webdriver.First of all we need to identify the iframe with the help iframe id, name, number or webelement. Then we shall use the explicit wait concept in synchronization to wait for the iframe to load. We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class. We will wait for the iframe to be loaded with the condition frameToBeAvailableAndSwitchToIt. Let us see an html document of a frame. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; public class FrameLoadWait{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); driver.get("https://the-internet.herokuapp.com/nested_frames"); // frame load explicit condition WebDriverWait w = new WebDriverWait(driver, 5); w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frame-bottom")); // identify element inside frame WebElement p=driver.findElement(By.cssSelector("body")); System.out.println("Text inside frame is: " + p.getText()); driver.close(); } }
[ { "code": null, "e": 1324, "s": 1062, "text": "We can wait for the iframe to load completely with Selenium webdriver.First of all we need to identify the iframe with the help iframe id, name, number or webelement. Then we shall use the explicit wait concept in synchronization to wait for the iframe to load." }, { "code": null, "e": 1601, "s": 1324, "text": "We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class. We will wait for the iframe to be loaded with the condition frameToBeAvailableAndSwitchToIt." }, { "code": null, "e": 1641, "s": 1601, "text": "Let us see an html document of a frame." }, { "code": null, "e": 2682, "s": 1641, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.WebDriverWait;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\n\npublic class FrameLoadWait{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);\n driver.get(\"https://the-internet.herokuapp.com/nested_frames\");\n // frame load explicit condition\n WebDriverWait w = new WebDriverWait(driver, 5); \n w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(\"frame-bottom\"));\n // identify element inside frame\n WebElement p=driver.findElement(By.cssSelector(\"body\"));\n System.out.println(\"Text inside frame is: \" + p.getText());\n driver.close();\n }\n}" } ]
Write a C Program to count the frequency of each character
Follow the algorithm to write a C program which enables to count the frequency of each character. Step 1: Define MAX size. Step 2: Declare char and integer variables. Step 3: Read the string from console. Step 4: Find length of the string. Step 5: Initialize frequency of each character to 0. Step 6: Find total number of occurrences of each character. for(i=0; i<length; i++) i. if(string[i]>='a' && string[i]<='z') frequency[string[i] - 97]++; ii. else if(string[i]>='A' && string[i]<='Z') frequency[string[i] - 65]++; Step 7: Print the frequency of all characters in the string. if(frequency[i] != 0) printf("'%c' = %d\n", (i + 97), frequency[i]); Given below is the C program to count frequency of each character in a string − Live Demo #include <stdio.h> #include <string.h> #define MAX 100 // Maximum string size int main(){ char string[MAX]; int i, length; int frequency[20]; /* Input string from user */ printf("enter the string:\n "); gets(string); length = strlen(string); /* Initialize frequency of each character to 0 */ for(i=0; i<20; i++){ frequency[i] = 0; } /* Find total number of occurrences of each character */ for(i=0; i<length; i++){ /* If the current character is lowercase alphabet */ if(string[i]>='a' && string[i]<='z'){ frequency[string[i] - 97]++; } else if(string[i]>='A' && string[i]<='Z'){ frequency[string[i] - 65]++; } } /* Print the frequency of all characters in the string */ printf("\nFrequency of all characters in string: \n"); for(i=0; i<20; i++){ /* If current character exists in given string */ if(frequency[i] != 0){ printf("'%c' = %d\n", (i + 97), frequency[i]); } } return 0; } When the above program is executed, it produces the following result − enter the string: Tutorials Point Frequency of all characters in string: 'a' = 1 'i' = 2 'l' = 1 'n' = 1 'o' = 2 'p' = 1 'r' = 1 's' = 1 't' = 3
[ { "code": null, "e": 1160, "s": 1062, "text": "Follow the algorithm to write a C program which enables to count the frequency of each character." }, { "code": null, "e": 1731, "s": 1160, "text": "Step 1: Define MAX size.\nStep 2: Declare char and integer variables.\nStep 3: Read the string from console.\nStep 4: Find length of the string.\nStep 5: Initialize frequency of each character to 0.\nStep 6: Find total number of occurrences of each character.\nfor(i=0; i<length; i++)\n i. if(string[i]>='a' && string[i]<='z')\n frequency[string[i] - 97]++;\n ii. else if(string[i]>='A' && string[i]<='Z')\n frequency[string[i] - 65]++;\nStep 7: Print the frequency of all characters in the string.\nif(frequency[i] != 0)\n printf(\"'%c' = %d\\n\", (i + 97), frequency[i]);" }, { "code": null, "e": 1811, "s": 1731, "text": "Given below is the C program to count frequency of each character in a string −" }, { "code": null, "e": 1822, "s": 1811, "text": " Live Demo" }, { "code": null, "e": 2840, "s": 1822, "text": "#include <stdio.h>\n#include <string.h>\n#define MAX 100 // Maximum string size\nint main(){\n char string[MAX];\n int i, length;\n int frequency[20];\n /* Input string from user */\n printf(\"enter the string:\\n \");\n gets(string);\n length = strlen(string);\n /* Initialize frequency of each character to 0 */\n for(i=0; i<20; i++){\n frequency[i] = 0;\n }\n /* Find total number of occurrences of each character */\n for(i=0; i<length; i++){\n /* If the current character is lowercase alphabet */\n if(string[i]>='a' && string[i]<='z'){\n frequency[string[i] - 97]++;\n }\n else if(string[i]>='A' && string[i]<='Z'){\n frequency[string[i] - 65]++;\n }\n }\n /* Print the frequency of all characters in the string */\n printf(\"\\nFrequency of all characters in string: \\n\");\n for(i=0; i<20; i++){\n /* If current character exists in given string */\n if(frequency[i] != 0){\n printf(\"'%c' = %d\\n\", (i + 97), frequency[i]);\n }\n }\n return 0;\n}" }, { "code": null, "e": 2911, "s": 2840, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3056, "s": 2911, "text": "enter the string:\nTutorials Point\nFrequency of all characters in string:\n'a' = 1\n'i' = 2\n'l' = 1\n'n' = 1\n'o' = 2\n'p' = 1\n'r' = 1\n's' = 1\n't' = 3" } ]
File Objects in Java
The File object represents the actual file/directory on the disk. Here are the list of constructors to create File Object in Java − Assuming an object is present in the given location, the first argument to the command line will be considered as the path and the below code will be executed − import java.io.File; public class Demo{ public static void main(String[] args){ String file_name =args[0]; File my_file = new File(file_name); System.out.println("File name is :"+my_file.getName()); System.out.println("The path to the file is: "+my_file.getPath()); System.out.println("The absolute path to the file is:" +my_file.getAbsolutePath()); System.out.println("The parent directory is :"+my_file.getParent()); if(my_file.exists()){ System.out.println("Is the file readable"+my_file.canRead()); System.out.println("The size of the file in bytes is "+my_file.length()); } } } The details about the file will be displayed here. A class named Demo contains the main function, and a string is defined, that holds the first argument passed in the command line. The details of the file are printed on the screen, this includes name of the file, file path, the absolute path of the file, and the parent directory of the file.
[ { "code": null, "e": 1194, "s": 1062, "text": "The File object represents the actual file/directory on the disk. Here are the list of constructors to\ncreate File Object in Java −" }, { "code": null, "e": 1355, "s": 1194, "text": "Assuming an object is present in the given location, the first argument to the command line will be\nconsidered as the path and the below code will be executed −" }, { "code": null, "e": 2010, "s": 1355, "text": "import java.io.File;\npublic class Demo{\n public static void main(String[] args){\n String file_name =args[0];\n File my_file = new File(file_name);\n System.out.println(\"File name is :\"+my_file.getName());\n System.out.println(\"The path to the file is: \"+my_file.getPath());\n System.out.println(\"The absolute path to the file is:\" +my_file.getAbsolutePath());\n System.out.println(\"The parent directory is :\"+my_file.getParent());\n if(my_file.exists()){\n System.out.println(\"Is the file readable\"+my_file.canRead());\n System.out.println(\"The size of the file in bytes is \"+my_file.length());\n }\n }\n}" }, { "code": null, "e": 2061, "s": 2010, "text": "The details about the file will be displayed here." }, { "code": null, "e": 2354, "s": 2061, "text": "A class named Demo contains the main function, and a string is defined, that holds the first\nargument passed in the command line. The details of the file are printed on the screen, this includes\nname of the file, file path, the absolute path of the file, and the parent directory of the file." } ]
MuseGAN: Using GANs to generate original Music | by Victor Sim | Towards Data Science
Here is the github repo (ads) of this project: GANs are highly versatile, allowing for the generation of anything that can be synthesized into images. By utilizing this feature of GANs, it is possible to generate very unorthodox content, at least from the perspective of machine learning. This article is sharing my project where I used GANs to generate baroque music, based on midi files of Bach compositions. This is not the first time that I used GANs to generate creative content. I wrote a GAN last time that would generate art, based on famous artworks by famous artists. From that project I have a few key takeaways about GANs and how to balance them out: Quality over quantity. When I first trained the GAN to generate art, I used a massive jumble of realistic, abstract and impressionist artworks to train the GAN. The results of this paled in comparison with those generated by being only trained in each category.Balance is key. The thing that holds the GAN together is the adversarial relationship between the discriminator and the generator. If the discriminator gets too get at recognizing fake generations, the generator is stuck in its current position. If the discriminator gets too weak at recognizing fake generations, the generator starts to exploit the environment and starts to generating content that tricks the discriminator, but does not imitate the real data points. Quality over quantity. When I first trained the GAN to generate art, I used a massive jumble of realistic, abstract and impressionist artworks to train the GAN. The results of this paled in comparison with those generated by being only trained in each category. Balance is key. The thing that holds the GAN together is the adversarial relationship between the discriminator and the generator. If the discriminator gets too get at recognizing fake generations, the generator is stuck in its current position. If the discriminator gets too weak at recognizing fake generations, the generator starts to exploit the environment and starts to generating content that tricks the discriminator, but does not imitate the real data points. With these two key takeaways, I got to work on the program: The first step to machine learning is the data preprocessing. For this project, it contains 3 steps: I found a dataset online on bach’s compositions online, scraped from an online website. I extracted all the midi files and put them into a folder. I found a github page that had 2 programs that used the music21 library to convert midi files into images and back. Each note can be represented as a white block. The height of the block defines the pitch, and the length defines how long the note is played. I then wrote a script to integrate these two programs with my midi files, to create new images in a different directory: import osimport numpy as nppath = 'XXXXXXXXX'os.chdir(path)midiz = os.listdir()midis = []for midi in midiz: midis.append(path+'\\'+midi) This script goes to midi directory, and then adds all the midi file paths to a list, to be accessed later. from music21 import midimf = midi.MidiFile()mf.open(midis[0]) mf.read()mf.close()s = midi.translate.midiFileToStream(mf)s.show('midi') This script opens the first midi file, and plays it to make sure that the program is working. This might not work if you run this in a non-interactive environment. import osimport numpy as npimport py_midicsv as pmos.chdir(path)midiz = os.listdir()midis = []for midi in midiz: midis.append(path+'\\'+midi) new_dir = 'XXXXXXXX'for midi in midis: try: midi2image(midi) basewidth = 106 img_path = midi.split('\\')[-1].replace(".mid",".png") img_path = new_dir+"\\"+img_path print(img_path) img = Image.open(img_path) hsize = 106 img = img.resize((basewidth,hsize), Image.ANTIALIAS) img.save(img_path) except: pass This script uses the midi2image function from the github page and converts all the midi files, given the path to the midi files. They are also reshaped into the shape (106,106). Why? 106 is the height of the program, as this is the number of possible notes on a midi file. Also, it is much easier to work with squares for convolutional transpositions. import osfrom PIL import Imagefrom matplotlib import pyplot as plt import numpy as nppath = 'XXXXXXXXXXXXXX'os.getcwd()img_list = os.listdir(path)def access_images(img_list,path,length): pixels = [] imgs = [] for i in range(length): if 'png' in img_list[i]: try: img = Image.open(path+'/'+img_list[i],'r') img = img.convert('1') pix = np.array(img.getdata()) pix = pix.astype('float32') pix /= 255.0 pixels.append(pix.reshape(106,106,1)) imgs.append(img) except: pass return np.array(pixels),imgsdef show_image(pix_list): array = np.array(pix_list.reshape(106,106), dtype=np.uint8) new_image = Image.fromarray(array) new_image.show() pixels,imgs = access_images(img_list,path,200) This script goes to the directory that contains all the images and records all the pixel values. This will be the pixel values that will be used as the real samples that will be fed into the discriminator, along with the computer generated samples. The pixel values have to be divided by 255, so that the values can be either 1 or 0 (white or black), which makes it easier for the program to work well. np.unique(pixels) This script just makes sure that the pixels values have been normalized between 1 and 0. There are quite a lot of prerequisites for this program to work: from numpy import zerosfrom numpy import onesfrom numpy import vstackfrom numpy.random import randnfrom numpy.random import randintfrom keras.datasets.mnist import load_datafrom keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Reshapefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Conv2Dfrom keras.layers import Conv2DTransposefrom keras.layers import LeakyReLUfrom keras.layers import Dropoutfrom matplotlib import pyplotfrom IPython.display import clear_output These are basically all the layers and numpy functions that need to be used when running the GAN. clear_output is just to clear the screen every 10 epochs, so that the screen does not get clogged up. def define_discriminator(in_shape = (106,106,1)): model = Sequential() model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same', input_shape=in_shape)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.5)) model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(BatchNormalization()) model.add(Dense(1, activation='sigmoid')) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']) return model This discriminator has been fine-tuned after a lot of experimentation. The convolutional layers have a low number of nodes, so that the generator can catch up with the discriminator before the discriminator gets too ahead. The layers of dropout are also necessary so that the discriminator does not overfit on the data. def define_generator(latent_dim): model = Sequential() n_nodes = 128 * 53 * 53 model.add(Dense(n_nodes, input_dim=latent_dim)) model.add(LeakyReLU(alpha=0.2)) model.add(Reshape((53, 53, 128))) model.add(Dense(1024)) model.add(Conv2DTranspose(1024, (4,4), strides=(2,2), padding='same')) model.add(Dense(1024)) model.add(LeakyReLU(alpha=0.2)) model.add(Dense(1024)) model.add(Conv2D(1, (7,7) , padding='same',activation = 'sigmoid')) return model The generator is especially deep, because in nearly all cases, the generator will fall behind. The use of leaky relu is to prevent the “dying relu” problem, where values smaller than 1 block training completely. The latent_dimension for this GAN must not be too big, as it could slow down the generator’s training. The value that I decided for it is 100 def define_gan(g_model, d_model): d_model.trainable = False model = Sequential() model.add(g_model) model.add(d_model) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt) return model This script combines the discriminator and the generator together, so the loss from the discriminator can be backpropagated back into the generator. def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_latent_points(latent_dim, n_samples): x_input = randn(latent_dim * n_samples) x_input = x_input.reshape(n_samples, latent_dim) return x_inputdef generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input) y = zeros((n_samples, 1)) return X, y These free functions are able to generate all the parameters and data that the GAN needs to function: The latent_points work as the input of the generator while the fake and real samples are to train and test the discriminator. def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=51, n_batch=10): bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_real_samples(dataset, half_batch) X_fake, y_fake = generate_fake_samples(g_model, latent_dim, half_batch) X, y = vstack((X_real, X_fake)), vstack((y_real, y_fake)) d_loss, _ = d_model.train_on_batch(X, y) X_gan = generate_latent_points(latent_dim, n_batch) y_gan = ones((n_batch, 1)) g_loss = gan_model.train_on_batch(X_gan, y_gan) print('>%d, %d/%d, d=%.3f, g=%.3f' % (i+1, j+1, bat_per_epo, d_loss, g_loss)) if (i+1) % 10 == 0: summarize_performance(i, g_model, d_model, dataset, latent_dim) clear_output() This function trains the GAN. It basically orchestrates all the functions defined above and prints the loss for both the discriminator and the generator. This allows you to check the balance between the generator and the discriminator. latent_dim = 100d_model = define_discriminator()g_model = define_generator(latent_dim)gan_model = define_gan(g_model, d_model)print(pixels.shape)train(g_model, d_model, gan_model, np.array(pixels), latent_dim) This script is just calling upon the functions and actually running the program. from keras.models import load_modelfrom numpy.random import randnfrom matplotlib import pyplotdef generate_latent_points(latent_dim, n_samples): x_input = randn(latent_dim * n_samples) x_input = x_input.reshape(n_samples, latent_dim) return x_inputmodel = g_modellatent_points = generate_latent_points(latent_dim,1)X = g_model.predict(latent_points)array = np.array(X.reshape(106,106),dtype = np.uint8)array*= 255new_image = Image.fromarray(array,'L')new_image = new_image.save('composition.png') This script calls upon the model to make predictions on latent points, which results in an array. This array is then converted into an image using PIL. image2midi('composition.png') After converting the image into a midi file, you can run these commands in a cell to listen to the midi file. !apt install fluidsynth!cp /usr/share/sounds/sf2/FluidR3_GM.sf2 ./font.sf2!fluidsynth -ni font.sf2 composition.mid -F output.wav -r 44100from IPython.display import AudioAudio('output.wav') Here are a few of my favourite cuts from the AI generated music: The model has begun to pick up on song structure, basic harmony and rhythm, although it does start to sound a bit like jazz music. If you want to see more of my content, click this link.
[ { "code": null, "e": 94, "s": 47, "text": "Here is the github repo (ads) of this project:" }, { "code": null, "e": 458, "s": 94, "text": "GANs are highly versatile, allowing for the generation of anything that can be synthesized into images. By utilizing this feature of GANs, it is possible to generate very unorthodox content, at least from the perspective of machine learning. This article is sharing my project where I used GANs to generate baroque music, based on midi files of Bach compositions." }, { "code": null, "e": 710, "s": 458, "text": "This is not the first time that I used GANs to generate creative content. I wrote a GAN last time that would generate art, based on famous artworks by famous artists. From that project I have a few key takeaways about GANs and how to balance them out:" }, { "code": null, "e": 1440, "s": 710, "text": "Quality over quantity. When I first trained the GAN to generate art, I used a massive jumble of realistic, abstract and impressionist artworks to train the GAN. The results of this paled in comparison with those generated by being only trained in each category.Balance is key. The thing that holds the GAN together is the adversarial relationship between the discriminator and the generator. If the discriminator gets too get at recognizing fake generations, the generator is stuck in its current position. If the discriminator gets too weak at recognizing fake generations, the generator starts to exploit the environment and starts to generating content that tricks the discriminator, but does not imitate the real data points." }, { "code": null, "e": 1702, "s": 1440, "text": "Quality over quantity. When I first trained the GAN to generate art, I used a massive jumble of realistic, abstract and impressionist artworks to train the GAN. The results of this paled in comparison with those generated by being only trained in each category." }, { "code": null, "e": 2171, "s": 1702, "text": "Balance is key. The thing that holds the GAN together is the adversarial relationship between the discriminator and the generator. If the discriminator gets too get at recognizing fake generations, the generator is stuck in its current position. If the discriminator gets too weak at recognizing fake generations, the generator starts to exploit the environment and starts to generating content that tricks the discriminator, but does not imitate the real data points." }, { "code": null, "e": 2231, "s": 2171, "text": "With these two key takeaways, I got to work on the program:" }, { "code": null, "e": 2332, "s": 2231, "text": "The first step to machine learning is the data preprocessing. For this project, it contains 3 steps:" }, { "code": null, "e": 2479, "s": 2332, "text": "I found a dataset online on bach’s compositions online, scraped from an online website. I extracted all the midi files and put them into a folder." }, { "code": null, "e": 2595, "s": 2479, "text": "I found a github page that had 2 programs that used the music21 library to convert midi files into images and back." }, { "code": null, "e": 2737, "s": 2595, "text": "Each note can be represented as a white block. The height of the block defines the pitch, and the length defines how long the note is played." }, { "code": null, "e": 2858, "s": 2737, "text": "I then wrote a script to integrate these two programs with my midi files, to create new images in a different directory:" }, { "code": null, "e": 2998, "s": 2858, "text": "import osimport numpy as nppath = 'XXXXXXXXX'os.chdir(path)midiz = os.listdir()midis = []for midi in midiz: midis.append(path+'\\\\'+midi)" }, { "code": null, "e": 3105, "s": 2998, "text": "This script goes to midi directory, and then adds all the midi file paths to a list, to be accessed later." }, { "code": null, "e": 3240, "s": 3105, "text": "from music21 import midimf = midi.MidiFile()mf.open(midis[0]) mf.read()mf.close()s = midi.translate.midiFileToStream(mf)s.show('midi')" }, { "code": null, "e": 3404, "s": 3240, "text": "This script opens the first midi file, and plays it to make sure that the program is working. This might not work if you run this in a non-interactive environment." }, { "code": null, "e": 3933, "s": 3404, "text": "import osimport numpy as npimport py_midicsv as pmos.chdir(path)midiz = os.listdir()midis = []for midi in midiz: midis.append(path+'\\\\'+midi) new_dir = 'XXXXXXXX'for midi in midis: try: midi2image(midi) basewidth = 106 img_path = midi.split('\\\\')[-1].replace(\".mid\",\".png\") img_path = new_dir+\"\\\\\"+img_path print(img_path) img = Image.open(img_path) hsize = 106 img = img.resize((basewidth,hsize), Image.ANTIALIAS) img.save(img_path) except: pass" }, { "code": null, "e": 4285, "s": 3933, "text": "This script uses the midi2image function from the github page and converts all the midi files, given the path to the midi files. They are also reshaped into the shape (106,106). Why? 106 is the height of the program, as this is the number of possible notes on a midi file. Also, it is much easier to work with squares for convolutional transpositions." }, { "code": null, "e": 5139, "s": 4285, "text": "import osfrom PIL import Imagefrom matplotlib import pyplot as plt import numpy as nppath = 'XXXXXXXXXXXXXX'os.getcwd()img_list = os.listdir(path)def access_images(img_list,path,length): pixels = [] imgs = [] for i in range(length): if 'png' in img_list[i]: try: img = Image.open(path+'/'+img_list[i],'r') img = img.convert('1') pix = np.array(img.getdata()) pix = pix.astype('float32') pix /= 255.0 pixels.append(pix.reshape(106,106,1)) imgs.append(img) except: pass return np.array(pixels),imgsdef show_image(pix_list): array = np.array(pix_list.reshape(106,106), dtype=np.uint8) new_image = Image.fromarray(array) new_image.show() pixels,imgs = access_images(img_list,path,200)" }, { "code": null, "e": 5542, "s": 5139, "text": "This script goes to the directory that contains all the images and records all the pixel values. This will be the pixel values that will be used as the real samples that will be fed into the discriminator, along with the computer generated samples. The pixel values have to be divided by 255, so that the values can be either 1 or 0 (white or black), which makes it easier for the program to work well." }, { "code": null, "e": 5560, "s": 5542, "text": "np.unique(pixels)" }, { "code": null, "e": 5649, "s": 5560, "text": "This script just makes sure that the pixels values have been normalized between 1 and 0." }, { "code": null, "e": 5714, "s": 5649, "text": "There are quite a lot of prerequisites for this program to work:" }, { "code": null, "e": 6275, "s": 5714, "text": "from numpy import zerosfrom numpy import onesfrom numpy import vstackfrom numpy.random import randnfrom numpy.random import randintfrom keras.datasets.mnist import load_datafrom keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Reshapefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Conv2Dfrom keras.layers import Conv2DTransposefrom keras.layers import LeakyReLUfrom keras.layers import Dropoutfrom matplotlib import pyplotfrom IPython.display import clear_output" }, { "code": null, "e": 6475, "s": 6275, "text": "These are basically all the layers and numpy functions that need to be used when running the GAN. clear_output is just to clear the screen every 10 epochs, so that the screen does not get clogged up." }, { "code": null, "e": 7062, "s": 6475, "text": "def define_discriminator(in_shape = (106,106,1)): model = Sequential() model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same', input_shape=in_shape)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.5)) model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(BatchNormalization()) model.add(Dense(1, activation='sigmoid')) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']) return model" }, { "code": null, "e": 7382, "s": 7062, "text": "This discriminator has been fine-tuned after a lot of experimentation. The convolutional layers have a low number of nodes, so that the generator can catch up with the discriminator before the discriminator gets too ahead. The layers of dropout are also necessary so that the discriminator does not overfit on the data." }, { "code": null, "e": 7864, "s": 7382, "text": "def define_generator(latent_dim): model = Sequential() n_nodes = 128 * 53 * 53 model.add(Dense(n_nodes, input_dim=latent_dim)) model.add(LeakyReLU(alpha=0.2)) model.add(Reshape((53, 53, 128))) model.add(Dense(1024)) model.add(Conv2DTranspose(1024, (4,4), strides=(2,2), padding='same')) model.add(Dense(1024)) model.add(LeakyReLU(alpha=0.2)) model.add(Dense(1024)) model.add(Conv2D(1, (7,7) , padding='same',activation = 'sigmoid')) return model" }, { "code": null, "e": 8218, "s": 7864, "text": "The generator is especially deep, because in nearly all cases, the generator will fall behind. The use of leaky relu is to prevent the “dying relu” problem, where values smaller than 1 block training completely. The latent_dimension for this GAN must not be too big, as it could slow down the generator’s training. The value that I decided for it is 100" }, { "code": null, "e": 8462, "s": 8218, "text": "def define_gan(g_model, d_model): d_model.trainable = False model = Sequential() model.add(g_model) model.add(d_model) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt) return model" }, { "code": null, "e": 8611, "s": 8462, "text": "This script combines the discriminator and the generator together, so the loss from the discriminator can be backpropagated back into the generator." }, { "code": null, "e": 9125, "s": 8611, "text": "def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_latent_points(latent_dim, n_samples): x_input = randn(latent_dim * n_samples) x_input = x_input.reshape(n_samples, latent_dim) return x_inputdef generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input) y = zeros((n_samples, 1)) return X, y" }, { "code": null, "e": 9353, "s": 9125, "text": "These free functions are able to generate all the parameters and data that the GAN needs to function: The latent_points work as the input of the generator while the fake and real samples are to train and test the discriminator." }, { "code": null, "e": 10238, "s": 9353, "text": "def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=51, n_batch=10): bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_real_samples(dataset, half_batch) X_fake, y_fake = generate_fake_samples(g_model, latent_dim, half_batch) X, y = vstack((X_real, X_fake)), vstack((y_real, y_fake)) d_loss, _ = d_model.train_on_batch(X, y) X_gan = generate_latent_points(latent_dim, n_batch) y_gan = ones((n_batch, 1)) g_loss = gan_model.train_on_batch(X_gan, y_gan) print('>%d, %d/%d, d=%.3f, g=%.3f' % (i+1, j+1, bat_per_epo, d_loss, g_loss)) if (i+1) % 10 == 0: summarize_performance(i, g_model, d_model, dataset, latent_dim) clear_output()" }, { "code": null, "e": 10474, "s": 10238, "text": "This function trains the GAN. It basically orchestrates all the functions defined above and prints the loss for both the discriminator and the generator. This allows you to check the balance between the generator and the discriminator." }, { "code": null, "e": 10684, "s": 10474, "text": "latent_dim = 100d_model = define_discriminator()g_model = define_generator(latent_dim)gan_model = define_gan(g_model, d_model)print(pixels.shape)train(g_model, d_model, gan_model, np.array(pixels), latent_dim)" }, { "code": null, "e": 10765, "s": 10684, "text": "This script is just calling upon the functions and actually running the program." }, { "code": null, "e": 11271, "s": 10765, "text": "from keras.models import load_modelfrom numpy.random import randnfrom matplotlib import pyplotdef generate_latent_points(latent_dim, n_samples): x_input = randn(latent_dim * n_samples) x_input = x_input.reshape(n_samples, latent_dim) return x_inputmodel = g_modellatent_points = generate_latent_points(latent_dim,1)X = g_model.predict(latent_points)array = np.array(X.reshape(106,106),dtype = np.uint8)array*= 255new_image = Image.fromarray(array,'L')new_image = new_image.save('composition.png')" }, { "code": null, "e": 11423, "s": 11271, "text": "This script calls upon the model to make predictions on latent points, which results in an array. This array is then converted into an image using PIL." }, { "code": null, "e": 11453, "s": 11423, "text": "image2midi('composition.png')" }, { "code": null, "e": 11563, "s": 11453, "text": "After converting the image into a midi file, you can run these commands in a cell to listen to the midi file." }, { "code": null, "e": 11753, "s": 11563, "text": "!apt install fluidsynth!cp /usr/share/sounds/sf2/FluidR3_GM.sf2 ./font.sf2!fluidsynth -ni font.sf2 composition.mid -F output.wav -r 44100from IPython.display import AudioAudio('output.wav')" }, { "code": null, "e": 11818, "s": 11753, "text": "Here are a few of my favourite cuts from the AI generated music:" }, { "code": null, "e": 11949, "s": 11818, "text": "The model has begun to pick up on song structure, basic harmony and rhythm, although it does start to sound a bit like jazz music." } ]
Tryit Editor v3.7
Tryit: HTML layout
[]
Microsoft Interview Experience | Set 141 (Off-Campus - Online Coding Test for IDC) - GeeksforGeeks
06 Nov, 2017 The online test was conducted on CoCubes on 2017, 5th November. The test was webcam enabled to avoid any kind of cheating. You cannot open any other tab or minimize the window. It consisted of 3 coding questions. TIME LIMIT: 75 minutes(*) Marks(Qn-1) = 2 (*) Marks(Qn-2) = 3 (*) Marks(Qn-3) = 5 Question 1: Write a function which accepts an integer array and its size and modifies the array in the following manner: 1) If the elements of index i and (i+1) are equal then, double the value at index i and replace the element at index (i+1) with 0. 2) If the element at index i is 0, then ignore it. 3) Any number (element in an array) must be modified only once. 4) At the end, shift all the zeros (0s) to the right of the array and remaining nonzeros to the left of the array. Example: Input: 2 2 0 4 0 8 Output: 4 4 8 0 0 0 Input: 2 2 0 4 0 2 Output: 4 4 2 0 0 0 Question 2: Write a function which accepts an integer array and its size and returns the maximum index difference i.e. (i-j) such that array[i] < array[j] and i < j. If there is no such case, return -1 . Input: 2 0 3 5 6 1 Output: 4 There was only one test case given which is mentioned above. But I am providing the below one of the sample cases which is an important thing to be noted. It returns -1 because all the elements after any given element are smaller than it. DO take care of such cases. Input: 9 8 7 6 5 Output: -1 Question 3: Write a function which accepts the root of a tree, and returns a Linked List which contains the leaf nodes of the tree from left to right order.Assumptions: (*) Structure of the node of tree is as follows: struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right; }; (*) Don't allocate extra memory for Linked List, just let the right pointer of a leaf node point to the next leaf node to form a linked list. Example: 10 / \ 20 100 / \ / \ 30 40 9 66 Output: 30 -> 40 -> 9 -> 66 Keep practicing questions from GeeksForGeeks. This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Microsoft Interview Experiences Microsoft Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Directi Interview | Set 7 (Programming Questions) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience (Off-Campus) 2022 Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience for SDE-1(Off-Campus)
[ { "code": null, "e": 25268, "s": 25240, "text": "\n06 Nov, 2017" }, { "code": null, "e": 25481, "s": 25268, "text": "The online test was conducted on CoCubes on 2017, 5th November. The test was webcam enabled to avoid any kind of cheating. You cannot open any other tab or minimize the window. It consisted of 3 coding questions." }, { "code": null, "e": 25523, "s": 25481, "text": "TIME LIMIT: 75 minutes(*) Marks(Qn-1) = 2" }, { "code": null, "e": 25543, "s": 25523, "text": "(*) Marks(Qn-2) = 3" }, { "code": null, "e": 25563, "s": 25543, "text": "(*) Marks(Qn-3) = 5" }, { "code": null, "e": 25684, "s": 25563, "text": "Question 1: Write a function which accepts an integer array and its size and modifies the array in the following manner:" }, { "code": null, "e": 26140, "s": 25684, "text": "1) If the elements of index i and (i+1) are equal then, double the value at index i\nand replace the element at index (i+1) with 0. \n\n2) If the element at index i is 0, then ignore it.\n\n3) Any number (element in an array) must be modified only once.\n\n4) At the end, shift all the zeros (0s) to the right of the array and remaining\nnonzeros to the left of the array.\n\nExample: \nInput: 2 2 0 4 0 8\nOutput: 4 4 8 0 0 0\n\nInput: 2 2 0 4 0 2\nOutput: 4 4 2 0 0 0\n" }, { "code": null, "e": 26344, "s": 26140, "text": "Question 2: Write a function which accepts an integer array and its size and returns the maximum index difference i.e. (i-j) such that array[i] < array[j] and i < j.\nIf there is no such case, return -1 ." }, { "code": null, "e": 26671, "s": 26344, "text": "Input: 2 0 3 5 6 1\nOutput: 4\n\nThere was only one test case given which is mentioned above. But I am providing the below\none of the sample cases which is an important thing to be noted. It returns -1 because all the\nelements after any given element are smaller than it. DO take care of such cases.\n\nInput: 9 8 7 6 5\nOutput: -1\n" }, { "code": null, "e": 26840, "s": 26671, "text": "Question 3: Write a function which accepts the root of a tree, and returns a Linked List which contains the leaf nodes of the tree from left to right order.Assumptions:" }, { "code": null, "e": 27306, "s": 26840, "text": "(*) Structure of the node of tree is as follows:\nstruct TreeNode\n{\n int data;\n struct TreeNode* left;\n struct TreeNode* right;\n};\n\n(*) Don't allocate extra memory for Linked List, just let the right pointer of a leaf\nnode point to the next leaf node to form a linked list.\n\nExample:\n 10 \n / \\ \n 20 100 \n / \\ / \\ \n 30 40 9 66\n\nOutput: 30 -> 40 -> 9 -> 66 \n \n" }, { "code": null, "e": 27352, "s": 27306, "text": "Keep practicing questions from GeeksForGeeks." }, { "code": null, "e": 27656, "s": 27352, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27781, "s": 27656, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27791, "s": 27781, "text": "Microsoft" }, { "code": null, "e": 27813, "s": 27791, "text": "Interview Experiences" }, { "code": null, "e": 27823, "s": 27813, "text": "Microsoft" }, { "code": null, "e": 27921, "s": 27823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27930, "s": 27921, "text": "Comments" }, { "code": null, "e": 27943, "s": 27930, "text": "Old Comments" }, { "code": null, "e": 27993, "s": 27943, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 28052, "s": 27993, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 28090, "s": 28052, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28126, "s": 28090, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 28176, "s": 28126, "text": "Directi Interview | Set 7 (Programming Questions)" }, { "code": null, "e": 28214, "s": 28176, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28279, "s": 28214, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 28325, "s": 28279, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 28361, "s": 28325, "text": "Zoho Interview | Set 3 (Off-Campus)" } ]
Cellular Nucleus Image Segmentation Project | by Christopher Bui | Towards Data Science
The 2018 Data Science Bowl Kaggle competition caught my attention for its potential to have a profoundly practical impact in the biotechnology industry. This post covers my overall experience while a detailed summary of my work can be found on my Github. The Challenge: Given microscope images of many types of nuclei taken in varying environment conditions, build a machine learning model that can detect the nuclei. The Motivation: The goal of this challenge is to establish a foundation for the ability to quantify a facet of a biological system. Specifically, by having a model that can segment out nuclei among the messiness in a microscope image, one can apply currently available software to count the number of detected nuclei. Knowing the number of nuclei in a biological sample allows scientists to quantify their observations rather than “eye-balling” them. For example, in the realm of drug discovery research, after applying a test drug to a batch of cells, this model would be able to report whether the cell count increased or decreased in response to the drug. Furthermore, traditional software methods that perform this same task are limited in their abilities and can take days to a week to accomplish. By decreasing the time of this task, I can only imagine costs for related research to decrease and the opportunities of discovering a beneficial drug to come sooner. This video from the challenge’s organizer expands on the motivation. The Model: This project’s challenge is an image segmentation problem. There are numerous convolution neural network (CNN) architectures, each apt for a certain task. For biomedical applications however, the U-Net architecture has proven to be quite successful. So accordingly, I built my model based on that architecture. My goal was to utilize the U-Net CNN to segment the nuclei apart from miscellaneous objects in the images. The training data consists of 670 raw microscope images. In addition, each raw image has its respective binary mask, a separate image such that white pixels designate nuclei-present regions, and black pixels designate nuclei-absent regions. The binary masks had been manually labeled by the competition’s organizers. We need these binary masks so that the model has a reference to know whether it has segmented nuclei correctly or not during the training stage. I then trained the model on 600 images, setting aside 70 for the test set. The Results: Here is the U-Net architecture Python code. After training the model, I test it on the 70 images from the test set. For each test image, the model returns a predicted binary image. We evaluate the performance of the model by overlaying the original image’s binary mask over the predicted result. From this, we see regions where the model predicted correctly and incorrectly. The colors in the overlay image above are as follows: Yellow: True Positive Black: True Negative Green: False Positive (Error) Red: False Negative (Error) To quantify the model’s performance, I used the Jaccard Distance (a.k.a. Intersection Over Union) metric. This Jaccard Distance value is calculated by taking the area of regions where nuclei was predicted correctly (true positives), and dividing that value by the sum of the false negative, false positive, and true positive areas. Jaccard Distance = True Positive / (True Positive + False Negative + False Positive) This metric value thus ranges between 0 to 1. A perfect score of 1 translates to the model being able to detect all regions of nuclei without any false negatives and false positives. For the 70 test images, my average Jaccard Distance equaled 0.75. This means that on average, the model was able to correctly detect quite a significant portion of all nuclei. Conclusion: The results show that the U-Net architecture works satisfactorily in segmenting out regions of nuclei. Although not 100% optimal, the outcome is adequate for a biologist’s line of work and needs. The model consistently captures large chunks of nuclei, and any regions of error are insignificant for the interests of a biologist. With the significant portions of segmented nuclei, you can apply other software to now count their number or calculate their size. This will enable a biologist to perform a cell count, but in a much shorter amount of time compared to traditional methods. The notable Python library OpenCV has object detection functionality that can be used to achieve this. Nevertheless, a common challenge persists in the situation where the nuclei overlap. How does the model distinguish between 2 or more overlapping nuclei versus a single one? My rudimentary proposed work-around to this problem is to measure the average nucleus size (topical area in this case since an image depicts a 2D representation of the nuclei) for a type of cell. Then after the model returns a binary image for the same type of nucleus, identify connected white pixel regions that have an area greater than the average nucleus size, within a reasonable amount of error. If such a region surpasses an arbitrary threshold of say 1.5 times the average, then count this region as 2 nuclei. I repeat that this is a crude proposal, and that it only applies to a single type of nuclei as distinct types of nuclei vary in size. Further exploration of this challenge is left for future work. Overall, the goal of this Kaggle competition was to implement a machine learning model that could segment nuclei, and I say my efforts were quite satisfactory. If this task could be further improved by accounting for the problem described above, then I see the potential where such a capable model could be commercialized as a software product for biology researchers in academia and industry alike for its practical usefulness.
[ { "code": null, "e": 427, "s": 172, "text": "The 2018 Data Science Bowl Kaggle competition caught my attention for its potential to have a profoundly practical impact in the biotechnology industry. This post covers my overall experience while a detailed summary of my work can be found on my Github." }, { "code": null, "e": 442, "s": 427, "text": "The Challenge:" }, { "code": null, "e": 590, "s": 442, "text": "Given microscope images of many types of nuclei taken in varying environment conditions, build a machine learning model that can detect the nuclei." }, { "code": null, "e": 606, "s": 590, "text": "The Motivation:" }, { "code": null, "e": 1041, "s": 606, "text": "The goal of this challenge is to establish a foundation for the ability to quantify a facet of a biological system. Specifically, by having a model that can segment out nuclei among the messiness in a microscope image, one can apply currently available software to count the number of detected nuclei. Knowing the number of nuclei in a biological sample allows scientists to quantify their observations rather than “eye-balling” them." }, { "code": null, "e": 1559, "s": 1041, "text": "For example, in the realm of drug discovery research, after applying a test drug to a batch of cells, this model would be able to report whether the cell count increased or decreased in response to the drug. Furthermore, traditional software methods that perform this same task are limited in their abilities and can take days to a week to accomplish. By decreasing the time of this task, I can only imagine costs for related research to decrease and the opportunities of discovering a beneficial drug to come sooner." }, { "code": null, "e": 1628, "s": 1559, "text": "This video from the challenge’s organizer expands on the motivation." }, { "code": null, "e": 1639, "s": 1628, "text": "The Model:" }, { "code": null, "e": 2057, "s": 1639, "text": "This project’s challenge is an image segmentation problem. There are numerous convolution neural network (CNN) architectures, each apt for a certain task. For biomedical applications however, the U-Net architecture has proven to be quite successful. So accordingly, I built my model based on that architecture. My goal was to utilize the U-Net CNN to segment the nuclei apart from miscellaneous objects in the images." }, { "code": null, "e": 2519, "s": 2057, "text": "The training data consists of 670 raw microscope images. In addition, each raw image has its respective binary mask, a separate image such that white pixels designate nuclei-present regions, and black pixels designate nuclei-absent regions. The binary masks had been manually labeled by the competition’s organizers. We need these binary masks so that the model has a reference to know whether it has segmented nuclei correctly or not during the training stage." }, { "code": null, "e": 2594, "s": 2519, "text": "I then trained the model on 600 images, setting aside 70 for the test set." }, { "code": null, "e": 2607, "s": 2594, "text": "The Results:" }, { "code": null, "e": 2788, "s": 2607, "text": "Here is the U-Net architecture Python code. After training the model, I test it on the 70 images from the test set. For each test image, the model returns a predicted binary image." }, { "code": null, "e": 2982, "s": 2788, "text": "We evaluate the performance of the model by overlaying the original image’s binary mask over the predicted result. From this, we see regions where the model predicted correctly and incorrectly." }, { "code": null, "e": 3036, "s": 2982, "text": "The colors in the overlay image above are as follows:" }, { "code": null, "e": 3058, "s": 3036, "text": "Yellow: True Positive" }, { "code": null, "e": 3079, "s": 3058, "text": "Black: True Negative" }, { "code": null, "e": 3109, "s": 3079, "text": "Green: False Positive (Error)" }, { "code": null, "e": 3137, "s": 3109, "text": "Red: False Negative (Error)" }, { "code": null, "e": 3469, "s": 3137, "text": "To quantify the model’s performance, I used the Jaccard Distance (a.k.a. Intersection Over Union) metric. This Jaccard Distance value is calculated by taking the area of regions where nuclei was predicted correctly (true positives), and dividing that value by the sum of the false negative, false positive, and true positive areas." }, { "code": null, "e": 3554, "s": 3469, "text": "Jaccard Distance = True Positive / (True Positive + False Negative + False Positive)" }, { "code": null, "e": 3737, "s": 3554, "text": "This metric value thus ranges between 0 to 1. A perfect score of 1 translates to the model being able to detect all regions of nuclei without any false negatives and false positives." }, { "code": null, "e": 3913, "s": 3737, "text": "For the 70 test images, my average Jaccard Distance equaled 0.75. This means that on average, the model was able to correctly detect quite a significant portion of all nuclei." }, { "code": null, "e": 3925, "s": 3913, "text": "Conclusion:" }, { "code": null, "e": 4121, "s": 3925, "text": "The results show that the U-Net architecture works satisfactorily in segmenting out regions of nuclei. Although not 100% optimal, the outcome is adequate for a biologist’s line of work and needs." }, { "code": null, "e": 4612, "s": 4121, "text": "The model consistently captures large chunks of nuclei, and any regions of error are insignificant for the interests of a biologist. With the significant portions of segmented nuclei, you can apply other software to now count their number or calculate their size. This will enable a biologist to perform a cell count, but in a much shorter amount of time compared to traditional methods. The notable Python library OpenCV has object detection functionality that can be used to achieve this." }, { "code": null, "e": 4786, "s": 4612, "text": "Nevertheless, a common challenge persists in the situation where the nuclei overlap. How does the model distinguish between 2 or more overlapping nuclei versus a single one?" }, { "code": null, "e": 5502, "s": 4786, "text": "My rudimentary proposed work-around to this problem is to measure the average nucleus size (topical area in this case since an image depicts a 2D representation of the nuclei) for a type of cell. Then after the model returns a binary image for the same type of nucleus, identify connected white pixel regions that have an area greater than the average nucleus size, within a reasonable amount of error. If such a region surpasses an arbitrary threshold of say 1.5 times the average, then count this region as 2 nuclei. I repeat that this is a crude proposal, and that it only applies to a single type of nuclei as distinct types of nuclei vary in size. Further exploration of this challenge is left for future work." }, { "code": null, "e": 5662, "s": 5502, "text": "Overall, the goal of this Kaggle competition was to implement a machine learning model that could segment nuclei, and I say my efforts were quite satisfactory." } ]
Check if strings are rotations of each other or not in Python
Suppose we have two strings s and t, we have to check whether t is a rotation of s or not. So, if the input is like s = "hello", t = "llohe", then the output will be True. To solve this, we will follow these steps − if size of s is not same as size of t, thenreturn False return False temp := s concatenate with s again if count of t in temp > 0, thenreturn True return True return False Let us see the following implementation to get better understanding − Live Demo def solve(s, t): if len(s) != len(t): return False temp = s + s if temp.count(t)> 0: return True return False s = "hello" t = "llohe" print(solve(s, t)) "hello", "llohe" True
[ { "code": null, "e": 1153, "s": 1062, "text": "Suppose we have two strings s and t, we have to check whether t is a rotation of s or not." }, { "code": null, "e": 1234, "s": 1153, "text": "So, if the input is like s = \"hello\", t = \"llohe\", then the output will be True." }, { "code": null, "e": 1278, "s": 1234, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1334, "s": 1278, "text": "if size of s is not same as size of t, thenreturn False" }, { "code": null, "e": 1347, "s": 1334, "text": "return False" }, { "code": null, "e": 1382, "s": 1347, "text": "temp := s concatenate with s again" }, { "code": null, "e": 1425, "s": 1382, "text": "if count of t in temp > 0, thenreturn True" }, { "code": null, "e": 1437, "s": 1425, "text": "return True" }, { "code": null, "e": 1450, "s": 1437, "text": "return False" }, { "code": null, "e": 1520, "s": 1450, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1530, "s": 1520, "text": "Live Demo" }, { "code": null, "e": 1712, "s": 1530, "text": "def solve(s, t):\n if len(s) != len(t):\n return False\n \n temp = s + s\n \n if temp.count(t)> 0:\n return True\n return False\n\ns = \"hello\"\nt = \"llohe\"\nprint(solve(s, t))" }, { "code": null, "e": 1730, "s": 1712, "text": "\"hello\", \"llohe\"\n" }, { "code": null, "e": 1735, "s": 1730, "text": "True" } ]
jQuery | prev() & prevAll() with Examples - GeeksforGeeks
13 Feb, 2019 The prev() is an inbuilt function in jQuery which is used to return the previous sibling element of the selected element. Siblings are those having same parent element in DOM Tree. Document Object Model(DOM) is a World Wide Web Consortium standard defined for accessing elements. prev() Syntax: $(selector).prev() Here selector is the selected element whose previous siblings get returned.Parameters: It does not accept any parameter.Return Value: It returns the previous sibling of the selected element. <html> <head> <style> .pre * { display: block; border: 2px solid lightgrey; color: black; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("h3").prev().css({ "color": "black", "border": "2px solid green" }); }); </script></head> <body class="pre"> <div> This is parent element ! <p>This is first paragraph </p> <span>First span box </span> <h2>heading 2 !</h2> <h3>heading 3 !</h3> <p>This is the second paragraph and next sibling to h3 !</p> </div></body> </html> In the above code, previous sibling element of “h3” get highlighted with green color.Output: prevAll() The prevAll() is an inbuilt method in jQuery which is used to return all the previous sibling elements of the selected element.Syntax: $(selector).prevAll() Here selector is the selected element whose previous siblings get returned.Parameters: It does not accept any parameter.Return Value: It returns all the previous sibling elements of the selected element. <html> <head> <style> .preAll * { display: block; border: 2px solid lightgrey; color: black; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("h3").prevAll().css({ "color": "black", "border": "2px solid green" }); }); </script></head> <body class="preAll"> <div> This is parent element ! <p>This is first paragraph </p> <span>first span box </span> <h2>heading 2 !</h2> <h3>heading 3 !</h3> <p>This is the second paragraph and next sibling to h3 !</p> </div></body> </html> In the above code, all the previous sibling elements of “h3” get highlighted with green color.Output: jQuery-Traversing JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ? How to add options to a select element using jQuery?
[ { "code": null, "e": 24761, "s": 24733, "text": "\n13 Feb, 2019" }, { "code": null, "e": 25041, "s": 24761, "text": "The prev() is an inbuilt function in jQuery which is used to return the previous sibling element of the selected element. Siblings are those having same parent element in DOM Tree. Document Object Model(DOM) is a World Wide Web Consortium standard defined for accessing elements." }, { "code": null, "e": 25048, "s": 25041, "text": "prev()" }, { "code": null, "e": 25056, "s": 25048, "text": "Syntax:" }, { "code": null, "e": 25076, "s": 25056, "text": "$(selector).prev()\n" }, { "code": null, "e": 25267, "s": 25076, "text": "Here selector is the selected element whose previous siblings get returned.Parameters: It does not accept any parameter.Return Value: It returns the previous sibling of the selected element." }, { "code": "<html> <head> <style> .pre * { display: block; border: 2px solid lightgrey; color: black; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"h3\").prev().css({ \"color\": \"black\", \"border\": \"2px solid green\" }); }); </script></head> <body class=\"pre\"> <div> This is parent element ! <p>This is first paragraph </p> <span>First span box </span> <h2>heading 2 !</h2> <h3>heading 3 !</h3> <p>This is the second paragraph and next sibling to h3 !</p> </div></body> </html>", "e": 26071, "s": 25267, "text": null }, { "code": null, "e": 26164, "s": 26071, "text": "In the above code, previous sibling element of “h3” get highlighted with green color.Output:" }, { "code": null, "e": 26174, "s": 26164, "text": "prevAll()" }, { "code": null, "e": 26309, "s": 26174, "text": "The prevAll() is an inbuilt method in jQuery which is used to return all the previous sibling elements of the selected element.Syntax:" }, { "code": null, "e": 26332, "s": 26309, "text": "$(selector).prevAll()\n" }, { "code": null, "e": 26536, "s": 26332, "text": "Here selector is the selected element whose previous siblings get returned.Parameters: It does not accept any parameter.Return Value: It returns all the previous sibling elements of the selected element." }, { "code": "<html> <head> <style> .preAll * { display: block; border: 2px solid lightgrey; color: black; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"h3\").prevAll().css({ \"color\": \"black\", \"border\": \"2px solid green\" }); }); </script></head> <body class=\"preAll\"> <div> This is parent element ! <p>This is first paragraph </p> <span>first span box </span> <h2>heading 2 !</h2> <h3>heading 3 !</h3> <p>This is the second paragraph and next sibling to h3 !</p> </div></body> </html>", "e": 27361, "s": 26536, "text": null }, { "code": null, "e": 27463, "s": 27361, "text": "In the above code, all the previous sibling elements of “h3” get highlighted with green color.Output:" }, { "code": null, "e": 27481, "s": 27463, "text": "jQuery-Traversing" }, { "code": null, "e": 27492, "s": 27481, "text": "JavaScript" }, { "code": null, "e": 27499, "s": 27492, "text": "JQuery" }, { "code": null, "e": 27597, "s": 27499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27642, "s": 27597, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27703, "s": 27642, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27775, "s": 27703, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27827, "s": 27775, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27873, "s": 27827, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27936, "s": 27873, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 27965, "s": 27936, "text": "Form validation using jQuery" }, { "code": null, "e": 28042, "s": 27965, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 28098, "s": 28042, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" } ]
An RFM Analysis with Python | Wenling Yao | Towards Data Science
It’s time to brush up on my Python skills! 👩🏻‍💻 This week I want to go techie and share a recent Python exercise using the RFM framework. It is a method used to determine customer value by looking at three dimensions: Recency: when is the last time the user takes an action (e.g., login, place an order)? Frequency: how many times does the user take this action? Monetary value: what is the sum of monetary value from this user throughout his/her lifetime? My work was heavily inspired by many helpful posts on the same dataset like this one. With this post, I want to share my RFM segmentation analysis and focus on some tips that I found useful in quickly bringing out the business value from the model output. Convert absolute recency, frequency, and monetary values into relative ones to reduce the bias associated with the actual customer lifetime. Generate simple, heuristic business logic to deliver business value in a quick manner. Join the segments with other datasets to gain more insights into your customer base. Before we dive into details, I want to give a quick look into how our dataset looks like and what problems we aim to resolve. Our raw data is a table of transaction records with the following fields: <class 'pandas.core.frame.DataFrame'>Int64Index: 406829 entries, 0 to 541908Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 InvoiceNo 406829 non-null object 1 StockCode 406829 non-null object 2 Description 406829 non-null object 3 Quantity 406829 non-null int64 4 InvoiceDate 406829 non-null object 5 UnitPrice 406829 non-null float64 6 CustomerID 406829 non-null float64 7 Country 406829 non-null object dtypes: float64(2), int64(1), object(5)memory usage: 27.9+ MB Usually, we would aggregate the data on the customer level. We want to apply the RFM framework to this aggregate dataset and answer the following questions: Is there a correlation between Recency, Frequency, and Monetary Value?How should we define our most valuable customers (MVC)? What percentage of our customers are the most valuable customers?Are we able to create distinguishing segments and design CRM campaigns accordingly to improve customer engagement and/or monetization? Is there a correlation between Recency, Frequency, and Monetary Value? How should we define our most valuable customers (MVC)? What percentage of our customers are the most valuable customers? Are we able to create distinguishing segments and design CRM campaigns accordingly to improve customer engagement and/or monetization? One thing I noticed in many tutorials is that absolute numbers are used for the calculation. In other words, we have the following: Recency = the interval between the last action and today Frequency = the number of actions between the user’s signup date and today Monetary value = the sum of revenue within the user’s lifetime After this step, one typical approach is to calculate the Recency/Frequency/Monetary Score by creating buckets based on the quartiles of each individual column. For example, on the column “Frequency” we do the following: customer_data["FrequencyScore"] = pd.cut(customer_data["Frequency"], bins=[-1, np.percentile(customer_data["Frequency"], 25), np.percentile(customer_data["Frequency"], 50), np.percentile(customer_data["Frequency"], 75), customer_data["Frequency"].max()], labels=[1, 2, 3, 4]).astype("int") Note that for Recency Score we need to give inverse labels as the more active the customer is the lower the value of Recency. :) Once we obtain the scores of each individual dimension, we calculate the overall RFM score by summing up the three scores. The higher the overall RFM score (in a range from 3 to 12), the more valuable the customer. customer_data["RFM"] = customer_data["RecencyScore"] + customer_data["FrequencyScore"] + customer_data["MonetaryScore"] This method is easy to implement, yet it is prone to bias associated with the actual customer lifetime. For example, compared to the customers who sign up in the last 6 months, those who signed up 12 months ago would by nature have lower recency (assuming generally decreasing user engagement over lifetime), higher frequency, and higher monetary value (assuming cohorts are homogenous in terms of user activity and monetization). Hence, the RFM score of customers who signed up 12 months may be overestimated. To account for this bias, I would first normalize Recency, Frequency, and Monetary Value before calculating individual scores. For example, I would do Relative Frequency = Recency / Lifetime. customer_data["RelFrequency"] = customer_data["Frequency"] / customer_data["Lifetime"] Then I would calculate the Frequency Score based on the Relative Frequency: customer_data["FrequencyScore"] = pd.cut(customer_data["RelFrequency"], bins=[-1, np.percentile(customer_data["RelFrequency"], 25), np.percentile(customer_data["RelFrequency"], 50), np.percentile(customer_data["RelFrequency"], 75), customer_data["RelFrequency"].max()], labels=[1, 2, 3, 4]).astype("int") In my notebook, you can find rfm_abs the RFM segmentation using absolute values and rfm_rel using relative values. Here I attach only the median customer lifetime of each RFM segment under these two approaches. As we can see, the segments from the RFM segmentation using absolute values have a larger variance in customer lifetime whereas those from the RFM segmentation using relative values have rather a constant customer lifetime. More specifically, with the 1st approach we see that those with an RFM score of 5 and 6 (thus at the low bound of activity) have a significantly shorter lifetime (and thus are more recent customers). This approach seems to “penalize” the more recent customers for their lower frequency and monetary amount. On the other hand, our approach manages to reduce the bias associated with customer lifetime in RFM segmentation! So far so good! Many tutorials end up here with generating RFM segmentation labels (3–12) with the following summary statistics: This table answers our first two questions: There is indeed a positive correlation across Recency, Frequency, and Monetary Value.Our MVCs are those with a total RFM score of 11 and 12, i.e., they on average had more than 7 transactions, generated more than 2K in their lifetime, and had their last transaction within the last 2 weeks. Such customers account for ~16% of our total customer base. There is indeed a positive correlation across Recency, Frequency, and Monetary Value. Our MVCs are those with a total RFM score of 11 and 12, i.e., they on average had more than 7 transactions, generated more than 2K in their lifetime, and had their last transaction within the last 2 weeks. Such customers account for ~16% of our total customer base. However, in real life, this output might not be sufficient for creating quick business value. On one hand, the buckets we get are not so different from each other and there is a chance we can merge some segments. On the other hand, the logic itself is rather complex — if we want to strictly follow the logic we need to deploy the notebook into production, which requires significant engineering effort with high uncertainty of generating substantial business value. We want to move fast. Therefore, I would like to generate some simple and heuristic logic based on the RFM segmentation results above and apply them to production for analytical and operational purposes. Note that there is no perfect logic — here I only share one set of criteria that I consider as the most differentiating. customer_data["last_order_within_l60d"] = customer_data["Recency"]<60 # Had transactions in the last 60 dayscustomer_data["more_than_two_orders"] = customer_data["Frequency"]>2 # Logged in more than twicecustomer_data["value_higher_than_2k"] = customer_data["MonetaryValue"]>2000 # Sum of value higher than 2Kcustomer_data.groupby(["last_order_within_l60d", "more_than_two_orders", "value_higher_than_2k"]).count()["Lifetime"] Based on the branching above, I define five final segments (in the brackets you can find the segment sizes): High Engagement & High Value (523) are those who had their last transactions in the last 2 months, made more than 2 transactions, and contributed more than 2K on average.High Engagement & Low Value (876) are those who are as active as Group1 but contributed less than 2K.Recent Activity & Low Frequency (811) are those who had their last transactions in the last 2 months but made no more than 2 transactions. These customers also have a lower monetary value. Apparently, most customers in this group are recently acquired customers (their average lifetime is only 45 days).“Old” Activity & High Frequency (523) are those who did not have any transactions in the last 2 months. However, on average they had more than 2 transactions. These customers were very active at the beginning of their journey but are not that active recently. We need to find ways to reengage them.Low Engagement & Low Value (1426) are those who did not have any transactions in the last 2 months, made no more than 2 transactions, and contributed the lowest revenue. High Engagement & High Value (523) are those who had their last transactions in the last 2 months, made more than 2 transactions, and contributed more than 2K on average. High Engagement & Low Value (876) are those who are as active as Group1 but contributed less than 2K. Recent Activity & Low Frequency (811) are those who had their last transactions in the last 2 months but made no more than 2 transactions. These customers also have a lower monetary value. Apparently, most customers in this group are recently acquired customers (their average lifetime is only 45 days). “Old” Activity & High Frequency (523) are those who did not have any transactions in the last 2 months. However, on average they had more than 2 transactions. These customers were very active at the beginning of their journey but are not that active recently. We need to find ways to reengage them. Low Engagement & Low Value (1426) are those who did not have any transactions in the last 2 months, made no more than 2 transactions, and contributed the lowest revenue. There are many use cases based on the learnings we generate above. Here I want to elaborate on two use cases I have used at work. One way is to attach this customer value score as a new dimension to BI datasets (user profiles, tracking events, purchase records, etc). Combined with existing metrics and dashboards, this can help you answer questions like: What are the socioeconomic (income, occupation, etc) and demographic traits (age, gender, marital status, etc) of our MVCs? This sheds light on how we can target and acquire more of such customers. Do our MVCs have a significantly different user journey compared with other groups? How can we optimize the journey experience for our MVC? Do our MVCs have a significant market basket compared with other groups? This may give us some inspiration for improving recommendations for them. The other use case is to send this label to a CRM tool and use it for customized engagement communication. Take the final segments I generate above as one example: for Group 2 High Engagement & Low Value and Group 3 Recent Activity & Low Frequency we should focus on monetization (e.g., number of orders, average order value) by personalized recommendation while for Group 4 “Old” Activity & High Frequency we should try to re-engage them and bring them back to our website/application. Combined with features from other datasets we are able to design targeted content and medium to reach individual customers and maximize conversions. That’s it. Let me know your thoughts & feedback!
[ { "code": null, "e": 220, "s": 172, "text": "It’s time to brush up on my Python skills! 👩🏻‍💻" }, { "code": null, "e": 390, "s": 220, "text": "This week I want to go techie and share a recent Python exercise using the RFM framework. It is a method used to determine customer value by looking at three dimensions:" }, { "code": null, "e": 477, "s": 390, "text": "Recency: when is the last time the user takes an action (e.g., login, place an order)?" }, { "code": null, "e": 535, "s": 477, "text": "Frequency: how many times does the user take this action?" }, { "code": null, "e": 629, "s": 535, "text": "Monetary value: what is the sum of monetary value from this user throughout his/her lifetime?" }, { "code": null, "e": 885, "s": 629, "text": "My work was heavily inspired by many helpful posts on the same dataset like this one. With this post, I want to share my RFM segmentation analysis and focus on some tips that I found useful in quickly bringing out the business value from the model output." }, { "code": null, "e": 1026, "s": 885, "text": "Convert absolute recency, frequency, and monetary values into relative ones to reduce the bias associated with the actual customer lifetime." }, { "code": null, "e": 1113, "s": 1026, "text": "Generate simple, heuristic business logic to deliver business value in a quick manner." }, { "code": null, "e": 1198, "s": 1113, "text": "Join the segments with other datasets to gain more insights into your customer base." }, { "code": null, "e": 1324, "s": 1198, "text": "Before we dive into details, I want to give a quick look into how our dataset looks like and what problems we aim to resolve." }, { "code": null, "e": 1398, "s": 1324, "text": "Our raw data is a table of transaction records with the following fields:" }, { "code": null, "e": 1987, "s": 1398, "text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 406829 entries, 0 to 541908Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 InvoiceNo 406829 non-null object 1 StockCode 406829 non-null object 2 Description 406829 non-null object 3 Quantity 406829 non-null int64 4 InvoiceDate 406829 non-null object 5 UnitPrice 406829 non-null float64 6 CustomerID 406829 non-null float64 7 Country 406829 non-null object dtypes: float64(2), int64(1), object(5)memory usage: 27.9+ MB" }, { "code": null, "e": 2047, "s": 1987, "text": "Usually, we would aggregate the data on the customer level." }, { "code": null, "e": 2144, "s": 2047, "text": "We want to apply the RFM framework to this aggregate dataset and answer the following questions:" }, { "code": null, "e": 2470, "s": 2144, "text": "Is there a correlation between Recency, Frequency, and Monetary Value?How should we define our most valuable customers (MVC)? What percentage of our customers are the most valuable customers?Are we able to create distinguishing segments and design CRM campaigns accordingly to improve customer engagement and/or monetization?" }, { "code": null, "e": 2541, "s": 2470, "text": "Is there a correlation between Recency, Frequency, and Monetary Value?" }, { "code": null, "e": 2663, "s": 2541, "text": "How should we define our most valuable customers (MVC)? What percentage of our customers are the most valuable customers?" }, { "code": null, "e": 2798, "s": 2663, "text": "Are we able to create distinguishing segments and design CRM campaigns accordingly to improve customer engagement and/or monetization?" }, { "code": null, "e": 2930, "s": 2798, "text": "One thing I noticed in many tutorials is that absolute numbers are used for the calculation. In other words, we have the following:" }, { "code": null, "e": 2987, "s": 2930, "text": "Recency = the interval between the last action and today" }, { "code": null, "e": 3062, "s": 2987, "text": "Frequency = the number of actions between the user’s signup date and today" }, { "code": null, "e": 3125, "s": 3062, "text": "Monetary value = the sum of revenue within the user’s lifetime" }, { "code": null, "e": 3346, "s": 3125, "text": "After this step, one typical approach is to calculate the Recency/Frequency/Monetary Score by creating buckets based on the quartiles of each individual column. For example, on the column “Frequency” we do the following:" }, { "code": null, "e": 3890, "s": 3346, "text": "customer_data[\"FrequencyScore\"] = pd.cut(customer_data[\"Frequency\"], bins=[-1, np.percentile(customer_data[\"Frequency\"], 25), np.percentile(customer_data[\"Frequency\"], 50), np.percentile(customer_data[\"Frequency\"], 75), customer_data[\"Frequency\"].max()], labels=[1, 2, 3, 4]).astype(\"int\")" }, { "code": null, "e": 4019, "s": 3890, "text": "Note that for Recency Score we need to give inverse labels as the more active the customer is the lower the value of Recency. :)" }, { "code": null, "e": 4234, "s": 4019, "text": "Once we obtain the scores of each individual dimension, we calculate the overall RFM score by summing up the three scores. The higher the overall RFM score (in a range from 3 to 12), the more valuable the customer." }, { "code": null, "e": 4354, "s": 4234, "text": "customer_data[\"RFM\"] = customer_data[\"RecencyScore\"] + customer_data[\"FrequencyScore\"] + customer_data[\"MonetaryScore\"]" }, { "code": null, "e": 4865, "s": 4354, "text": "This method is easy to implement, yet it is prone to bias associated with the actual customer lifetime. For example, compared to the customers who sign up in the last 6 months, those who signed up 12 months ago would by nature have lower recency (assuming generally decreasing user engagement over lifetime), higher frequency, and higher monetary value (assuming cohorts are homogenous in terms of user activity and monetization). Hence, the RFM score of customers who signed up 12 months may be overestimated." }, { "code": null, "e": 5057, "s": 4865, "text": "To account for this bias, I would first normalize Recency, Frequency, and Monetary Value before calculating individual scores. For example, I would do Relative Frequency = Recency / Lifetime." }, { "code": null, "e": 5144, "s": 5057, "text": "customer_data[\"RelFrequency\"] = customer_data[\"Frequency\"] / customer_data[\"Lifetime\"]" }, { "code": null, "e": 5220, "s": 5144, "text": "Then I would calculate the Frequency Score based on the Relative Frequency:" }, { "code": null, "e": 5783, "s": 5220, "text": "customer_data[\"FrequencyScore\"] = pd.cut(customer_data[\"RelFrequency\"], bins=[-1, np.percentile(customer_data[\"RelFrequency\"], 25), np.percentile(customer_data[\"RelFrequency\"], 50), np.percentile(customer_data[\"RelFrequency\"], 75), customer_data[\"RelFrequency\"].max()], labels=[1, 2, 3, 4]).astype(\"int\")" }, { "code": null, "e": 6525, "s": 5783, "text": "In my notebook, you can find rfm_abs the RFM segmentation using absolute values and rfm_rel using relative values. Here I attach only the median customer lifetime of each RFM segment under these two approaches. As we can see, the segments from the RFM segmentation using absolute values have a larger variance in customer lifetime whereas those from the RFM segmentation using relative values have rather a constant customer lifetime. More specifically, with the 1st approach we see that those with an RFM score of 5 and 6 (thus at the low bound of activity) have a significantly shorter lifetime (and thus are more recent customers). This approach seems to “penalize” the more recent customers for their lower frequency and monetary amount." }, { "code": null, "e": 6639, "s": 6525, "text": "On the other hand, our approach manages to reduce the bias associated with customer lifetime in RFM segmentation!" }, { "code": null, "e": 6655, "s": 6639, "text": "So far so good!" }, { "code": null, "e": 6768, "s": 6655, "text": "Many tutorials end up here with generating RFM segmentation labels (3–12) with the following summary statistics:" }, { "code": null, "e": 6812, "s": 6768, "text": "This table answers our first two questions:" }, { "code": null, "e": 7163, "s": 6812, "text": "There is indeed a positive correlation across Recency, Frequency, and Monetary Value.Our MVCs are those with a total RFM score of 11 and 12, i.e., they on average had more than 7 transactions, generated more than 2K in their lifetime, and had their last transaction within the last 2 weeks. Such customers account for ~16% of our total customer base." }, { "code": null, "e": 7249, "s": 7163, "text": "There is indeed a positive correlation across Recency, Frequency, and Monetary Value." }, { "code": null, "e": 7515, "s": 7249, "text": "Our MVCs are those with a total RFM score of 11 and 12, i.e., they on average had more than 7 transactions, generated more than 2K in their lifetime, and had their last transaction within the last 2 weeks. Such customers account for ~16% of our total customer base." }, { "code": null, "e": 7982, "s": 7515, "text": "However, in real life, this output might not be sufficient for creating quick business value. On one hand, the buckets we get are not so different from each other and there is a chance we can merge some segments. On the other hand, the logic itself is rather complex — if we want to strictly follow the logic we need to deploy the notebook into production, which requires significant engineering effort with high uncertainty of generating substantial business value." }, { "code": null, "e": 8307, "s": 7982, "text": "We want to move fast. Therefore, I would like to generate some simple and heuristic logic based on the RFM segmentation results above and apply them to production for analytical and operational purposes. Note that there is no perfect logic — here I only share one set of criteria that I consider as the most differentiating." }, { "code": null, "e": 8734, "s": 8307, "text": "customer_data[\"last_order_within_l60d\"] = customer_data[\"Recency\"]<60 # Had transactions in the last 60 dayscustomer_data[\"more_than_two_orders\"] = customer_data[\"Frequency\"]>2 # Logged in more than twicecustomer_data[\"value_higher_than_2k\"] = customer_data[\"MonetaryValue\"]>2000 # Sum of value higher than 2Kcustomer_data.groupby([\"last_order_within_l60d\", \"more_than_two_orders\", \"value_higher_than_2k\"]).count()[\"Lifetime\"]" }, { "code": null, "e": 8843, "s": 8734, "text": "Based on the branching above, I define five final segments (in the brackets you can find the segment sizes):" }, { "code": null, "e": 9885, "s": 8843, "text": "High Engagement & High Value (523) are those who had their last transactions in the last 2 months, made more than 2 transactions, and contributed more than 2K on average.High Engagement & Low Value (876) are those who are as active as Group1 but contributed less than 2K.Recent Activity & Low Frequency (811) are those who had their last transactions in the last 2 months but made no more than 2 transactions. These customers also have a lower monetary value. Apparently, most customers in this group are recently acquired customers (their average lifetime is only 45 days).“Old” Activity & High Frequency (523) are those who did not have any transactions in the last 2 months. However, on average they had more than 2 transactions. These customers were very active at the beginning of their journey but are not that active recently. We need to find ways to reengage them.Low Engagement & Low Value (1426) are those who did not have any transactions in the last 2 months, made no more than 2 transactions, and contributed the lowest revenue." }, { "code": null, "e": 10056, "s": 9885, "text": "High Engagement & High Value (523) are those who had their last transactions in the last 2 months, made more than 2 transactions, and contributed more than 2K on average." }, { "code": null, "e": 10158, "s": 10056, "text": "High Engagement & Low Value (876) are those who are as active as Group1 but contributed less than 2K." }, { "code": null, "e": 10462, "s": 10158, "text": "Recent Activity & Low Frequency (811) are those who had their last transactions in the last 2 months but made no more than 2 transactions. These customers also have a lower monetary value. Apparently, most customers in this group are recently acquired customers (their average lifetime is only 45 days)." }, { "code": null, "e": 10761, "s": 10462, "text": "“Old” Activity & High Frequency (523) are those who did not have any transactions in the last 2 months. However, on average they had more than 2 transactions. These customers were very active at the beginning of their journey but are not that active recently. We need to find ways to reengage them." }, { "code": null, "e": 10931, "s": 10761, "text": "Low Engagement & Low Value (1426) are those who did not have any transactions in the last 2 months, made no more than 2 transactions, and contributed the lowest revenue." }, { "code": null, "e": 11061, "s": 10931, "text": "There are many use cases based on the learnings we generate above. Here I want to elaborate on two use cases I have used at work." }, { "code": null, "e": 11287, "s": 11061, "text": "One way is to attach this customer value score as a new dimension to BI datasets (user profiles, tracking events, purchase records, etc). Combined with existing metrics and dashboards, this can help you answer questions like:" }, { "code": null, "e": 11485, "s": 11287, "text": "What are the socioeconomic (income, occupation, etc) and demographic traits (age, gender, marital status, etc) of our MVCs? This sheds light on how we can target and acquire more of such customers." }, { "code": null, "e": 11625, "s": 11485, "text": "Do our MVCs have a significantly different user journey compared with other groups? How can we optimize the journey experience for our MVC?" }, { "code": null, "e": 11772, "s": 11625, "text": "Do our MVCs have a significant market basket compared with other groups? This may give us some inspiration for improving recommendations for them." }, { "code": null, "e": 12408, "s": 11772, "text": "The other use case is to send this label to a CRM tool and use it for customized engagement communication. Take the final segments I generate above as one example: for Group 2 High Engagement & Low Value and Group 3 Recent Activity & Low Frequency we should focus on monetization (e.g., number of orders, average order value) by personalized recommendation while for Group 4 “Old” Activity & High Frequency we should try to re-engage them and bring them back to our website/application. Combined with features from other datasets we are able to design targeted content and medium to reach individual customers and maximize conversions." } ]
Calculate range of data types using C++ - GeeksforGeeks
12 Jan, 2018 C++ program for printing the range data type like int, char, short. Signed Data Types METHOD 1.) calculate total number of bits by multiplying sizeof with 8 (say n) 2.) Calculate -2^(n-1) for minimum range 3.) Calculate (2^(n-1))-1 for maximum range // CPP program to calculate // range of signed data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std; // function to calculate range of//unsigned data typevoid printSignedRange(int count){ int min = pow(2, count - 1); int max = pow(2, count - 1) - 1; printf("%d to %d", min * (-1), max);} // DRIVER programint main(){ cout << "signed char: "; printSignedRange(SIZE(char)); cout << "\nsigned int: "; printSignedRange(SIZE(int)); cout << "\nsigned short int: "; printSignedRange(SIZE(short int)); return 0;} Output: signed char: -128 to 127 signed int: -2147483648 to 2147483647 signed short int: -32768 to 32767 Unsigned Data Types METHOD 1.)Find number of bits by multiplying result of sizeof with 8 say n 2.)minimum range is always zero for unsigned data type 3.)for maximum range calculate 2^n-1 // CPP program to calculate range // of given unsigned data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std; // function to calculate range // of given unsigned data typevoid UnsignedRange(int count){ // calculate 2^number of bits unsigned int max = pow(2, count) - 1; cout << "0 to " << max;} // DRIVER programint main(){ cout << "unsigned char: "; UnsignedRange(SIZE(unsigned char)); cout << "\nunsigned int: "; UnsignedRange(SIZE(unsigned int)); cout << "\nunsigned short int: "; UnsignedRange(SIZE(unsigned short)); return 0;} Output: unsigned char: 0 to 255 unsigned int: 0 to 4294967295 unsigned short int: 0 to 65535 cpp-data-types cpp-puzzle C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25479, "s": 25451, "text": "\n12 Jan, 2018" }, { "code": null, "e": 25547, "s": 25479, "text": "C++ program for printing the range data type like int, char, short." }, { "code": null, "e": 25565, "s": 25547, "text": "Signed Data Types" }, { "code": null, "e": 25732, "s": 25565, "text": "METHOD\n1.) calculate total number of bits by multiplying sizeof with 8 (say n)\n2.) Calculate -2^(n-1) for minimum range\n3.) Calculate (2^(n-1))-1 for maximum range\n" }, { "code": "// CPP program to calculate // range of signed data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std; // function to calculate range of//unsigned data typevoid printSignedRange(int count){ int min = pow(2, count - 1); int max = pow(2, count - 1) - 1; printf(\"%d to %d\", min * (-1), max);} // DRIVER programint main(){ cout << \"signed char: \"; printSignedRange(SIZE(char)); cout << \"\\nsigned int: \"; printSignedRange(SIZE(int)); cout << \"\\nsigned short int: \"; printSignedRange(SIZE(short int)); return 0;}", "e": 26300, "s": 25732, "text": null }, { "code": null, "e": 26308, "s": 26300, "text": "Output:" }, { "code": null, "e": 26406, "s": 26308, "text": "signed char: -128 to 127\nsigned int: -2147483648 to 2147483647\nsigned short int: -32768 to 32767\n" }, { "code": null, "e": 26426, "s": 26406, "text": "Unsigned Data Types" }, { "code": null, "e": 26594, "s": 26426, "text": "METHOD\n1.)Find number of bits by multiplying result of sizeof with 8 say n\n2.)minimum range is always zero for unsigned data type\n3.)for maximum range calculate 2^n-1\n" }, { "code": "// CPP program to calculate range // of given unsigned data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std; // function to calculate range // of given unsigned data typevoid UnsignedRange(int count){ // calculate 2^number of bits unsigned int max = pow(2, count) - 1; cout << \"0 to \" << max;} // DRIVER programint main(){ cout << \"unsigned char: \"; UnsignedRange(SIZE(unsigned char)); cout << \"\\nunsigned int: \"; UnsignedRange(SIZE(unsigned int)); cout << \"\\nunsigned short int: \"; UnsignedRange(SIZE(unsigned short)); return 0;}", "e": 27189, "s": 26594, "text": null }, { "code": null, "e": 27197, "s": 27189, "text": "Output:" }, { "code": null, "e": 27283, "s": 27197, "text": "unsigned char: 0 to 255\nunsigned int: 0 to 4294967295\nunsigned short int: 0 to 65535\n" }, { "code": null, "e": 27298, "s": 27283, "text": "cpp-data-types" }, { "code": null, "e": 27309, "s": 27298, "text": "cpp-puzzle" }, { "code": null, "e": 27313, "s": 27309, "text": "C++" }, { "code": null, "e": 27326, "s": 27313, "text": "C++ Programs" }, { "code": null, "e": 27330, "s": 27326, "text": "CPP" }, { "code": null, "e": 27428, "s": 27330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27456, "s": 27428, "text": "Operator Overloading in C++" }, { "code": null, "e": 27476, "s": 27456, "text": "Polymorphism in C++" }, { "code": null, "e": 27509, "s": 27476, "text": "Friend class and function in C++" }, { "code": null, "e": 27533, "s": 27509, "text": "Sorting a vector in C++" }, { "code": null, "e": 27558, "s": 27533, "text": "std::string class in C++" }, { "code": null, "e": 27593, "s": 27558, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27637, "s": 27593, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27663, "s": 27637, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27722, "s": 27663, "text": "How to return multiple values from a function in C or C++?" } ]
How to create a draggable HTML element with JavaScript and CSS?
To create a draggable HTML element with JavaScript and CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .dragDiv { position: absolute; z-index: 9; text-align: center; border: 1px solid #d3d3d3; padding: 30px; cursor: move; z-index: 10; background-color: rgb(108, 24, 177); color: #fff; font-size: 20px; font-weight: 500; } </style> <body> <h1>Draggable DIV Element Example</h1> <h2>Click and drag the below element to move it around</h2> <div class="dragDiv"> This div can be moved around </div> <script> dragElement(document.querySelector(".dragDiv")); function dragElement(ele) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.querySelector(ele.id + "header")) { document.getElementById( ele.id + "header" ).onmousedown = dragMouseDown; } else { ele.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; e.preventDefault(); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; ele.style.top = ele.offsetTop - pos2 + "px"; ele.style.left = ele.offsetLeft - pos1 + "px"; } function closeDragElement() { document.onmouseup = null; document.onmousemove = null; } } </script> </body> </html> The above code will produce the following output − On moving the div around by dragging −
[ { "code": null, "e": 1147, "s": 1062, "text": "To create a draggable HTML element with JavaScript and CSS, the code is as follows −" }, { "code": null, "e": 1158, "s": 1147, "text": " Live Demo" }, { "code": null, "e": 2858, "s": 1158, "text": "<!DOCTYPE html>\n<html>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .dragDiv {\n position: absolute;\n z-index: 9;\n text-align: center;\n border: 1px solid #d3d3d3;\n padding: 30px;\n cursor: move;\n z-index: 10;\n background-color: rgb(108, 24, 177);\n color: #fff;\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n<body>\n<h1>Draggable DIV Element Example</h1>\n<h2>Click and drag the below element to move it around</h2>\n<div class=\"dragDiv\">\nThis div can be moved around\n</div>\n<script>\n dragElement(document.querySelector(\".dragDiv\"));\n function dragElement(ele) {\n var pos1 = 0,\n pos2 = 0,\n pos3 = 0,\n pos4 = 0;\n if (document.querySelector(ele.id + \"header\")) {\n document.getElementById(\n ele.id + \"header\"\n ).onmousedown = dragMouseDown;\n }\n else {\n ele.onmousedown = dragMouseDown;\n }\n function dragMouseDown(e) {\n e = e || window.event;\n e.preventDefault();\n pos3 = e.clientX;\n pos4 = e.clientY;\n document.onmouseup = closeDragElement;\n document.onmousemove = elementDrag;\n }\n function elementDrag(e) {\n e = e || window.event;\n e.preventDefault();\n pos1 = pos3 - e.clientX;\n pos2 = pos4 - e.clientY;\n pos3 = e.clientX;\n pos4 = e.clientY;\n ele.style.top = ele.offsetTop - pos2 + \"px\";\n ele.style.left = ele.offsetLeft - pos1 + \"px\";\n }\n function closeDragElement() {\n document.onmouseup = null;\n document.onmousemove = null;\n }\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2909, "s": 2858, "text": "The above code will produce the following output −" }, { "code": null, "e": 2948, "s": 2909, "text": "On moving the div around by dragging −" } ]
How to include Functions from other files in Node.js ? - GeeksforGeeks
29 Jun, 2020 Code reusability is an important pillar in modern day programming. Code Reuse means the practice of using an existing code for a new function or software. In this article, we would learn how to use functions from other files in Node.js. This functionality can be easily implemented using the inbuilt export and require functions of Node.js. Export: The module.exports in Node.js is used to export any literal, function or object as a module. It is used to include JavaScript file into Node.js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module. Require() function: It is an inbuilt function and is the easiest way to include functions that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object. Let us consider the following basic example: Filename: cal.js function sum(x, y) { return (x + y);} function sub(x, y) { return (x - y);} function mul(x, y) { return (x * y);} module.exports = { add, sub, mul, div }; In the above example, we use the module.exports function so that we can use it in other files. The functions are enclosed within curly brackets( { } ) according to the format to export multiple functions at a time. Suppose we wanted to use these functions in main.js, then it can be easily done using the following code: Filename: main.js //requiring cal.js fileconst cal = require("./cal.js") //Using the functions from cal.js const sum = cal.sum(2, 2);console.log(sum); const sub = cal.sub(10, 5);console.log(sub); const product = cal.mul(2, 3);console.log(product); This will import the cal.js file and its functions into the main.js file. Run main.js file using the following command: node main.js Output: 4 5 6 Node.js-Misc Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Mongoose find() Function How to connect Node.js with React.js ? Mongoose Populate() Method Node.js Export Module Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26401, "s": 26373, "text": "\n29 Jun, 2020" }, { "code": null, "e": 26639, "s": 26401, "text": "Code reusability is an important pillar in modern day programming. Code Reuse means the practice of using an existing code for a new function or software. In this article, we would learn how to use functions from other files in Node.js. " }, { "code": null, "e": 26743, "s": 26639, "text": "This functionality can be easily implemented using the inbuilt export and require functions of Node.js." }, { "code": null, "e": 27042, "s": 26743, "text": "Export: The module.exports in Node.js is used to export any literal, function or object as a module. It is used to include JavaScript file into Node.js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module." }, { "code": null, "e": 27299, "s": 27042, "text": "Require() function: It is an inbuilt function and is the easiest way to include functions that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object." }, { "code": null, "e": 27344, "s": 27299, "text": "Let us consider the following basic example:" }, { "code": null, "e": 27361, "s": 27344, "text": "Filename: cal.js" }, { "code": "function sum(x, y) { return (x + y);} function sub(x, y) { return (x - y);} function mul(x, y) { return (x * y);} module.exports = { add, sub, mul, div };", "e": 27528, "s": 27361, "text": null }, { "code": null, "e": 27743, "s": 27528, "text": "In the above example, we use the module.exports function so that we can use it in other files. The functions are enclosed within curly brackets( { } ) according to the format to export multiple functions at a time." }, { "code": null, "e": 27849, "s": 27743, "text": "Suppose we wanted to use these functions in main.js, then it can be easily done using the following code:" }, { "code": null, "e": 27867, "s": 27849, "text": "Filename: main.js" }, { "code": "//requiring cal.js fileconst cal = require(\"./cal.js\") //Using the functions from cal.js const sum = cal.sum(2, 2);console.log(sum); const sub = cal.sub(10, 5);console.log(sub); const product = cal.mul(2, 3);console.log(product);", "e": 28104, "s": 27867, "text": null }, { "code": null, "e": 28178, "s": 28104, "text": "This will import the cal.js file and its functions into the main.js file." }, { "code": null, "e": 28224, "s": 28178, "text": "Run main.js file using the following command:" }, { "code": null, "e": 28237, "s": 28224, "text": "node main.js" }, { "code": null, "e": 28245, "s": 28237, "text": "Output:" }, { "code": null, "e": 28252, "s": 28245, "text": "4\n5\n6\n" }, { "code": null, "e": 28265, "s": 28252, "text": "Node.js-Misc" }, { "code": null, "e": 28273, "s": 28265, "text": "Node.js" }, { "code": null, "e": 28290, "s": 28273, "text": "Web Technologies" }, { "code": null, "e": 28317, "s": 28290, "text": "Web technologies Questions" }, { "code": null, "e": 28415, "s": 28317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28485, "s": 28415, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28510, "s": 28485, "text": "Mongoose find() Function" }, { "code": null, "e": 28549, "s": 28510, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28576, "s": 28549, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28598, "s": 28576, "text": "Node.js Export Module" }, { "code": null, "e": 28638, "s": 28598, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28683, "s": 28638, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28726, "s": 28683, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28776, "s": 28726, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
ES6 - Object Extensions
Some popular methods added to the String object in ES6 are − determines whether a string begins with the characters of a specified string. Returns true or false determines whether a string ends with the characters of a specified string. Returns true/false determines whether one string may be found within another string constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together In a regular expression, for example, /[A-Z]/g, the beginning and ending / are called delimiters. Anything after the closing delimiter is called a modifier. ES6 adds a new modifier /g where g stands for global. This match all instances of the pattern in a string, not just one. The following example searches and returns all upper-case characters in the string. <script> let str = 'JJavascript is Fun to Work , very Fun ' let regex = /[A-Z]/g // g stands for global matches let result = str.match(regex); console.log(result) </script> The output of the above code will be as given below − ["J", "J", "F", "W", "F"] Regular expression searches are case-sensitive. To turn-off case-sensitivity, use the /i modifier. The following example performs a case insensitive global match. The example replaces fun with enjoyable. <script> // /gi global match ignore case let str = 'Javascript is fun to Work , very Fun ' let regex = /Fun/gi; console.log(str.replace(regex,'enjoyable')); console.log(str) console.log(str.search(regex)) </script> The output of the above code will be as shown below − Javascript is enjoyable to Work , very enjoyable Javascript is fun to Work , very Fun 15 Some popular methods added to the Number object in ES6 are − method determines whether the passed value is a finite number. Returns true/false. returns true if the given value is NaN and its type is Number; otherwise, false. A floating-point number parsed from the given value. If the value cannot be converted to a number, NaN is returned. method parses a string argument and returns an integer of the specified radix or base. Some popular methods added to the Math object in ES6 are − function returns the sign of a number, indicating whether the number is positive, negative or zero. function returns the integer part of a number by removing any fractional digits. The table given below highlights the different array methods in ES6 along with the description. shallow copies part of an array to another location in the same array and returns it without modifying its length. method returns a new Array Iterator object that contains the key/value pairs for each index in the array. method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.. method fills all the elements of an array from a start index to an end index with a static value. It returns the modified array. method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments. method creates a shallow copy from an array like or iterable object. Methods related to Object function are mentioned below in the table along with the respective description. method determines whether two values are the same value method sets the prototype of a specified object to another object or null. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2338, "s": 2277, "text": "Some popular methods added to the String object in ES6 are −" }, { "code": null, "e": 2438, "s": 2338, "text": "determines whether a string begins with the characters of a specified string. Returns true or false" }, { "code": null, "e": 2533, "s": 2438, "text": "determines whether a string ends with the characters of a specified string. Returns true/false" }, { "code": null, "e": 2598, "s": 2533, "text": "determines whether one string may be found within another string" }, { "code": null, "e": 2740, "s": 2598, "text": "constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together" }, { "code": null, "e": 3018, "s": 2740, "text": "In a regular expression, for example, /[A-Z]/g, the beginning and ending / are called delimiters. Anything after the closing delimiter is called a modifier. ES6 adds a new modifier /g where g stands for global. This match all instances of the pattern in a string, not just one." }, { "code": null, "e": 3102, "s": 3018, "text": "The following example searches and returns all upper-case characters in the string." }, { "code": null, "e": 3287, "s": 3102, "text": "<script>\n let str = 'JJavascript is Fun to Work , very Fun '\n let regex = /[A-Z]/g // g stands for global matches\n let result = str.match(regex);\n console.log(result)\n</script>" }, { "code": null, "e": 3341, "s": 3287, "text": "The output of the above code will be as given below −" }, { "code": null, "e": 3368, "s": 3341, "text": "[\"J\", \"J\", \"F\", \"W\", \"F\"]\n" }, { "code": null, "e": 3467, "s": 3368, "text": "Regular expression searches are case-sensitive. To turn-off case-sensitivity, use the /i modifier." }, { "code": null, "e": 3572, "s": 3467, "text": "The following example performs a case insensitive global match. The example replaces fun with enjoyable." }, { "code": null, "e": 3806, "s": 3572, "text": "<script>\n // /gi global match ignore case\n\n let str = 'Javascript is fun to Work , very Fun '\n let regex = /Fun/gi;\n console.log(str.replace(regex,'enjoyable'));\n console.log(str)\n console.log(str.search(regex))\n</script>" }, { "code": null, "e": 3860, "s": 3806, "text": "The output of the above code will be as shown below −" }, { "code": null, "e": 3950, "s": 3860, "text": "Javascript is enjoyable to Work , very enjoyable\nJavascript is fun to Work , very Fun\n15\n" }, { "code": null, "e": 4011, "s": 3950, "text": "Some popular methods added to the Number object in ES6 are −" }, { "code": null, "e": 4094, "s": 4011, "text": "method determines whether the passed value is a finite number. Returns true/false." }, { "code": null, "e": 4175, "s": 4094, "text": "returns true if the given value is NaN and its type is Number; otherwise, false." }, { "code": null, "e": 4291, "s": 4175, "text": "A floating-point number parsed from the given value. If the value cannot be converted to a number, NaN is returned." }, { "code": null, "e": 4378, "s": 4291, "text": "method parses a string argument and returns an integer of the specified radix or base." }, { "code": null, "e": 4437, "s": 4378, "text": "Some popular methods added to the Math object in ES6 are −" }, { "code": null, "e": 4537, "s": 4437, "text": "function returns the sign of a number, indicating whether the number is positive, negative or zero." }, { "code": null, "e": 4618, "s": 4537, "text": "function returns the integer part of a number by removing any fractional digits." }, { "code": null, "e": 4714, "s": 4618, "text": "The table given below highlights the different array methods in ES6 along with the description." }, { "code": null, "e": 4829, "s": 4714, "text": "shallow copies part of an array to another location in the same array and returns it without modifying its length." }, { "code": null, "e": 4935, "s": 4829, "text": "method returns a new Array Iterator object that contains the key/value pairs for each index in the array." }, { "code": null, "e": 5074, "s": 4935, "text": "method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.." }, { "code": null, "e": 5203, "s": 5074, "text": "method fills all the elements of an array from a start index to an end index with a static value. It returns the modified array." }, { "code": null, "e": 5323, "s": 5203, "text": "method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments." }, { "code": null, "e": 5392, "s": 5323, "text": "method creates a shallow copy from an array like or iterable object." }, { "code": null, "e": 5499, "s": 5392, "text": "Methods related to Object function are mentioned below in the table along with the respective description." }, { "code": null, "e": 5555, "s": 5499, "text": "method determines whether two values are the same value" }, { "code": null, "e": 5630, "s": 5555, "text": "method sets the prototype of a specified object to another object or null." }, { "code": null, "e": 5783, "s": 5630, "text": "method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object." }, { "code": null, "e": 5818, "s": 5783, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5832, "s": 5818, "text": " Sharad Kumar" }, { "code": null, "e": 5865, "s": 5832, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 5883, "s": 5865, "text": " Richa Maheshwari" }, { "code": null, "e": 5916, "s": 5883, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5930, "s": 5916, "text": " Anadi Sharma" }, { "code": null, "e": 5965, "s": 5930, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5982, "s": 5965, "text": " Gowthami Swarna" }, { "code": null, "e": 6015, "s": 5982, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6031, "s": 6015, "text": " Deepti Trivedi" }, { "code": null, "e": 6066, "s": 6031, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6074, "s": 6066, "text": " Shweta" }, { "code": null, "e": 6081, "s": 6074, "text": " Print" }, { "code": null, "e": 6092, "s": 6081, "text": " Add Notes" } ]
Set heights and widths of forms with Bootstrap
Use classes like .input-lg and .col-lg-* to set the height and width of forms. You can try to run the following code to set the form height and width − 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> <form role = "form"> <div class = "form-group"> <input class = "form-control input-lg" type = "text" placeholder =".input-lg"> </div> <div class = "form-group"> <input class = "form-control" type = "text" placeholder = "Default input"> </div> <div class = "form-group"> <input class = "form-control input-sm" type = "text" placeholder = ".input-sm"> </div> <div class = "form-group"></div> <div class = "form-group"> <select class = "form-control input-lg"> <option value = "">.input-lg</option> </select> </div> <div class = "form-group"> <select class = "form-control"> <option value = "">Default select</option> </select> </div> <div class = "form-group"> <select class = "form-control input-sm"> <option value = "">.input-sm</option> </select> </div> <div class = "row"> <div class = "col-lg-2"> <input type = "text" class = "form-control" placeholder = ".col-lg-2"> </div> <div class = "col-lg-3"> <input type = "text" class = "form-control" placeholder = ".col-lg-3"> </div> <div class = "col-lg-4"> <input type = "text" class = "form-control" placeholder = ".col-lg-4"> </div> </div> </form> </body> </html>
[ { "code": null, "e": 1141, "s": 1062, "text": "Use classes like .input-lg and .col-lg-* to set the height and width of forms." }, { "code": null, "e": 1214, "s": 1141, "text": "You can try to run the following code to set the form height and width −" }, { "code": null, "e": 1224, "s": 1214, "text": "Live Demo" }, { "code": null, "e": 3044, "s": 1224, "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 <form role = \"form\">\n <div class = \"form-group\">\n <input class = \"form-control input-lg\" type = \"text\" placeholder =\".input-lg\">\n </div>\n <div class = \"form-group\">\n <input class = \"form-control\" type = \"text\" placeholder = \"Default input\">\n </div>\n <div class = \"form-group\">\n <input class = \"form-control input-sm\" type = \"text\" placeholder = \".input-sm\">\n </div>\n <div class = \"form-group\"></div>\n <div class = \"form-group\">\n <select class = \"form-control input-lg\">\n <option value = \"\">.input-lg</option>\n </select>\n </div>\n <div class = \"form-group\">\n <select class = \"form-control\">\n <option value = \"\">Default select</option>\n </select>\n </div>\n <div class = \"form-group\">\n <select class = \"form-control input-sm\">\n <option value = \"\">.input-sm</option>\n </select>\n </div>\n <div class = \"row\">\n <div class = \"col-lg-2\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-2\">\n </div>\n <div class = \"col-lg-3\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-3\">\n </div>\n <div class = \"col-lg-4\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-4\">\n </div>\n </div>\n </form>\n </body>\n</html>" } ]
Integer reverseBytes() Method in Java - GeeksforGeeks
07 Jul, 2018 The java.lang.Integer.reverseBytes(int a) is a built-in method which returns the value obtained by reversing the order of the bytes in the two’s complement representation of the specified int value. Syntax : public static int reverseBytes(int a) Parameter: The method takes one parameter a of integer type whose bytes are to be reversed. Return Value: The method will return the value obtained by reversing the bytes in the specified int value. Examples: Input: 75 Output: 1258291200 Explanation: Consider an integer a = 75 Binary Representation = 1001011 Number of one bit = 4 After reversing the bytes we get = 1258291200 Input: -43 Output: -704643073 Below programs illustrate the java.lang.Integer.reverseBytes() method:Program 1: For a positive number. // Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 61; System.out.println(" Integral Number = " + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println("After reversing the bytes we get = " + Integer.reverseBytes(a)); }} Integral Number = 61 After reversing the bytes we get = 1023410176 Program 2: For a negative number. // Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = -43; System.out.println(" Integral Number = " + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println("After reversing the bytes we get = " + Integer.reverseBytes(a)); }} Integral Number = -43 After reversing the bytes we get = -704643073 Program 3: For a decimal value and string.Note: It returns an error message when a decimal value and string is passed as an argument. // Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 37.81; System.out.println(" Integral Number = " + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println("After reversing the bytes we get = " + Integer.reverseBytes(a)); a = "81"; // compile time error will be generated System.out.println(" Integral Number = " + a); System.out.println("After reversing the bytes we get = " + Integer.reverseBytes(a)); }} prog.java:9: error: incompatible types: possible lossy conversion from double to int int a = 37.81; ^ prog.java:18: error: incompatible types: String cannot be converted to int a = "81"; ^ 2 errors Java-Functions Java-Integer Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 24456, "s": 24428, "text": "\n07 Jul, 2018" }, { "code": null, "e": 24655, "s": 24456, "text": "The java.lang.Integer.reverseBytes(int a) is a built-in method which returns the value obtained by reversing the order of the bytes in the two’s complement representation of the specified int value." }, { "code": null, "e": 24664, "s": 24655, "text": "Syntax :" }, { "code": null, "e": 24702, "s": 24664, "text": "public static int reverseBytes(int a)" }, { "code": null, "e": 24794, "s": 24702, "text": "Parameter: The method takes one parameter a of integer type whose bytes are to be reversed." }, { "code": null, "e": 24901, "s": 24794, "text": "Return Value: The method will return the value obtained by reversing the bytes in the specified int value." }, { "code": null, "e": 24911, "s": 24901, "text": "Examples:" }, { "code": null, "e": 25114, "s": 24911, "text": "Input: 75\nOutput: 1258291200\nExplanation:\nConsider an integer a = 75 \nBinary Representation = 1001011\nNumber of one bit = 4 \nAfter reversing the bytes we get = 1258291200\n\nInput: -43\nOutput: -704643073\n" }, { "code": null, "e": 25218, "s": 25114, "text": "Below programs illustrate the java.lang.Integer.reverseBytes() method:Program 1: For a positive number." }, { "code": "// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 61; System.out.println(\" Integral Number = \" + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println(\"After reversing the bytes we get = \" + Integer.reverseBytes(a)); }}", "e": 25671, "s": 25218, "text": null }, { "code": null, "e": 25739, "s": 25671, "text": "Integral Number = 61\nAfter reversing the bytes we get = 1023410176\n" }, { "code": null, "e": 25773, "s": 25739, "text": "Program 2: For a negative number." }, { "code": "// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = -43; System.out.println(\" Integral Number = \" + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println(\"After reversing the bytes we get = \" + Integer.reverseBytes(a)); }}", "e": 26227, "s": 25773, "text": null }, { "code": null, "e": 26296, "s": 26227, "text": "Integral Number = -43\nAfter reversing the bytes we get = -704643073\n" }, { "code": null, "e": 26430, "s": 26296, "text": "Program 3: For a decimal value and string.Note: It returns an error message when a decimal value and string is passed as an argument." }, { "code": "// Java program to illustrate the// Java.lang.Integer.reverseBytes() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 37.81; System.out.println(\" Integral Number = \" + a); // It will return the value obtained by reversing the bytes in the // specified int value System.out.println(\"After reversing the bytes we get = \" + Integer.reverseBytes(a)); a = \"81\"; // compile time error will be generated System.out.println(\" Integral Number = \" + a); System.out.println(\"After reversing the bytes we get = \" + Integer.reverseBytes(a)); }}", "e": 27097, "s": 26430, "text": null }, { "code": null, "e": 27325, "s": 27097, "text": "prog.java:9: error: incompatible types: possible lossy conversion from double to int\n int a = 37.81;\n ^\nprog.java:18: error: incompatible types: String cannot be converted to int\n a = \"81\";\n ^\n2 errors\n\n" }, { "code": null, "e": 27340, "s": 27325, "text": "Java-Functions" }, { "code": null, "e": 27353, "s": 27340, "text": "Java-Integer" }, { "code": null, "e": 27371, "s": 27353, "text": "Java-lang package" }, { "code": null, "e": 27376, "s": 27371, "text": "Java" }, { "code": null, "e": 27381, "s": 27376, "text": "Java" }, { "code": null, "e": 27479, "s": 27381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27511, "s": 27479, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27562, "s": 27511, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27592, "s": 27562, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27611, "s": 27592, "text": "Interfaces in Java" }, { "code": null, "e": 27642, "s": 27611, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27660, "s": 27642, "text": "ArrayList in Java" }, { "code": null, "e": 27692, "s": 27660, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27707, "s": 27692, "text": "Stream In Java" }, { "code": null, "e": 27727, "s": 27707, "text": "Stack Class in Java" } ]
How to fill array values in Java?
Let us first create an int array − int[] arr = new int[10]; Now, fill array values. Here, the numbers get added from the index 2 to 7 − Arrays.fill(arr, 2, 7, 100); Live Demo import java.util.Arrays; public class Demo { public static void main(String[] args) { int[] arr = new int[10]; System.out.println("Array = "+Arrays.toString(arr)); Arrays.fill(arr, 2, 7, 100); System.out.println("Fill = "+Arrays.toString(arr)); } } Array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Fill = [0, 0, 100, 100, 100, 100, 100, 0, 0, 0]
[ { "code": null, "e": 1097, "s": 1062, "text": "Let us first create an int array −" }, { "code": null, "e": 1122, "s": 1097, "text": "int[] arr = new int[10];" }, { "code": null, "e": 1198, "s": 1122, "text": "Now, fill array values. Here, the numbers get added from the index 2 to 7 −" }, { "code": null, "e": 1227, "s": 1198, "text": "Arrays.fill(arr, 2, 7, 100);" }, { "code": null, "e": 1238, "s": 1227, "text": " Live Demo" }, { "code": null, "e": 1517, "s": 1238, "text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] args) {\n int[] arr = new int[10];\n System.out.println(\"Array = \"+Arrays.toString(arr));\n Arrays.fill(arr, 2, 7, 100);\n System.out.println(\"Fill = \"+Arrays.toString(arr));\n }\n}" }, { "code": null, "e": 1604, "s": 1517, "text": "Array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nFill = [0, 0, 100, 100, 100, 100, 100, 0, 0, 0]" } ]
Build a GUI Application to Get Live Stock Price using Python - GeeksforGeeks
19 Jan, 2021 The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application. Yahoo_fin: This module is used to scrape historical stock price data, as well as to provide current information on market caps, dividend yields, and which stocks comprise the major exchanges. To install this module type the below command in the terminal. pip install yahoo_fin Below is what the GUI looks like:- Let’s write code to get stock data. Import the yahoo_fin module. Python3 from yahoo_fin import stock_info Use stock_info.get_live_price() method to get live stock price. Python3 stock_info.get_live_price("AMZN") Output: 3198.93994140625 Note: please visit this site to get company Symbol like Amazon is AMZN, Reliance is RELFF. This Script implements the above Implementation into a GUI. Python3 from yahoo_fin import stock_infofrom tkinter import * def stock_price(): price = stock_info.get_live_price(e1.get()) Current_stock.set(price) master = Tk()Current_stock = StringVar() Label(master, text="Company Symbol : ").grid(row=0, sticky=W)Label(master, text="Stock Result:").grid(row=3, sticky=W) result2 = Label(master, text="", textvariable=Current_stock, ).grid(row=3, column=1, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text="Show", command=stock_price)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop() Output: abhigoya Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n19 Jan, 2021" }, { "code": null, "e": 24496, "s": 24292, "text": "The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application." }, { "code": null, "e": 24751, "s": 24496, "text": "Yahoo_fin: This module is used to scrape historical stock price data, as well as to provide current information on market caps, dividend yields, and which stocks comprise the major exchanges. To install this module type the below command in the terminal." }, { "code": null, "e": 24773, "s": 24751, "text": "pip install yahoo_fin" }, { "code": null, "e": 24808, "s": 24773, "text": "Below is what the GUI looks like:-" }, { "code": null, "e": 24844, "s": 24808, "text": "Let’s write code to get stock data." }, { "code": null, "e": 24873, "s": 24844, "text": "Import the yahoo_fin module." }, { "code": null, "e": 24881, "s": 24873, "text": "Python3" }, { "code": "from yahoo_fin import stock_info", "e": 24914, "s": 24881, "text": null }, { "code": null, "e": 24978, "s": 24914, "text": "Use stock_info.get_live_price() method to get live stock price." }, { "code": null, "e": 24986, "s": 24978, "text": "Python3" }, { "code": "stock_info.get_live_price(\"AMZN\")", "e": 25020, "s": 24986, "text": null }, { "code": null, "e": 25032, "s": 25023, "text": "Output: " }, { "code": null, "e": 25049, "s": 25032, "text": "3198.93994140625" }, { "code": null, "e": 25140, "s": 25049, "text": "Note: please visit this site to get company Symbol like Amazon is AMZN, Reliance is RELFF." }, { "code": null, "e": 25202, "s": 25142, "text": "This Script implements the above Implementation into a GUI." }, { "code": null, "e": 25210, "s": 25202, "text": "Python3" }, { "code": "from yahoo_fin import stock_infofrom tkinter import * def stock_price(): price = stock_info.get_live_price(e1.get()) Current_stock.set(price) master = Tk()Current_stock = StringVar() Label(master, text=\"Company Symbol : \").grid(row=0, sticky=W)Label(master, text=\"Stock Result:\").grid(row=3, sticky=W) result2 = Label(master, text=\"\", textvariable=Current_stock, ).grid(row=3, column=1, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text=\"Show\", command=stock_price)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()", "e": 25802, "s": 25210, "text": null }, { "code": null, "e": 25810, "s": 25802, "text": "Output:" }, { "code": null, "e": 25819, "s": 25810, "text": "abhigoya" }, { "code": null, "e": 25844, "s": 25819, "text": "Python Tkinter-exercises" }, { "code": null, "e": 25859, "s": 25844, "text": "Python-tkinter" }, { "code": null, "e": 25874, "s": 25859, "text": "python-utility" }, { "code": null, "e": 25881, "s": 25874, "text": "Python" }, { "code": null, "e": 25979, "s": 25881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25988, "s": 25979, "text": "Comments" }, { "code": null, "e": 26001, "s": 25988, "text": "Old Comments" }, { "code": null, "e": 26033, "s": 26001, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26075, "s": 26033, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26130, "s": 26075, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26186, "s": 26130, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26228, "s": 26186, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26250, "s": 26228, "text": "Defaultdict in Python" }, { "code": null, "e": 26289, "s": 26250, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26320, "s": 26289, "text": "Python | os.path.join() method" }, { "code": null, "e": 26349, "s": 26320, "text": "Create a directory in Python" } ]
PHP program to find the maximum and the minimum in array - GeeksforGeeks
24 Jun, 2021 Given an array of integers, find the maximum and minimum in it.Examples: Input : arr[] = {2, 3, 1, 6, 7} Output : Maximum integer of the given array:7 Minimum integer of the given array:1 Input : arr[] = {1, 2, 3, 4, 5} Output : Maximum integer of the given array : 5 Minimum integer of the given array : 1 Approach 1 (Simple) : We simply traverse through the array, find its maximum and minimum. PHP <?php// Returns maximum in arrayfunction getMax($array){ $n = count($array); $max = $array[0]; for ($i = 1; $i < $n; $i++) if ($max < $array[$i]) $max = $array[$i]; return $max; } // Returns maximum in arrayfunction getMin($array){ $n = count($array); $min = $array[0]; for ($i = 1; $i < $n; $i++) if ($min > $array[$i]) $min = $array[$i]; return $min; } // Driver code$array = array(1, 2, 3, 4, 5);echo(getMax($array));echo("\n");echo(getMin($array));?> Output: 5 1 Approach 2 (Using Library Functions) : We use library functions to find minimum and maximum. Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. PHP <?php$array = array(1, 2, 3, 4, 5);echo(max($array));echo("\n");echo(min($array));?> Output: 5 1 sweetyty PHP-array PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to pop an alert message box 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 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31430, "s": 31402, "text": "\n24 Jun, 2021" }, { "code": null, "e": 31505, "s": 31430, "text": "Given an array of integers, find the maximum and minimum in it.Examples: " }, { "code": null, "e": 31759, "s": 31505, "text": "Input : arr[] = {2, 3, 1, 6, 7}\nOutput : Maximum integer of the given array:7\n Minimum integer of the given array:1\n\nInput : arr[] = {1, 2, 3, 4, 5}\nOutput : Maximum integer of the given array : 5\n Minimum integer of the given array : 1" }, { "code": null, "e": 31853, "s": 31761, "text": "Approach 1 (Simple) : We simply traverse through the array, find its maximum and minimum. " }, { "code": null, "e": 31857, "s": 31853, "text": "PHP" }, { "code": "<?php// Returns maximum in arrayfunction getMax($array){ $n = count($array); $max = $array[0]; for ($i = 1; $i < $n; $i++) if ($max < $array[$i]) $max = $array[$i]; return $max; } // Returns maximum in arrayfunction getMin($array){ $n = count($array); $min = $array[0]; for ($i = 1; $i < $n; $i++) if ($min > $array[$i]) $min = $array[$i]; return $min; } // Driver code$array = array(1, 2, 3, 4, 5);echo(getMax($array));echo(\"\\n\");echo(getMin($array));?>", "e": 32372, "s": 31857, "text": null }, { "code": null, "e": 32382, "s": 32372, "text": "Output: " }, { "code": null, "e": 32386, "s": 32382, "text": "5\n1" }, { "code": null, "e": 32479, "s": 32386, "text": "Approach 2 (Using Library Functions) : We use library functions to find minimum and maximum." }, { "code": null, "e": 32927, "s": 32479, "text": "Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned." }, { "code": null, "e": 33153, "s": 32927, "text": "Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned. " }, { "code": null, "e": 33376, "s": 33153, "text": "Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned." }, { "code": null, "e": 33382, "s": 33378, "text": "PHP" }, { "code": "<?php$array = array(1, 2, 3, 4, 5);echo(max($array));echo(\"\\n\");echo(min($array));?>", "e": 33467, "s": 33382, "text": null }, { "code": null, "e": 33477, "s": 33467, "text": "Output: " }, { "code": null, "e": 33481, "s": 33477, "text": "5\n1" }, { "code": null, "e": 33492, "s": 33483, "text": "sweetyty" }, { "code": null, "e": 33502, "s": 33492, "text": "PHP-array" }, { "code": null, "e": 33506, "s": 33502, "text": "PHP" }, { "code": null, "e": 33523, "s": 33506, "text": "Web Technologies" }, { "code": null, "e": 33527, "s": 33523, "text": "PHP" }, { "code": null, "e": 33625, "s": 33527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33670, "s": 33625, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 33720, "s": 33670, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 33744, "s": 33720, "text": "PHP in_array() Function" }, { "code": null, "e": 33784, "s": 33744, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 33828, "s": 33784, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 33870, "s": 33828, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 33903, "s": 33870, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33946, "s": 33903, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34008, "s": 33946, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Hour-glass Pattern - GeeksforGeeks
16 Nov, 2021 Given positive integer n, print numeric pattern in form of an hourglass.Examples : Input : rows_no = 7 Output : 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 C++ Java Python3 C# PHP Javascript // CPP code for hour glass// pattern.#include <iostream>using namespace std; // Function definitionvoid pattern(int rows_no){ int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) cout << " "; // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) cout << j << " "; cout << endl; } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) cout << " "; // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) cout << j << " "; cout << endl; }} // Driver codeint main(){ // taking rows value from the user int rows_no = 7; pattern(rows_no); return 0;} // Java code for hour glass// pattern.import java.io.*; class GFG{ // Function definition static void pattern(int rows_no) { int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) System.out.print(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) System.out.print(j + " "); System.out.println(); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) System.out.print(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) System.out.print(j + " "); System.out.println(); } } // Driver code public static void main (String[] args) { // taking rows value from the user int rows_no = 7; pattern(rows_no); }} // This code is contributed by vt_m. # Python3 code for hour glass pattern # Function definitiondef pattern(rows_no): # for loop for printing upper half for i in range(1, rows_no + 1): # printing i spaces at the # beginning of each row for k in range(1, i): print(" ", end = "") # printing i to rows value # at the end of each row for j in range(i, rows_no + 1): print(j, end = " ") print() # for loop for printing lower half for i in range(rows_no - 1, 0, -1): # printing i spaces at the # beginning of each row for k in range(1, i): print(" ", end = "") # printing i to rows value # at the end of each row for j in range(i, rows_no + 1): print(j, end = " ") print() # Driver code # taking rows value from the userrows_no = 7 pattern(rows_no) # This code is contributed# by ihritik // C# code for hour glass// pattern.using System;class GFG{ // Function definition static void pattern(int rows_no) { int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) Console.Write(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) Console.Write(j + " "); Console.WriteLine(); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) Console.Write(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) Console.Write(j + " "); Console.WriteLine(); } } // Driver code public static void Main () { // taking rows value from the user int rows_no = 7; pattern(rows_no); }} // This code is contributed by vt_m. <?php// PHP code for hour glass pattern// Function definitionfunction pattern($rows_no){ // for loop for printing // upper half for ($i = 1; $i <= $rows_no; $i++) { // printing i spaces at // the beginning of each row for ($k = 1; $k < $i; $k++) echo " "; // printing i to rows value // at the end of each row for ($j = $i; $j <= $rows_no; $j++) echo $j." "; echo "\n"; } // for loop for printing lower half for ($i = $rows_no - 1; $i >= 1; $i--) { // printing i spaces at the // beginning of each row for ($k = 1; $k < $i; $k++) echo " "; // printing i to rows value // at the end of each row for ($j = $i; $j <= $rows_no; $j++) echo $j." "; echo "\n"; }} // Driver code$rows_no = 7;pattern($rows_no); // This code is contributed by mits?> <script>// Javascript code for hour glass// pattern. // Function definition function pattern( rows_no) { let i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) document.write(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) document.write(j + " "); document.write("<br/>"); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) document.write(" "); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) document.write(j + " "); document.write("<br/>"); } } // Driver code // taking rows value from the user let rows_no = 7; pattern(rows_no); // This code is contributed by gauravrajput1</script> Output : 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 Mithun Kumar ihritik Akanksha_Rai GauravRajput1 surinderdawra388 arorakashish0911 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Copy Constructor in C++ Overriding in Java C++ Data Types Polymorphism in C++ Types of Operating Systems Friend class and function in C++
[ { "code": null, "e": 24506, "s": 24478, "text": "\n16 Nov, 2021" }, { "code": null, "e": 24591, "s": 24506, "text": "Given positive integer n, print numeric pattern in form of an hourglass.Examples : " }, { "code": null, "e": 24768, "s": 24591, "text": "Input : rows_no = 7\nOutput :\n\n1 2 3 4 5 6 7\n 2 3 4 5 6 7\n 3 4 5 6 7\n 4 5 6 7\n 5 6 7\n 6 7 \n 7\n 6 7\n 5 6 7\n 4 5 6 7\n 3 4 5 6 7\n 2 3 4 5 6 7\n1 2 3 4 5 6 7" }, { "code": null, "e": 24776, "s": 24772, "text": "C++" }, { "code": null, "e": 24781, "s": 24776, "text": "Java" }, { "code": null, "e": 24789, "s": 24781, "text": "Python3" }, { "code": null, "e": 24792, "s": 24789, "text": "C#" }, { "code": null, "e": 24796, "s": 24792, "text": "PHP" }, { "code": null, "e": 24807, "s": 24796, "text": "Javascript" }, { "code": "// CPP code for hour glass// pattern.#include <iostream>using namespace std; // Function definitionvoid pattern(int rows_no){ int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) cout << \" \"; // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) cout << j << \" \"; cout << endl; } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) cout << \" \"; // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) cout << j << \" \"; cout << endl; }} // Driver codeint main(){ // taking rows value from the user int rows_no = 7; pattern(rows_no); return 0;}", "e": 25835, "s": 24807, "text": null }, { "code": "// Java code for hour glass// pattern.import java.io.*; class GFG{ // Function definition static void pattern(int rows_no) { int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) System.out.print(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) System.out.print(j + \" \"); System.out.println(); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) System.out.print(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) System.out.print(j + \" \"); System.out.println(); } } // Driver code public static void main (String[] args) { // taking rows value from the user int rows_no = 7; pattern(rows_no); }} // This code is contributed by vt_m.", "e": 27147, "s": 25835, "text": null }, { "code": "# Python3 code for hour glass pattern # Function definitiondef pattern(rows_no): # for loop for printing upper half for i in range(1, rows_no + 1): # printing i spaces at the # beginning of each row for k in range(1, i): print(\" \", end = \"\") # printing i to rows value # at the end of each row for j in range(i, rows_no + 1): print(j, end = \" \") print() # for loop for printing lower half for i in range(rows_no - 1, 0, -1): # printing i spaces at the # beginning of each row for k in range(1, i): print(\" \", end = \"\") # printing i to rows value # at the end of each row for j in range(i, rows_no + 1): print(j, end = \" \") print() # Driver code # taking rows value from the userrows_no = 7 pattern(rows_no) # This code is contributed# by ihritik", "e": 28079, "s": 27147, "text": null }, { "code": "// C# code for hour glass// pattern.using System;class GFG{ // Function definition static void pattern(int rows_no) { int i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) Console.Write(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) Console.Write(j + \" \"); Console.WriteLine(); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) Console.Write(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) Console.Write(j + \" \"); Console.WriteLine(); } } // Driver code public static void Main () { // taking rows value from the user int rows_no = 7; pattern(rows_no); }} // This code is contributed by vt_m.", "e": 29357, "s": 28079, "text": null }, { "code": "<?php// PHP code for hour glass pattern// Function definitionfunction pattern($rows_no){ // for loop for printing // upper half for ($i = 1; $i <= $rows_no; $i++) { // printing i spaces at // the beginning of each row for ($k = 1; $k < $i; $k++) echo \" \"; // printing i to rows value // at the end of each row for ($j = $i; $j <= $rows_no; $j++) echo $j.\" \"; echo \"\\n\"; } // for loop for printing lower half for ($i = $rows_no - 1; $i >= 1; $i--) { // printing i spaces at the // beginning of each row for ($k = 1; $k < $i; $k++) echo \" \"; // printing i to rows value // at the end of each row for ($j = $i; $j <= $rows_no; $j++) echo $j.\" \"; echo \"\\n\"; }} // Driver code$rows_no = 7;pattern($rows_no); // This code is contributed by mits?>", "e": 30298, "s": 29357, "text": null }, { "code": "<script>// Javascript code for hour glass// pattern. // Function definition function pattern( rows_no) { let i, j, k; // for loop for printing // upper half for (i = 1; i <= rows_no; i++) { // printing i spaces at // the beginning of each row for (k = 1; k < i; k++) document.write(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) document.write(j + \" \"); document.write(\"<br/>\"); } // for loop for printing lower half for (i = rows_no - 1; i >= 1; i--) { // printing i spaces at the // beginning of each row for (k = 1; k < i; k++) document.write(\" \"); // printing i to rows value // at the end of each row for (j = i; j <= rows_no; j++) document.write(j + \" \"); document.write(\"<br/>\"); } } // Driver code // taking rows value from the user let rows_no = 7; pattern(rows_no); // This code is contributed by gauravrajput1</script>", "e": 31504, "s": 30298, "text": null }, { "code": null, "e": 31515, "s": 31504, "text": "Output : " }, { "code": null, "e": 31662, "s": 31515, "text": "1 2 3 4 5 6 7\n 2 3 4 5 6 7\n 3 4 5 6 7\n 4 5 6 7\n 5 6 7\n 6 7 \n 7\n 6 7\n 5 6 7\n 4 5 6 7\n 3 4 5 6 7\n 2 3 4 5 6 7\n1 2 3 4 5 6 7" }, { "code": null, "e": 31677, "s": 31664, "text": "Mithun Kumar" }, { "code": null, "e": 31685, "s": 31677, "text": "ihritik" }, { "code": null, "e": 31698, "s": 31685, "text": "Akanksha_Rai" }, { "code": null, "e": 31712, "s": 31698, "text": "GauravRajput1" }, { "code": null, "e": 31729, "s": 31712, "text": "surinderdawra388" }, { "code": null, "e": 31746, "s": 31729, "text": "arorakashish0911" }, { "code": null, "e": 31763, "s": 31746, "text": "pattern-printing" }, { "code": null, "e": 31782, "s": 31763, "text": "School Programming" }, { "code": null, "e": 31799, "s": 31782, "text": "pattern-printing" }, { "code": null, "e": 31897, "s": 31799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31906, "s": 31897, "text": "Comments" }, { "code": null, "e": 31919, "s": 31906, "text": "Old Comments" }, { "code": null, "e": 31938, "s": 31919, "text": "Interfaces in Java" }, { "code": null, "e": 31962, "s": 31938, "text": "C++ Classes and Objects" }, { "code": null, "e": 31990, "s": 31962, "text": "Operator Overloading in C++" }, { "code": null, "e": 32010, "s": 31990, "text": "Constructors in C++" }, { "code": null, "e": 32034, "s": 32010, "text": "Copy Constructor in C++" }, { "code": null, "e": 32053, "s": 32034, "text": "Overriding in Java" }, { "code": null, "e": 32068, "s": 32053, "text": "C++ Data Types" }, { "code": null, "e": 32088, "s": 32068, "text": "Polymorphism in C++" }, { "code": null, "e": 32115, "s": 32088, "text": "Types of Operating Systems" } ]
Visualizing the Fundamentals of Convolutional Neural Networks | by Mark C. F. Sousa | Towards Data Science
Convolutional Neural Networks (CNNs) are a subtype of Artificial Neural Networks (ANNs) mostly used for image classification. CNNs follow the biological principle of the replication of a structure capable of identifying patterns to identify these patterns in different locations. It was inspired by the model of cats’ visual system proposed by the Nobel prizes winners Hubel and Wiesel at “Receptive fields, binocular interaction and functional architecture in the cat’s visual cortex”, published in 1962. One of the works that used this inspiration was the Fukushima’s Neocognitron, in 1980, although the word Convolution was not used at the time. Therefore, it is not a coincidence that CNNs are very successful in image recognition. However, they have also shown good results dealing with temporal data such as time series and speech recognition, or even when applied on graphs. The CNNs became very popular after winning the 2012 edition of the competition Imagenet Large Scale Visual Recognition Challenge (ILSVRC) by a margin of roughly 10%. Alex Krizhevsky and Ilya Sutskever, under the guidance of Geoffrey Hinton, submitted the CNN architecture that became famous under the name of “AlexNet”. At the time, Geoffrey Hinton had already made significant scientific contributions to the field of ANNs. He was one of the contributors of the Backpropagation algorithm in 1986, and Boltzmann Machines in 1983. These are some of the reasons that Geoffrey Hinton was recognised as one of the fathers of Deep Learning. A typical CNN is composed by a series of convolutional layers, that act as features extractors, followed by a classifier, usually a Multilayer Perceptron (MLP), also known as Fully Connected Layers (FC layers), as shown by Figure 1. The first layer receives the input image represented in three colour channels, the RGB channels. Then, the first layer executes the convolutions of the input image with multiple kernels, resulting in a set of feature maps of the first layer. Each feature map determines the intensity and location of a specific feature. The feature map extracted by a convolutional layer can be submitted to a downsampling operation known as Pooling. The Pooling operation is optional, so it may not follow every convolutional layer. The result of a Pooling layer is another set of feature maps, with the same number of maps, but with reduced resolution. The following convolutional layer uses the feature map from the previous layer to execute more convolutions and generate new feature maps. The feature maps from the last layers are the input of the classifier, the FC layers. The convolution operation, which is denoted by an ∗ (asterisk), can be described as: being x some type of input, such as a sensor signal, t a given time, and k the kernel applied. One important property of the convolution operation is that it is commutative, which means that (x∗ k)=( k∗x) as follows: On the other hand, the cross-correlation operation, denoted by ⋆ (five-pointed star), is not commutative and can be described as: The commutative property of the convolution emerges from the fact that the kernel is flipped relative to the input. The flip occurs as a result of index manipulation. Note that the index for the input x is a and the index for kernel is t−a. Even though the commutative is a valuable property for writing mathematical proofs, it is not as relevant for neural network implementation. In fact, many machine learning libraries implement the cross-correlation instead of convolution and refer to both operations as convolution. As a consequence, the kernel that is learned during training will be flipped in comparison to a library that actually implements the convolution as described by equation 1. We will follow the same convention in this text and call the cross-correlation convolution. We can adapt the equation 3 for the convolution with 2D data, such as grey-scale images: being r[i,j] a discrete output of the convolution, h the height of the kernel, w the width of the kernel, x[a,b] the patch of the grey-scale image, and k[i+a, j+b] the kernel. In other words, the convolution operation extracts multiple patches of pixels from the image to multiply by the kernel. The kernel is basically a matrix of weights. The patch of pixels extracted from the image is often known as receptive field — in biology, the receptive field is a sensorial region that stimulates a neuron. The multiplication between the receptive field and the kernel consists of an element-wise multiplication between each pixel and the respective element of the kernel. After the multiplications, the results are added to form one element of the feature map, defined in equation 4 by r[i,j]. The following animation shows the convolution operation between a 5x5 grey-scale image and a 3x3 kernel. The receptive field is highlighted by the red square. The output of this convolution is a 3x3 feature map. The actual image used in the animation can be seen in Figure 3 below. The values in the kernel and the feature map were rescaled to fit into the interval between 0 and 255 to be represented as grey-scale pixels. The brighter pixels in the image represent higher values from convolution, while the darker pixels represent lower values. The convolution above uses kernel 3x3, consequently, there are nine possible receptive fields in the input, each with size 3x3. Note that the receptive fields composed of mostly white pixels or composed of mostly dark pixels result in a very dark pixel after the convolution. On the other hand, the receptive fields that are composed by three bright pixels on the left, intermediate pixels in the middle and dark pixels on the right, result in the brightest pixels after the convolution. This is because this type of kernel is useful to highlight edges, specifically edges transitioning from a bright region on the left to a dark region on the right. Now, see what happens when we apply the same kernel to an image that also contains the opposite transition, from a dark region on the left to a bright region on the right. In Figure 4, the receptive fields that exhibit the transition from dark to bright resulted in the darkest pixels. Note that the former transition (from bright to dark) still resulted in the brighter pixels. It means that this kernel not only detects the edges transitioning from bright to dark but also detects the opposite edges, from dark to bright. One type of edge results in the most positive values, while the other type of edge results in the most negative values. The convolution for RGB images is quite similar to the grey-scale case. The equation 4 can be adapted to RGB image adding another loop to iterate over the RGB channels as follows: The additional loop over the variable c allows the iteration on the channels RBG. As a result, the sum is done over three-dimensional data, instead of bi-dimensional, and still results in a single value for each three-dimensional receptive field and kernel. Let’s start this topic with a practical example. Look at the result of the following three convolutions in Figure 5. In order to illustrate the result of the convolutions, each of the three kernels in the following examples consists of a small patch extracted from the image. In the first example, the patch composing the kernel comprises the region of the plane with the number six in white. The grey-scale image on the right is essentially the result of the convolution between the kernel and the image. The darkest pixels represent the smallest results of the operation between a receptive field and the kernel, on the other hand, the brightest pixels represent the highest values for the operation between a receptive field and the kernel. In the second example, the kernel consists of the patch of pixels forming the wheel of the plane. In the third example, the kernel consists of a patch of yellow pixels copied from the tail of the plane. Note that the brightest pixels in each resulting image correspond to the location that originated each kernel. In the first example, it corresponds to the location of the number 6. In the second example, it corresponds to the location of the wheels. Even though the kernel is a copy of one of the wheels, the other wheel is quite similar and also resulted in bright pixels. In the third example, the brightest pixels correspond to all the yellow region of the plane. The stride is the distance between each receptive field. All the examples we have shown so far use a stride of one. The adoption of such small strides results in a big overlap between receptive fields. As a result, a lot of information is repeated in adjacent receptive fields, as shown in Figure 6. In the case of a kernel with dimensions 3x3, the adoption of a stride of 2 results in one column or one row overlapping with adjacent receptive fields. This overlap is desired to guarantee that the stride doesn’t skip important information. Increasing the stride will reduce the computational cost of the convolutions. If we change the stride from one to two, the reduction in the computational cost is about four. It happens because the stride affects the distance between receptive fields in both dimensions. Similarly, if we triple the stride, we can expect a computational cost reduction of roughly nine times. The computation cost is reduced because the increase in stride reduces the number of receptive fields extracted from the input, consequently, the dimension of the output is also reduced. Figure 7 shows four results of convolution using strides of 2, 4, 8, and 16. The kernel size used in the convolutions is 70x70. Note that increasing the stride by a factor of two, the execution time is reduced by almost four. In Figure 7, the result of the convolution using a stride of 16 has four times fewer pixels than the result using the stride of 8. Note that adopting the stride of 16 results in an overlapping of 54 rows or columns, because the receptive field size is 70x70. With the stride of 16, it is still possible to identify the highest values of the convolution by the brightest pixels in the wheel of the plane. In this section, we will study how the forward propagation works in the convolutional layers. To do so, we will understand how a single convolutional layer works and then understand how multiple layers work together. In this study, we will learn two new concepts: non-linear activation and pooling operation. Figure 8 shows the forward propagation in a typical convolutional layer, which consists of three stages: convolutions, non-linear activations, and pooling. The convolution operation was already discussed in the first section. Now, we will see the other two operations. The non-linear activation is also known as the detector stage. In this stage, the result of the convolutions and the bias are submitted to a non-linear activation such as the ReLU function. The non-linear activation doesn’t change the dimensions of the feature map, it only modulates the values in it. First, what is linear activation? A linear activation is a function that follows the rule f(x)=ax, where a is a constant and x the variable. Its graph is a straight line through the origin (0, 0). It means that the functions in the shape f(x)=ax + b, in which a and b are constant, are not linear. Both are affine functions, but only the one with a single constant multiplying the variable is a linear function. To a function be linear, when we multiply the input by a constant α, we should also see the output multiplied by the same constant α. That means: Another requirement is that when we apply the sum of two inputs in a linear function, we should get the output equivalent of the sum of the two variable applied individually to the function: Now, why we do we use non-linear activation? Because when we apply linear combinations (additions or multiplications) in linear functions, the result is also linear. Even though many models can be roughly approximated by linear models, using non-linearities in ANNs makes it capable of representing both linear and non-linear models. In other words, non-linearities make ANNs more powerful function approximators. One of the most common non-linear activation used in deep learning is the ReLU function, which stands for Rectified Linear Unit. This function is given by: This function, when applied with a bias, results in a graph illustrated in Figure 9. Figure 10 shows how the ReLU modulates the result of the convolution. Here, the same results from Figure 2 are used to apply the ReLU function. The equivalent image of the ReLU function used in the example above is shown in Figure 11. Note that some of the intermediate values were blacked-out, highlighting the brightest three pixels. Next, in Figure 12, you can see some options of bias in the ReLU function. The function takes the result of the convolution of the plane with the patch of the image containing the wheel as input. Note that the bias behaves like a threshold that determines what is shown and what is not. The threshold behaviour depicted in Figure 12 resembles the biological neurons, that doesn’t fire when it receives a stimulus under a certain threshold. If the stimulus surpasses the threshold, the neuron starts to fire, and also fires more frequently as the stimulus increases. In Figure 12, when the bias is 500, it is contributing to the activity of the artificial neuron. However, if we define the bias as -1000, the artificial neuron only fires with the strongest stimulus. To conclude, the ReLU function works as an artificial neuron. That is why this phase is called the detection phase. The ReLU function is responsible for detecting the presence of the feature extracted by the kernel. Consequently, there is a single bias for each the kernel, because each feature requires a different threshold. At last, but not least, the pooling operation. It is a downsampling operation executed over each feature map. It extracts receptive fields from the feature map and replaces it with a single value. This single value can be obtained by different aggregation criteria, such as maximum value, average, or weighted average according to the distance from the centre of the receptive field. Besides the aggregation criteria, there are other two hyperparameters in the pooling operation, the size of the receptive field and the stride. Similar to the stride, the pooling operation results in fewer data processed by the convolutions. One difference is that instead of skipping data, the pooling operation tries to summarise the receptive field into a single value. Another difference is that the stride is applied before the convolution, while pooling is applied over the result of a convolution, reducing the volume of data to the next layer. Furthermore, the receptive field of the pooling operation is bi-dimensional, because it is applied to each feature map individually, while the receptive field of the convolution is three-dimensional, comprising a section of all the feature maps in a layer. One desired side-effect of the pooling operation is that is increases the invariance of the network to translations of the input. This effect is amplified as more convolutional layers are followed by pooling layers. Figure 13 shows the propagation of values through two pooling layers with pooling size of 3x3 and stride of 2. Any activation in the region covered in blue the input feature map affects the region covered in blue in the outcome of pooling 1. Similarly, the activations in the region covered in blue in the outcome of pooling 1 affect the region covered in blue in the outcome of pooling 2. The same relationship is valid between the regions covered in green. Considering that the pooling in Figure 13 is max pooling, it doesn’t matter where in the blue region the highest value occurs in the input feature map, because it will be propagated to the blue activation in the outcome pooling 2 in the same way. This is the reason why pooling layers enhance translation invariance, small translations in the input don’t change the values in the output. Figure 14 shows the effect of different combinations of strides in convolution, biases in the ReLU function, pooling sizes, and pooling strides. On the left, there are three examples of strides: 2, 9, and 16. For each option of stride, there are three examples of bias: 500, -250, and -1000. For each bias, there are three examples of pooling size and stride: pooling size 3x3 and stride of 2, pooling size 5x5 and stride of 3, and pooling size 7x7 and stride of 4x4. The effect of the stride in the convolution and the stride in the max pooling is cumulative. When we use a stride of two in both convolution and in the max pooling, the final result is a reduction of roughly four times in the width and in the height of the feature map. The values 16 for stride in the convolution and four in the stride of max pooling are unusual. They were intentionally exaggerated to illustrate the impact they have in the final result of the convolutional layer. The resulting feature map has only 100 elements (10 x 10), much smaller than the feature map with 37636 elements (194 x 194). We will come back to the AlexNet, the first famous CNN architecture. This is a good practical example to understand how the components of CNNs work together. The building blocks of AlexNet is represented in Figure 14. The dashed pyramids represent the execution of convolutions using a receptive field from the input or the feature map from the previous layer. The big boxes represent the feature maps and the small boxes inside the feature maps are the receptive fields. This CNN can classify objects in 1000 different classes. One peculiarity of this architecture is that it was trained using two GPUs. The top elements of Figure 15 were allocated in one GPU, while the elements at the bottom were allocated in another GPU. You can get this CNN already trained in some frameworks, such as PyTorch. It is relatively easy to use. You can also use transfer learning to apply this architecture to other image datasets. It requires a little data processing to normalize and rescale the images to match the requirements of AlexNet, but it worth the try. It would be something like: from torchvision import transformspre_transforms = transforms.Compose([transforms.RandomResizedCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) You can import the model in PyTorch as follows: from torchvision import modelsmodel = models.alexnet(pretrained=True) You can disable the training of the convolutional layers and create your own classifier to override the original AlexNet Fully Connected Layers: from torch import nnfor param in model.parameters(): param.requires_grad = False # disable trainingfcLayersDict = OrderedDict([('fc1', nn.Linear(9216, 1024)), ('relu1', nn.ReLU()), ('fc2', nn.Linear(1024, 102)), ('output', nn.LogSoftmax(dim=1)) ])model.fcLayersDict = fcLayersDictfc = nn.Sequential(fcLayersDict)model.classifier = fc In addition to AlexNet, there are also other models in PyTorch that can be used to classify your own image dataset, given the necessary customizations. It is really recommended to test these models or even build your own CNN from scratch to understand how CNN works. Even if you were already familiar with the concepts presented here, I hope you could at least see them from another perspective. There were some other concepts from CNNs that were not discussed here. If you are curious or are not sure about a particular aspect of CNNs, please, let me know.
[ { "code": null, "e": 1689, "s": 171, "text": "Convolutional Neural Networks (CNNs) are a subtype of Artificial Neural Networks (ANNs) mostly used for image classification. CNNs follow the biological principle of the replication of a structure capable of identifying patterns to identify these patterns in different locations. It was inspired by the model of cats’ visual system proposed by the Nobel prizes winners Hubel and Wiesel at “Receptive fields, binocular interaction and functional architecture in the cat’s visual cortex”, published in 1962. One of the works that used this inspiration was the Fukushima’s Neocognitron, in 1980, although the word Convolution was not used at the time. Therefore, it is not a coincidence that CNNs are very successful in image recognition. However, they have also shown good results dealing with temporal data such as time series and speech recognition, or even when applied on graphs. The CNNs became very popular after winning the 2012 edition of the competition Imagenet Large Scale Visual Recognition Challenge (ILSVRC) by a margin of roughly 10%. Alex Krizhevsky and Ilya Sutskever, under the guidance of Geoffrey Hinton, submitted the CNN architecture that became famous under the name of “AlexNet”. At the time, Geoffrey Hinton had already made significant scientific contributions to the field of ANNs. He was one of the contributors of the Backpropagation algorithm in 1986, and Boltzmann Machines in 1983. These are some of the reasons that Geoffrey Hinton was recognised as one of the fathers of Deep Learning." }, { "code": null, "e": 1922, "s": 1689, "text": "A typical CNN is composed by a series of convolutional layers, that act as features extractors, followed by a classifier, usually a Multilayer Perceptron (MLP), also known as Fully Connected Layers (FC layers), as shown by Figure 1." }, { "code": null, "e": 2785, "s": 1922, "text": "The first layer receives the input image represented in three colour channels, the RGB channels. Then, the first layer executes the convolutions of the input image with multiple kernels, resulting in a set of feature maps of the first layer. Each feature map determines the intensity and location of a specific feature. The feature map extracted by a convolutional layer can be submitted to a downsampling operation known as Pooling. The Pooling operation is optional, so it may not follow every convolutional layer. The result of a Pooling layer is another set of feature maps, with the same number of maps, but with reduced resolution. The following convolutional layer uses the feature map from the previous layer to execute more convolutions and generate new feature maps. The feature maps from the last layers are the input of the classifier, the FC layers." }, { "code": null, "e": 2870, "s": 2785, "text": "The convolution operation, which is denoted by an ∗ (asterisk), can be described as:" }, { "code": null, "e": 2965, "s": 2870, "text": "being x some type of input, such as a sensor signal, t a given time, and k the kernel applied." }, { "code": null, "e": 3087, "s": 2965, "text": "One important property of the convolution operation is that it is commutative, which means that (x∗ k)=( k∗x) as follows:" }, { "code": null, "e": 3217, "s": 3087, "text": "On the other hand, the cross-correlation operation, denoted by ⋆ (five-pointed star), is not commutative and can be described as:" }, { "code": null, "e": 4005, "s": 3217, "text": "The commutative property of the convolution emerges from the fact that the kernel is flipped relative to the input. The flip occurs as a result of index manipulation. Note that the index for the input x is a and the index for kernel is t−a. Even though the commutative is a valuable property for writing mathematical proofs, it is not as relevant for neural network implementation. In fact, many machine learning libraries implement the cross-correlation instead of convolution and refer to both operations as convolution. As a consequence, the kernel that is learned during training will be flipped in comparison to a library that actually implements the convolution as described by equation 1. We will follow the same convention in this text and call the cross-correlation convolution." }, { "code": null, "e": 4094, "s": 4005, "text": "We can adapt the equation 3 for the convolution with 2D data, such as grey-scale images:" }, { "code": null, "e": 4270, "s": 4094, "text": "being r[i,j] a discrete output of the convolution, h the height of the kernel, w the width of the kernel, x[a,b] the patch of the grey-scale image, and k[i+a, j+b] the kernel." }, { "code": null, "e": 4884, "s": 4270, "text": "In other words, the convolution operation extracts multiple patches of pixels from the image to multiply by the kernel. The kernel is basically a matrix of weights. The patch of pixels extracted from the image is often known as receptive field — in biology, the receptive field is a sensorial region that stimulates a neuron. The multiplication between the receptive field and the kernel consists of an element-wise multiplication between each pixel and the respective element of the kernel. After the multiplications, the results are added to form one element of the feature map, defined in equation 4 by r[i,j]." }, { "code": null, "e": 5096, "s": 4884, "text": "The following animation shows the convolution operation between a 5x5 grey-scale image and a 3x3 kernel. The receptive field is highlighted by the red square. The output of this convolution is a 3x3 feature map." }, { "code": null, "e": 5431, "s": 5096, "text": "The actual image used in the animation can be seen in Figure 3 below. The values in the kernel and the feature map were rescaled to fit into the interval between 0 and 255 to be represented as grey-scale pixels. The brighter pixels in the image represent higher values from convolution, while the darker pixels represent lower values." }, { "code": null, "e": 6082, "s": 5431, "text": "The convolution above uses kernel 3x3, consequently, there are nine possible receptive fields in the input, each with size 3x3. Note that the receptive fields composed of mostly white pixels or composed of mostly dark pixels result in a very dark pixel after the convolution. On the other hand, the receptive fields that are composed by three bright pixels on the left, intermediate pixels in the middle and dark pixels on the right, result in the brightest pixels after the convolution. This is because this type of kernel is useful to highlight edges, specifically edges transitioning from a bright region on the left to a dark region on the right." }, { "code": null, "e": 6726, "s": 6082, "text": "Now, see what happens when we apply the same kernel to an image that also contains the opposite transition, from a dark region on the left to a bright region on the right. In Figure 4, the receptive fields that exhibit the transition from dark to bright resulted in the darkest pixels. Note that the former transition (from bright to dark) still resulted in the brighter pixels. It means that this kernel not only detects the edges transitioning from bright to dark but also detects the opposite edges, from dark to bright. One type of edge results in the most positive values, while the other type of edge results in the most negative values." }, { "code": null, "e": 6906, "s": 6726, "text": "The convolution for RGB images is quite similar to the grey-scale case. The equation 4 can be adapted to RGB image adding another loop to iterate over the RGB channels as follows:" }, { "code": null, "e": 7164, "s": 6906, "text": "The additional loop over the variable c allows the iteration on the channels RBG. As a result, the sum is done over three-dimensional data, instead of bi-dimensional, and still results in a single value for each three-dimensional receptive field and kernel." }, { "code": null, "e": 7440, "s": 7164, "text": "Let’s start this topic with a practical example. Look at the result of the following three convolutions in Figure 5. In order to illustrate the result of the convolutions, each of the three kernels in the following examples consists of a small patch extracted from the image." }, { "code": null, "e": 7908, "s": 7440, "text": "In the first example, the patch composing the kernel comprises the region of the plane with the number six in white. The grey-scale image on the right is essentially the result of the convolution between the kernel and the image. The darkest pixels represent the smallest results of the operation between a receptive field and the kernel, on the other hand, the brightest pixels represent the highest values for the operation between a receptive field and the kernel." }, { "code": null, "e": 8111, "s": 7908, "text": "In the second example, the kernel consists of the patch of pixels forming the wheel of the plane. In the third example, the kernel consists of a patch of yellow pixels copied from the tail of the plane." }, { "code": null, "e": 8578, "s": 8111, "text": "Note that the brightest pixels in each resulting image correspond to the location that originated each kernel. In the first example, it corresponds to the location of the number 6. In the second example, it corresponds to the location of the wheels. Even though the kernel is a copy of one of the wheels, the other wheel is quite similar and also resulted in bright pixels. In the third example, the brightest pixels correspond to all the yellow region of the plane." }, { "code": null, "e": 8878, "s": 8578, "text": "The stride is the distance between each receptive field. All the examples we have shown so far use a stride of one. The adoption of such small strides results in a big overlap between receptive fields. As a result, a lot of information is repeated in adjacent receptive fields, as shown in Figure 6." }, { "code": null, "e": 9119, "s": 8878, "text": "In the case of a kernel with dimensions 3x3, the adoption of a stride of 2 results in one column or one row overlapping with adjacent receptive fields. This overlap is desired to guarantee that the stride doesn’t skip important information." }, { "code": null, "e": 9680, "s": 9119, "text": "Increasing the stride will reduce the computational cost of the convolutions. If we change the stride from one to two, the reduction in the computational cost is about four. It happens because the stride affects the distance between receptive fields in both dimensions. Similarly, if we triple the stride, we can expect a computational cost reduction of roughly nine times. The computation cost is reduced because the increase in stride reduces the number of receptive fields extracted from the input, consequently, the dimension of the output is also reduced." }, { "code": null, "e": 9906, "s": 9680, "text": "Figure 7 shows four results of convolution using strides of 2, 4, 8, and 16. The kernel size used in the convolutions is 70x70. Note that increasing the stride by a factor of two, the execution time is reduced by almost four." }, { "code": null, "e": 10310, "s": 9906, "text": "In Figure 7, the result of the convolution using a stride of 16 has four times fewer pixels than the result using the stride of 8. Note that adopting the stride of 16 results in an overlapping of 54 rows or columns, because the receptive field size is 70x70. With the stride of 16, it is still possible to identify the highest values of the convolution by the brightest pixels in the wheel of the plane." }, { "code": null, "e": 10619, "s": 10310, "text": "In this section, we will study how the forward propagation works in the convolutional layers. To do so, we will understand how a single convolutional layer works and then understand how multiple layers work together. In this study, we will learn two new concepts: non-linear activation and pooling operation." }, { "code": null, "e": 10888, "s": 10619, "text": "Figure 8 shows the forward propagation in a typical convolutional layer, which consists of three stages: convolutions, non-linear activations, and pooling. The convolution operation was already discussed in the first section. Now, we will see the other two operations." }, { "code": null, "e": 11190, "s": 10888, "text": "The non-linear activation is also known as the detector stage. In this stage, the result of the convolutions and the bias are submitted to a non-linear activation such as the ReLU function. The non-linear activation doesn’t change the dimensions of the feature map, it only modulates the values in it." }, { "code": null, "e": 11602, "s": 11190, "text": "First, what is linear activation? A linear activation is a function that follows the rule f(x)=ax, where a is a constant and x the variable. Its graph is a straight line through the origin (0, 0). It means that the functions in the shape f(x)=ax + b, in which a and b are constant, are not linear. Both are affine functions, but only the one with a single constant multiplying the variable is a linear function." }, { "code": null, "e": 11748, "s": 11602, "text": "To a function be linear, when we multiply the input by a constant α, we should also see the output multiplied by the same constant α. That means:" }, { "code": null, "e": 11939, "s": 11748, "text": "Another requirement is that when we apply the sum of two inputs in a linear function, we should get the output equivalent of the sum of the two variable applied individually to the function:" }, { "code": null, "e": 12353, "s": 11939, "text": "Now, why we do we use non-linear activation? Because when we apply linear combinations (additions or multiplications) in linear functions, the result is also linear. Even though many models can be roughly approximated by linear models, using non-linearities in ANNs makes it capable of representing both linear and non-linear models. In other words, non-linearities make ANNs more powerful function approximators." }, { "code": null, "e": 12509, "s": 12353, "text": "One of the most common non-linear activation used in deep learning is the ReLU function, which stands for Rectified Linear Unit. This function is given by:" }, { "code": null, "e": 12594, "s": 12509, "text": "This function, when applied with a bias, results in a graph illustrated in Figure 9." }, { "code": null, "e": 12738, "s": 12594, "text": "Figure 10 shows how the ReLU modulates the result of the convolution. Here, the same results from Figure 2 are used to apply the ReLU function." }, { "code": null, "e": 12930, "s": 12738, "text": "The equivalent image of the ReLU function used in the example above is shown in Figure 11. Note that some of the intermediate values were blacked-out, highlighting the brightest three pixels." }, { "code": null, "e": 13217, "s": 12930, "text": "Next, in Figure 12, you can see some options of bias in the ReLU function. The function takes the result of the convolution of the plane with the patch of the image containing the wheel as input. Note that the bias behaves like a threshold that determines what is shown and what is not." }, { "code": null, "e": 13696, "s": 13217, "text": "The threshold behaviour depicted in Figure 12 resembles the biological neurons, that doesn’t fire when it receives a stimulus under a certain threshold. If the stimulus surpasses the threshold, the neuron starts to fire, and also fires more frequently as the stimulus increases. In Figure 12, when the bias is 500, it is contributing to the activity of the artificial neuron. However, if we define the bias as -1000, the artificial neuron only fires with the strongest stimulus." }, { "code": null, "e": 14023, "s": 13696, "text": "To conclude, the ReLU function works as an artificial neuron. That is why this phase is called the detection phase. The ReLU function is responsible for detecting the presence of the feature extracted by the kernel. Consequently, there is a single bias for each the kernel, because each feature requires a different threshold." }, { "code": null, "e": 14407, "s": 14023, "text": "At last, but not least, the pooling operation. It is a downsampling operation executed over each feature map. It extracts receptive fields from the feature map and replaces it with a single value. This single value can be obtained by different aggregation criteria, such as maximum value, average, or weighted average according to the distance from the centre of the receptive field." }, { "code": null, "e": 14551, "s": 14407, "text": "Besides the aggregation criteria, there are other two hyperparameters in the pooling operation, the size of the receptive field and the stride." }, { "code": null, "e": 15216, "s": 14551, "text": "Similar to the stride, the pooling operation results in fewer data processed by the convolutions. One difference is that instead of skipping data, the pooling operation tries to summarise the receptive field into a single value. Another difference is that the stride is applied before the convolution, while pooling is applied over the result of a convolution, reducing the volume of data to the next layer. Furthermore, the receptive field of the pooling operation is bi-dimensional, because it is applied to each feature map individually, while the receptive field of the convolution is three-dimensional, comprising a section of all the feature maps in a layer." }, { "code": null, "e": 15432, "s": 15216, "text": "One desired side-effect of the pooling operation is that is increases the invariance of the network to translations of the input. This effect is amplified as more convolutional layers are followed by pooling layers." }, { "code": null, "e": 15891, "s": 15432, "text": "Figure 13 shows the propagation of values through two pooling layers with pooling size of 3x3 and stride of 2. Any activation in the region covered in blue the input feature map affects the region covered in blue in the outcome of pooling 1. Similarly, the activations in the region covered in blue in the outcome of pooling 1 affect the region covered in blue in the outcome of pooling 2. The same relationship is valid between the regions covered in green." }, { "code": null, "e": 16279, "s": 15891, "text": "Considering that the pooling in Figure 13 is max pooling, it doesn’t matter where in the blue region the highest value occurs in the input feature map, because it will be propagated to the blue activation in the outcome pooling 2 in the same way. This is the reason why pooling layers enhance translation invariance, small translations in the input don’t change the values in the output." }, { "code": null, "e": 16747, "s": 16279, "text": "Figure 14 shows the effect of different combinations of strides in convolution, biases in the ReLU function, pooling sizes, and pooling strides. On the left, there are three examples of strides: 2, 9, and 16. For each option of stride, there are three examples of bias: 500, -250, and -1000. For each bias, there are three examples of pooling size and stride: pooling size 3x3 and stride of 2, pooling size 5x5 and stride of 3, and pooling size 7x7 and stride of 4x4." }, { "code": null, "e": 17017, "s": 16747, "text": "The effect of the stride in the convolution and the stride in the max pooling is cumulative. When we use a stride of two in both convolution and in the max pooling, the final result is a reduction of roughly four times in the width and in the height of the feature map." }, { "code": null, "e": 17357, "s": 17017, "text": "The values 16 for stride in the convolution and four in the stride of max pooling are unusual. They were intentionally exaggerated to illustrate the impact they have in the final result of the convolutional layer. The resulting feature map has only 100 elements (10 x 10), much smaller than the feature map with 37636 elements (194 x 194)." }, { "code": null, "e": 17886, "s": 17357, "text": "We will come back to the AlexNet, the first famous CNN architecture. This is a good practical example to understand how the components of CNNs work together. The building blocks of AlexNet is represented in Figure 14. The dashed pyramids represent the execution of convolutions using a receptive field from the input or the feature map from the previous layer. The big boxes represent the feature maps and the small boxes inside the feature maps are the receptive fields. This CNN can classify objects in 1000 different classes." }, { "code": null, "e": 18083, "s": 17886, "text": "One peculiarity of this architecture is that it was trained using two GPUs. The top elements of Figure 15 were allocated in one GPU, while the elements at the bottom were allocated in another GPU." }, { "code": null, "e": 18435, "s": 18083, "text": "You can get this CNN already trained in some frameworks, such as PyTorch. It is relatively easy to use. You can also use transfer learning to apply this architecture to other image datasets. It requires a little data processing to normalize and rescale the images to match the requirements of AlexNet, but it worth the try. It would be something like:" }, { "code": null, "e": 18631, "s": 18435, "text": "from torchvision import transformspre_transforms = transforms.Compose([transforms.RandomResizedCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])" }, { "code": null, "e": 18679, "s": 18631, "text": "You can import the model in PyTorch as follows:" }, { "code": null, "e": 18749, "s": 18679, "text": "from torchvision import modelsmodel = models.alexnet(pretrained=True)" }, { "code": null, "e": 18894, "s": 18749, "text": "You can disable the training of the convolutional layers and create your own classifier to override the original AlexNet Fully Connected Layers:" }, { "code": null, "e": 19311, "s": 18894, "text": "from torch import nnfor param in model.parameters(): param.requires_grad = False # disable trainingfcLayersDict = OrderedDict([('fc1', nn.Linear(9216, 1024)), ('relu1', nn.ReLU()), ('fc2', nn.Linear(1024, 102)), ('output', nn.LogSoftmax(dim=1)) ])model.fcLayersDict = fcLayersDictfc = nn.Sequential(fcLayersDict)model.classifier = fc" }, { "code": null, "e": 19578, "s": 19311, "text": "In addition to AlexNet, there are also other models in PyTorch that can be used to classify your own image dataset, given the necessary customizations. It is really recommended to test these models or even build your own CNN from scratch to understand how CNN works." } ]
Count how many times the given digital clock shows identical digits in C++
Suppose we have a digital clock of type HH:MM. Which shows the time in hours and minutes only. We are given a number of hours and minutes as input. The goal is to count the number of times all digits are the same. H=M. This happens 3 times a day, first at 00:00 midnight, then at 11:11 and last at 22:22. As time is represented in 24 hour format. Input: 12 hours 22 minutes. 2 Explanation − For times 00:00 and 11:11. Twice in 12 hours. Input: 48 hours 22 minutes. 5 Explanation − For times 00:00 and 11:11, 22:22 . Variables hours and minutes store the input. Function countIdentical(int hours, int minutes) takes minutes and hours and return count of no. of times all HH;MM digits are the same. For 00:00 initialize count as 1. For each hour as 11 and 22 and minutes as 11 and 22 increment count by 1. Return the result after the loop ends. Count is the desired result. Print the count. Live Demo // C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // examples- 11:11 11hrs 11 mins, 22:22 int countIdentical(int hours, int minutes){ // Initialized to 1 because of 00:00 int i, count=1; // For double digit hours for (i = 0; i <= 99 && i < hours; i = i + 11) { // Double digit minutes if ((i % 10) < minutes) count++; } return count; } int main(){ int hours = 48; int minutes = 22; cout <<"Times when all digits are identical in HH:MM :" << countIdentical(hours, minutes); return 0; } Times when all digits are identical in HH:MM : 6
[ { "code": null, "e": 1281, "s": 1062, "text": "Suppose we have a digital clock of type HH:MM. Which shows the time in hours and minutes\nonly. We are given a number of hours and minutes as input. The goal is to count the number of times all digits are the same. H=M." }, { "code": null, "e": 1409, "s": 1281, "text": "This happens 3 times a day, first at 00:00 midnight, then at 11:11 and last at 22:22. As time is represented in 24 hour format." }, { "code": null, "e": 1437, "s": 1409, "text": "Input: 12 hours 22 minutes." }, { "code": null, "e": 1439, "s": 1437, "text": "2" }, { "code": null, "e": 1499, "s": 1439, "text": "Explanation − For times 00:00 and 11:11. Twice in 12 hours." }, { "code": null, "e": 1527, "s": 1499, "text": "Input: 48 hours 22 minutes." }, { "code": null, "e": 1529, "s": 1527, "text": "5" }, { "code": null, "e": 1578, "s": 1529, "text": "Explanation − For times 00:00 and 11:11, 22:22 ." }, { "code": null, "e": 1623, "s": 1578, "text": "Variables hours and minutes store the input." }, { "code": null, "e": 1759, "s": 1623, "text": "Function countIdentical(int hours, int minutes) takes minutes and hours and return count\nof no. of times all HH;MM digits are the same." }, { "code": null, "e": 1792, "s": 1759, "text": "For 00:00 initialize count as 1." }, { "code": null, "e": 1866, "s": 1792, "text": "For each hour as 11 and 22 and minutes as 11 and 22 increment count by 1." }, { "code": null, "e": 1905, "s": 1866, "text": "Return the result after the loop ends." }, { "code": null, "e": 1934, "s": 1905, "text": "Count is the desired result." }, { "code": null, "e": 1951, "s": 1934, "text": "Print the count." }, { "code": null, "e": 1962, "s": 1951, "text": " Live Demo" }, { "code": null, "e": 2532, "s": 1962, "text": "// C++ implementation of the approach\n#include <bits/stdc++.h>\nusing namespace std;\n// examples- 11:11 11hrs 11 mins, 22:22\nint countIdentical(int hours, int minutes){\n // Initialized to 1 because of 00:00\n int i, count=1;\n // For double digit hours\n for (i = 0; i <= 99 && i < hours; i = i + 11) {\n // Double digit minutes\n if ((i % 10) < minutes)\n count++;\n }\n return count;\n}\nint main(){\n int hours = 48;\n int minutes = 22;\n cout <<\"Times when all digits are identical in HH:MM :\"\n << countIdentical(hours, minutes);\n return 0;\n}" }, { "code": null, "e": 2581, "s": 2532, "text": "Times when all digits are identical in HH:MM : 6" } ]
KL Divergence Python Example. We can think of the KL divergence as... | by Cory Maklin | Towards Data Science
As you progress in your career as a data scientist, you will inevitable come across the Kullback–Leibler (KL) divergence. We can think of the KL divergence as distance metric (although it isn’t symmetric) that quantifies the difference between two probability distributions. One common scenario where this is useful is when we are working with a complex distribution. Rather than working with the distribution directly, we can make our life easier by using another distribution with well known properties (i.e. normal distribution) that does a decent job of describing the data. In other words, we can use the KL divergence to tell whether a poisson distribution or a normal distribution is a better at approximating the data. The KL divergence is also a key component of Gaussian Mixture Models and t-SNE. For distributions P and Q of a continuous random variable, the Kullback-Leibler divergence is computed as an integral. On the other hand, if P and Q represent the probability distribution of a discrete random variable, the Kullback-Leibler divergence is calculated as a summation. To start, we import the following libraries. import numpy as npfrom scipy.stats import normfrom matplotlib import pyplot as pltimport tensorflow as tfimport seaborn as snssns.set() Next, we define a function to calculate the KL divergence of two probability distributions. We need to make sure that we don’t include any probabilities equal to 0 because the log of 0 is negative infinity. def kl_divergence(p, q): return np.sum(np.where(p != 0, p * np.log(p / q), 0)) The KL divergence between a normal distribution with a mean of 0 and a standard deviation of 2 and another distribution with a mean of 2 and a standard deviation of 2 is equal to 500. x = np.arange(-10, 10, 0.001)p = norm.pdf(x, 0, 2)q = norm.pdf(x, 2, 2)plt.title('KL(P||Q) = %1.3f' % kl_divergence(p, q))plt.plot(x, p)plt.plot(x, q, c='red') If we measure the KL divergence between the initial probability distribution and another distribution with a mean of 5 and a standard deviation of 4, we expect the KL divergence to be higher than in the previous example. q = norm.pdf(x, 5, 4)plt.title('KL(P||Q) = %1.3f' % kl_divergence(p, q))plt.plot(x, p)plt.plot(x, q, c='red') It’s important to note that the KL divergence is not symmetrical. In other words, if we switch P for Q and vice versa, we get a different result. q = norm.pdf(x, 5, 4)plt.title('KL(P||Q) = %1.3f' % kl_divergence(q, p))plt.plot(x, p)plt.plot(x, q, c='red') The lower the KL divergence, the closer the two distributions are to one another. Therefore, as in the case of t-SNE and Gaussian Mixture Models, we can estimate the Gaussian parameters of one distribution by minimizing its KL divergence with respect to another. Let’s see how we could go about minimizing the KL divergence between two probability distributions using gradient descent. To begin, we create a probability distribution with a known mean (0) and variance (2). Then, we create another distribution with random parameters. x = np.arange(-10, 10, 0.001)p_pdf = norm.pdf(x, 0, 2).reshape(1, -1)np.random.seed(0)random_mean = np.random.randint(10, size=1)random_sigma = np.random.randint(10, size=1)random_pdf = norm.pdf(x, random_mean, random_sigma).reshape(1, -1) Given that we are using gradient descent, we need to select values for the hyperparameters (i.e. step size, number of iterations). learning_rate = 0.001epochs = 100 Just like numpy, in tensorflow we need to allocate memory for variables. For the variable q, we use the equation for a normal distribution given mu and sigma, only we exclude the part before the exponent since we’re normalizing the result. p = tf.placeholder(tf.float64, shape=pdf.shape)mu = tf.Variable(np.zeros(1))sigma = tf.Variable(np.eye(1))normal = tf.exp(-tf.square(x - mu) / (2 * sigma))q = normal / tf.reduce_sum(normal) Just like before, we define a function to compute the KL divergence that excludes probabilities equal to zero. kl_divergence = tf.reduce_sum( tf.where(p == 0, tf.zeros(pdf.shape, tf.float64), p * tf.log(p / q))) Next, we initialize an instance of the GradientDescentOptimizer class and call the minimize method with the KL divergence function as an argument. optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(kl_divergence) Only after running tf.global_variables_initializer() will the variables hold the values we set when we declared them (i.e. tf.zeros). init = tf.global_variables_initializer() All operations in tensorflow must be done within a session. In the proceeding code block, we minimize the KL divergence using gradient descent. with tf.Session() as sess: sess.run(init) history = [] means = [] variances = [] for i in range(epochs): sess.run(optimizer, { p: pdf }) if i % 10 == 0: history.append(sess.run(kl_divergence, { p: pdf })) means.append(sess.run(mu)[0]) variances.append(sess.run(sigma)[0][0]) for mean, variance in zip(means, variances): q_pdf = norm.pdf(x, mean, np.sqrt(variance)) plt.plot(x, q_pdf.reshape(-1, 1), c='red')plt.title('KL(P||Q) = %1.3f' % history[-1]) plt.plot(x, p_pdf.reshape(-1, 1), linewidth=3) plt.show() plt.plot(history) plt.show() sess.close() Then, we plot the probability distribution and KL divergence at different points in time.
[ { "code": null, "e": 854, "s": 47, "text": "As you progress in your career as a data scientist, you will inevitable come across the Kullback–Leibler (KL) divergence. We can think of the KL divergence as distance metric (although it isn’t symmetric) that quantifies the difference between two probability distributions. One common scenario where this is useful is when we are working with a complex distribution. Rather than working with the distribution directly, we can make our life easier by using another distribution with well known properties (i.e. normal distribution) that does a decent job of describing the data. In other words, we can use the KL divergence to tell whether a poisson distribution or a normal distribution is a better at approximating the data. The KL divergence is also a key component of Gaussian Mixture Models and t-SNE." }, { "code": null, "e": 973, "s": 854, "text": "For distributions P and Q of a continuous random variable, the Kullback-Leibler divergence is computed as an integral." }, { "code": null, "e": 1135, "s": 973, "text": "On the other hand, if P and Q represent the probability distribution of a discrete random variable, the Kullback-Leibler divergence is calculated as a summation." }, { "code": null, "e": 1180, "s": 1135, "text": "To start, we import the following libraries." }, { "code": null, "e": 1316, "s": 1180, "text": "import numpy as npfrom scipy.stats import normfrom matplotlib import pyplot as pltimport tensorflow as tfimport seaborn as snssns.set()" }, { "code": null, "e": 1523, "s": 1316, "text": "Next, we define a function to calculate the KL divergence of two probability distributions. We need to make sure that we don’t include any probabilities equal to 0 because the log of 0 is negative infinity." }, { "code": null, "e": 1605, "s": 1523, "text": "def kl_divergence(p, q): return np.sum(np.where(p != 0, p * np.log(p / q), 0))" }, { "code": null, "e": 1789, "s": 1605, "text": "The KL divergence between a normal distribution with a mean of 0 and a standard deviation of 2 and another distribution with a mean of 2 and a standard deviation of 2 is equal to 500." }, { "code": null, "e": 1949, "s": 1789, "text": "x = np.arange(-10, 10, 0.001)p = norm.pdf(x, 0, 2)q = norm.pdf(x, 2, 2)plt.title('KL(P||Q) = %1.3f' % kl_divergence(p, q))plt.plot(x, p)plt.plot(x, q, c='red')" }, { "code": null, "e": 2170, "s": 1949, "text": "If we measure the KL divergence between the initial probability distribution and another distribution with a mean of 5 and a standard deviation of 4, we expect the KL divergence to be higher than in the previous example." }, { "code": null, "e": 2280, "s": 2170, "text": "q = norm.pdf(x, 5, 4)plt.title('KL(P||Q) = %1.3f' % kl_divergence(p, q))plt.plot(x, p)plt.plot(x, q, c='red')" }, { "code": null, "e": 2426, "s": 2280, "text": "It’s important to note that the KL divergence is not symmetrical. In other words, if we switch P for Q and vice versa, we get a different result." }, { "code": null, "e": 2536, "s": 2426, "text": "q = norm.pdf(x, 5, 4)plt.title('KL(P||Q) = %1.3f' % kl_divergence(q, p))plt.plot(x, p)plt.plot(x, q, c='red')" }, { "code": null, "e": 2799, "s": 2536, "text": "The lower the KL divergence, the closer the two distributions are to one another. Therefore, as in the case of t-SNE and Gaussian Mixture Models, we can estimate the Gaussian parameters of one distribution by minimizing its KL divergence with respect to another." }, { "code": null, "e": 3070, "s": 2799, "text": "Let’s see how we could go about minimizing the KL divergence between two probability distributions using gradient descent. To begin, we create a probability distribution with a known mean (0) and variance (2). Then, we create another distribution with random parameters." }, { "code": null, "e": 3310, "s": 3070, "text": "x = np.arange(-10, 10, 0.001)p_pdf = norm.pdf(x, 0, 2).reshape(1, -1)np.random.seed(0)random_mean = np.random.randint(10, size=1)random_sigma = np.random.randint(10, size=1)random_pdf = norm.pdf(x, random_mean, random_sigma).reshape(1, -1)" }, { "code": null, "e": 3441, "s": 3310, "text": "Given that we are using gradient descent, we need to select values for the hyperparameters (i.e. step size, number of iterations)." }, { "code": null, "e": 3475, "s": 3441, "text": "learning_rate = 0.001epochs = 100" }, { "code": null, "e": 3715, "s": 3475, "text": "Just like numpy, in tensorflow we need to allocate memory for variables. For the variable q, we use the equation for a normal distribution given mu and sigma, only we exclude the part before the exponent since we’re normalizing the result." }, { "code": null, "e": 3905, "s": 3715, "text": "p = tf.placeholder(tf.float64, shape=pdf.shape)mu = tf.Variable(np.zeros(1))sigma = tf.Variable(np.eye(1))normal = tf.exp(-tf.square(x - mu) / (2 * sigma))q = normal / tf.reduce_sum(normal)" }, { "code": null, "e": 4016, "s": 3905, "text": "Just like before, we define a function to compute the KL divergence that excludes probabilities equal to zero." }, { "code": null, "e": 4120, "s": 4016, "text": "kl_divergence = tf.reduce_sum( tf.where(p == 0, tf.zeros(pdf.shape, tf.float64), p * tf.log(p / q)))" }, { "code": null, "e": 4267, "s": 4120, "text": "Next, we initialize an instance of the GradientDescentOptimizer class and call the minimize method with the KL divergence function as an argument." }, { "code": null, "e": 4352, "s": 4267, "text": "optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(kl_divergence)" }, { "code": null, "e": 4486, "s": 4352, "text": "Only after running tf.global_variables_initializer() will the variables hold the values we set when we declared them (i.e. tf.zeros)." }, { "code": null, "e": 4527, "s": 4486, "text": "init = tf.global_variables_initializer()" }, { "code": null, "e": 4671, "s": 4527, "text": "All operations in tensorflow must be done within a session. In the proceeding code block, we minimize the KL divergence using gradient descent." }, { "code": null, "e": 5344, "s": 4671, "text": "with tf.Session() as sess: sess.run(init) history = [] means = [] variances = [] for i in range(epochs): sess.run(optimizer, { p: pdf }) if i % 10 == 0: history.append(sess.run(kl_divergence, { p: pdf })) means.append(sess.run(mu)[0]) variances.append(sess.run(sigma)[0][0]) for mean, variance in zip(means, variances): q_pdf = norm.pdf(x, mean, np.sqrt(variance)) plt.plot(x, q_pdf.reshape(-1, 1), c='red')plt.title('KL(P||Q) = %1.3f' % history[-1]) plt.plot(x, p_pdf.reshape(-1, 1), linewidth=3) plt.show() plt.plot(history) plt.show() sess.close()" } ]
Angular 6 - CLI
Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc. To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same − npm install -g @angular/cli To create a new project, we can run the following command in the command line and the project will be created. ng new PROJECT-NAME cd PROJECT-NAME ng serve // ng serve // will compile and you can see the output of your project in the browser − http://localhost:4200/ 4200 is the default port used when a new project is created. You can change the port with the following command − ng serve --host 0.0.0.0 --port 4201 The following table lists down a few important commands required while working with Angular 4 projects. Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2258, "s": 1995, "text": "Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc." }, { "code": null, "e": 2376, "s": 2258, "text": "To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same −" }, { "code": null, "e": 2405, "s": 2376, "text": "npm install -g @angular/cli\n" }, { "code": null, "e": 2516, "s": 2405, "text": "To create a new project, we can run the following command in the command line and the project will be created." }, { "code": null, "e": 2565, "s": 2516, "text": "ng new PROJECT-NAME\ncd PROJECT-NAME\nng serve //\n" }, { "code": null, "e": 2650, "s": 2565, "text": "ng serve // will compile and you can see the output of your project in the browser −" }, { "code": null, "e": 2674, "s": 2650, "text": "http://localhost:4200/\n" }, { "code": null, "e": 2788, "s": 2674, "text": "4200 is the default port used when a new project is created. You can change the port with the following command −" }, { "code": null, "e": 2825, "s": 2788, "text": "ng serve --host 0.0.0.0 --port 4201\n" }, { "code": null, "e": 2929, "s": 2825, "text": "The following table lists down a few important commands required while working with Angular 4 projects." }, { "code": null, "e": 3063, "s": 2929, "text": "Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts." }, { "code": null, "e": 3098, "s": 3063, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3112, "s": 3098, "text": " Anadi Sharma" }, { "code": null, "e": 3147, "s": 3112, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3161, "s": 3147, "text": " Anadi Sharma" }, { "code": null, "e": 3196, "s": 3161, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3216, "s": 3196, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3251, "s": 3216, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3268, "s": 3251, "text": " Frahaan Hussain" }, { "code": null, "e": 3301, "s": 3268, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3313, "s": 3301, "text": " Senol Atac" }, { "code": null, "e": 3348, "s": 3313, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3360, "s": 3348, "text": " Senol Atac" }, { "code": null, "e": 3367, "s": 3360, "text": " Print" }, { "code": null, "e": 3378, "s": 3367, "text": " Add Notes" } ]
Functions in Julia - GeeksforGeeks
26 Mar, 2020 A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.With Julia’s function, we can write bigger computations but in very fewer lines of code as function support some comprehensive notations. Creating and using functions in Julia is very easy. Functions in Julia can be of multiple types as per the requirement. Some of these types are listed below: A function with single expression A function with multiple expressions A function with no argument A function with variable arguments, etc. Defining a function is as easier as calling a function, just write the predefined keyword function and provide a function_name. A function can be assigned with a single expression to follow or multiple expressions or no expression. It is not necessary to provide expressions to some functions to perform operations. For ex- Mathematical addition operator(+): It can just be called with arguments and the function will return the output as addition of those arguments. Note: Just like looping statements, a function also needs an end statement to mark the closing of the function. Example: # Defining a functionfunction fn() println("this is a function")end # Function callfn() Output: this is a function Functions with arguments can also be created by passing a tuple of arguments. Defining such function is also as above but with a little modification. Also, functions can be assigned with some other names or we can say that function is copied from one name to another. # Defining a function with argumentsfunction add_fn(x, y) println(x + y)end # Assigning another name to functionanother_add = add_fn # Calling defined functionadd_fn(7, 8) # Calling function by new nameanother_add(6, 7) Output: 15 13 A single line function can also be defined using ‘=’(assignment operator). Using such notation is useful as it will save time and lines of source code. # Defining a shorthand functionadd_fn(x, y) = println(x + y) # Function calladd_fn(7, 8) Output: 15 Sometime we want our function to return some value which can further be used for some computation. For returning a value from a function return keyword is used. This will return the computed value as per the instructions defined in the function, to the statement from where the function is being called. A return statement can also be used to compute the operation of the function by just writing the whole operation after the return statement. This will result in fewer lines of code, by not writing the statements to compute and then returning the computed value. # Defining a functionfunction add_fn(x, y) # Defining return statement return x + yend # Function callz = add_fn(1, 9)println(z) Output: 10 The above code will take values of ‘x’ and ‘y’ as arguments and then return them after adding ‘x’ and ‘y’ and will store the returned result in another variable ‘z’ from where the function is being called. Note:Whenever something is returned the function is exited. So the statement after the return statement will not work. Example: # Defining a functionfunction fn(x, y) # Return statement return x * y println("This is not executed")end # Function callout = fn(7, 7) println(out) Output: 49 As in the above code, the output is only what is returned and the statement after return is not executed. There is no need to use return keyword if we are using only a single statement inside out function. This is because Julia automatically returns the output of the last processed statement in the function. # Defining functionfunction f(x, y) x * xendfunction g() println("printed data is returned")end # Function callout1 = f(5, 5)out2 = g() println(out1)println(out2) Output: 25 printed data is returned In Julia, operators can also be used as a function. Operators like +, -, *, etc are functions. Since operators can work as functions we can alias (give another name) to an operator. Note: When assigning an operator to a variable, the statement line needs to be ended with a ;(semicolon). Otherwise an Error will be generated. Example: # Performing addition operation directlya = 50 + 20 + 1println(a) # '+' working as functionb = +(50, 20, 1)println(b) # aliasing operator as functionf = +;println(f(50, 20, 1)) Output: 71 71 71 Sometimes there is no need to think of a name for a function. Julia allows creating functions without a name as well. Now, a problem arises that how to call these functions or how to pass arguments to these functions. Julia provides a keyword ‘ans‘ which automatically refers to the last computed value. This keyword can be used to pass arguments to the anonymous function. Example: # Creating an anonymous functionfunction (x) x^2 + 2x - 1 end # Passing argument to functionans(5) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Getting the maximum value from a list in Julia - max() Method Get array dimensions and size of a dimension in Julia - size() Method Find maximum element along with its index in Julia - findmax() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Searching in Array for a given element in Julia Working with Date and Time in Julia NamedTuple in Julia Exception handling in Julia Variables in Julia Getting last element of an array in Julia - last() Method
[ { "code": null, "e": 24464, "s": 24436, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24842, "s": 24464, "text": "A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.With Julia’s function, we can write bigger computations but in very fewer lines of code as function support some comprehensive notations. Creating and using functions in Julia is very easy." }, { "code": null, "e": 24948, "s": 24842, "text": "Functions in Julia can be of multiple types as per the requirement. Some of these types are listed below:" }, { "code": null, "e": 24982, "s": 24948, "text": "A function with single expression" }, { "code": null, "e": 25019, "s": 24982, "text": "A function with multiple expressions" }, { "code": null, "e": 25047, "s": 25019, "text": "A function with no argument" }, { "code": null, "e": 25088, "s": 25047, "text": "A function with variable arguments, etc." }, { "code": null, "e": 25556, "s": 25088, "text": "Defining a function is as easier as calling a function, just write the predefined keyword function and provide a function_name. A function can be assigned with a single expression to follow or multiple expressions or no expression. It is not necessary to provide expressions to some functions to perform operations. For ex- Mathematical addition operator(+): It can just be called with arguments and the function will return the output as addition of those arguments." }, { "code": null, "e": 25668, "s": 25556, "text": "Note: Just like looping statements, a function also needs an end statement to mark the closing of the function." }, { "code": null, "e": 25677, "s": 25668, "text": "Example:" }, { "code": "# Defining a functionfunction fn() println(\"this is a function\")end # Function callfn()", "e": 25769, "s": 25677, "text": null }, { "code": null, "e": 25777, "s": 25769, "text": "Output:" }, { "code": null, "e": 25797, "s": 25777, "text": "this is a function\n" }, { "code": null, "e": 26065, "s": 25797, "text": "Functions with arguments can also be created by passing a tuple of arguments. Defining such function is also as above but with a little modification. Also, functions can be assigned with some other names or we can say that function is copied from one name to another." }, { "code": "# Defining a function with argumentsfunction add_fn(x, y) println(x + y)end # Assigning another name to functionanother_add = add_fn # Calling defined functionadd_fn(7, 8) # Calling function by new nameanother_add(6, 7)", "e": 26291, "s": 26065, "text": null }, { "code": null, "e": 26299, "s": 26291, "text": "Output:" }, { "code": null, "e": 26306, "s": 26299, "text": "15\n13\n" }, { "code": null, "e": 26458, "s": 26306, "text": "A single line function can also be defined using ‘=’(assignment operator). Using such notation is useful as it will save time and lines of source code." }, { "code": "# Defining a shorthand functionadd_fn(x, y) = println(x + y) # Function calladd_fn(7, 8)", "e": 26548, "s": 26458, "text": null }, { "code": null, "e": 26556, "s": 26548, "text": "Output:" }, { "code": null, "e": 26560, "s": 26556, "text": "15\n" }, { "code": null, "e": 27126, "s": 26560, "text": "Sometime we want our function to return some value which can further be used for some computation. For returning a value from a function return keyword is used. This will return the computed value as per the instructions defined in the function, to the statement from where the function is being called. A return statement can also be used to compute the operation of the function by just writing the whole operation after the return statement. This will result in fewer lines of code, by not writing the statements to compute and then returning the computed value." }, { "code": "# Defining a functionfunction add_fn(x, y) # Defining return statement return x + yend # Function callz = add_fn(1, 9)println(z)", "e": 27264, "s": 27126, "text": null }, { "code": null, "e": 27272, "s": 27264, "text": "Output:" }, { "code": null, "e": 27276, "s": 27272, "text": "10\n" }, { "code": null, "e": 27482, "s": 27276, "text": "The above code will take values of ‘x’ and ‘y’ as arguments and then return them after adding ‘x’ and ‘y’ and will store the returned result in another variable ‘z’ from where the function is being called." }, { "code": null, "e": 27601, "s": 27482, "text": "Note:Whenever something is returned the function is exited. So the statement after the return statement will not work." }, { "code": null, "e": 27610, "s": 27601, "text": "Example:" }, { "code": "# Defining a functionfunction fn(x, y) # Return statement return x * y println(\"This is not executed\")end # Function callout = fn(7, 7) println(out)", "e": 27772, "s": 27610, "text": null }, { "code": null, "e": 27780, "s": 27772, "text": "Output:" }, { "code": null, "e": 27784, "s": 27780, "text": "49\n" }, { "code": null, "e": 27890, "s": 27784, "text": "As in the above code, the output is only what is returned and the statement after return is not executed." }, { "code": null, "e": 28094, "s": 27890, "text": "There is no need to use return keyword if we are using only a single statement inside out function. This is because Julia automatically returns the output of the last processed statement in the function." }, { "code": "# Defining functionfunction f(x, y) x * xendfunction g() println(\"printed data is returned\")end # Function callout1 = f(5, 5)out2 = g() println(out1)println(out2)", "e": 28265, "s": 28094, "text": null }, { "code": null, "e": 28273, "s": 28265, "text": "Output:" }, { "code": null, "e": 28302, "s": 28273, "text": "25\nprinted data is returned\n" }, { "code": null, "e": 28484, "s": 28302, "text": "In Julia, operators can also be used as a function. Operators like +, -, *, etc are functions. Since operators can work as functions we can alias (give another name) to an operator." }, { "code": null, "e": 28628, "s": 28484, "text": "Note: When assigning an operator to a variable, the statement line needs to be ended with a ;(semicolon). Otherwise an Error will be generated." }, { "code": null, "e": 28637, "s": 28628, "text": "Example:" }, { "code": "# Performing addition operation directlya = 50 + 20 + 1println(a) # '+' working as functionb = +(50, 20, 1)println(b) # aliasing operator as functionf = +;println(f(50, 20, 1))", "e": 28816, "s": 28637, "text": null }, { "code": null, "e": 28824, "s": 28816, "text": "Output:" }, { "code": null, "e": 28834, "s": 28824, "text": "71\n71\n71\n" }, { "code": null, "e": 29208, "s": 28834, "text": "Sometimes there is no need to think of a name for a function. Julia allows creating functions without a name as well. Now, a problem arises that how to call these functions or how to pass arguments to these functions. Julia provides a keyword ‘ans‘ which automatically refers to the last computed value. This keyword can be used to pass arguments to the anonymous function." }, { "code": null, "e": 29217, "s": 29208, "text": "Example:" }, { "code": "# Creating an anonymous functionfunction (x) x^2 + 2x - 1 end # Passing argument to functionans(5)", "e": 29333, "s": 29217, "text": null }, { "code": null, "e": 29341, "s": 29333, "text": "Output:" }, { "code": null, "e": 29347, "s": 29341, "text": "Julia" }, { "code": null, "e": 29445, "s": 29347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29454, "s": 29445, "text": "Comments" }, { "code": null, "e": 29467, "s": 29454, "text": "Old Comments" }, { "code": null, "e": 29529, "s": 29467, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 29599, "s": 29529, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 29669, "s": 29599, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 29742, "s": 29669, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 29790, "s": 29742, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 29826, "s": 29790, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 29846, "s": 29826, "text": "NamedTuple in Julia" }, { "code": null, "e": 29874, "s": 29846, "text": "Exception handling in Julia" }, { "code": null, "e": 29893, "s": 29874, "text": "Variables in Julia" } ]
Python Program for Merge Sort
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given an array, we need to sort it using the concept of merge sort Here we place the maximum element at the end. This is repeated until the array is sorted. Now let’s observe the solution in the implementation below − #merge function def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # create arrays L = [0] * (n1) R = [0] * (n2) # Copy data to arrays for i in range(0 , n1): L[i] = arr[l + i] for j in range(0 , n2): R[j] = arr[m + 1 + j] i = 0 # first half of array j = 0 # second half of array k = l # merges two halves while i < n1 and j < n2 : if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # copy the left out elements of left half while i < n1: arr[k] = L[i] i += 1 k += 1 # copy the left out elements of right half while j < n2: arr[k] = R[j] j += 1 k += 1 # sort def mergeSort(arr,l,r): if l < r: # getting the average m = (l+(r-1))/2 # Sort mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) # main arr = [2,5,3,8,6,5,4,7] n = len(arr) mergeSort(arr,0,n-1) print ("Sorted array is") for i in range(n): print (arr[i],end=" ") Sorted array is 2 3 4 5 5 6 7 8 All the variables are declared in the local scope and their references are seen in the figure above. In this article, we have learned about how we can make a Python Program for Merge Sort
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1244, "s": 1150, "text": "Problem statement − We are given an array, we need to sort it using the concept of merge sort" }, { "code": null, "e": 1334, "s": 1244, "text": "Here we place the maximum element at the end. This is repeated until the array is sorted." }, { "code": null, "e": 1395, "s": 1334, "text": "Now let’s observe the solution in the implementation below −" }, { "code": null, "e": 2442, "s": 1395, "text": "#merge function\ndef merge(arr, l, m, r):\n n1 = m - l + 1\n n2 = r- m\n # create arrays\n L = [0] * (n1)\n R = [0] * (n2)\n # Copy data to arrays\n for i in range(0 , n1):\n L[i] = arr[l + i]\n for j in range(0 , n2):\n R[j] = arr[m + 1 + j]\n i = 0 # first half of array\n j = 0 # second half of array\n k = l # merges two halves\n while i < n1 and j < n2 :\n if L[i] <= R[j]:\n arr[k] = L[i]\n i += 1\n else:\n arr[k] = R[j]\n j += 1\n k += 1\n # copy the left out elements of left half\n while i < n1:\n arr[k] = L[i]\n i += 1\n k += 1\n # copy the left out elements of right half\n while j < n2:\n arr[k] = R[j]\n j += 1\n k += 1\n# sort\ndef mergeSort(arr,l,r):\n if l < r:\n # getting the average\n m = (l+(r-1))/2\n # Sort\n mergeSort(arr, l, m)\n mergeSort(arr, m+1, r)\n merge(arr, l, m, r)\n# main\narr = [2,5,3,8,6,5,4,7]\nn = len(arr)\nmergeSort(arr,0,n-1)\nprint (\"Sorted array is\")\nfor i in range(n):\n print (arr[i],end=\" \")" }, { "code": null, "e": 2474, "s": 2442, "text": "Sorted array is\n2 3 4 5 5 6 7 8" }, { "code": null, "e": 2575, "s": 2474, "text": "All the variables are declared in the local scope and their references are seen in the figure above." }, { "code": null, "e": 2662, "s": 2575, "text": "In this article, we have learned about how we can make a Python Program for Merge Sort" } ]
MapStruct - Custom Mapping
We can add custom methods as well to the Mapper created using org.mapstruct.Mapper annotation. We can create abstract class as well intead of an Interface. Mapstruct automatically creates the corresponding mapper class. Now create a default conversion method in interface. @Mapper public interface StudentMapper { default Student getModelFromEntity(StudentEntity studentEntity){ Student student = new Student(); student.setId(studentEntity.getId()); student.setName(studentEntity.getName()); student.setClassName(studentEntity.getClassVal()); return student; } } In similar fashion, we can create an abstract class as well as a mapper. @Mapper public absgract class StudentMapper { Student getModelFromEntity(StudentEntity studentEntity){ Student student = new Student(); student.setId(studentEntity.getId()); student.setName(studentEntity.getName()); student.setClassName(studentEntity.getClassVal()); return student; } } Open project mapping as updated in Basic Mapping chapter in Eclipse. Student.java package com.tutorialspoint.model; public class Student { private int id; private String name; private String className; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } } StudentEntity.java package com.tutorialspoint.entity; public class StudentEntity { private int id; private String name; private String classVal; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassVal() { return classVal; } public void setClassVal(String classVal) { this.classVal = classVal; } } StudentMapper.java package com.tutorialspoint.mapper; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import com.tutorialspoint.entity.StudentEntity; import com.tutorialspoint.model.Student; @Mapper public interface StudentMapper { default Student getModelFromEntity(StudentEntity studentEntity){ Student student = new Student(); student.setId(studentEntity.getId()); student.setName(studentEntity.getName()); student.setClassName(studentEntity.getClassVal()); return student; } @Mapping(target="classVal", source="className") StudentEntity getEntityFromModel(Student student); } StudentMapperTest.java package com.tutorialspoint.mapping; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import com.tutorialspoint.entity.StudentEntity; import com.tutorialspoint.mapper.StudentMapper; import com.tutorialspoint.model.Student; public class StudentMapperTest { private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class); @Test public void testEntityToModel() { StudentEntity entity = new StudentEntity(); entity.setClassVal("X"); entity.setName("John"); entity.setId(1); Student model = studentMapper.getModelFromEntity(entity); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } @Test public void testModelToEntity() { Student model = new Student(); model.setId(1); model.setName("John"); model.setClassName("X"); StudentEntity entity = studentMapper.getEntityFromModel(model); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } } Run the following command to test the mappings. mvn clean test Once command is successful. Verify the output. mvn clean test [INFO] Scanning for projects... ... [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping --- [INFO] Surefire report directory: \mvn\mapping\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.tutorialspoint.mapping.StudentMapperTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec ... Print Add Notes Bookmark this page
[ { "code": null, "e": 2480, "s": 2260, "text": "We can add custom methods as well to the Mapper created using org.mapstruct.Mapper annotation. We can create abstract class as well intead of an Interface. Mapstruct automatically creates the corresponding mapper class." }, { "code": null, "e": 2533, "s": 2480, "text": "Now create a default conversion method in interface." }, { "code": null, "e": 2859, "s": 2533, "text": "@Mapper\npublic interface StudentMapper {\n default Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n}" }, { "code": null, "e": 2932, "s": 2859, "text": "In similar fashion, we can create an abstract class as well as a mapper." }, { "code": null, "e": 3255, "s": 2932, "text": "@Mapper\npublic absgract class StudentMapper {\n Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n}" }, { "code": null, "e": 3324, "s": 3255, "text": "Open project mapping as updated in Basic Mapping chapter in Eclipse." }, { "code": null, "e": 3337, "s": 3324, "text": "Student.java" }, { "code": null, "e": 3842, "s": 3337, "text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n}" }, { "code": null, "e": 3861, "s": 3842, "text": "StudentEntity.java" }, { "code": null, "e": 4365, "s": 3861, "text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n}" }, { "code": null, "e": 4384, "s": 4365, "text": "StudentMapper.java" }, { "code": null, "e": 5000, "s": 4384, "text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n default Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n @Mapping(target=\"classVal\", source=\"className\")\n StudentEntity getEntityFromModel(Student student);\n}" }, { "code": null, "e": 5023, "s": 5000, "text": "StudentMapperTest.java" }, { "code": null, "e": 6277, "s": 5023, "text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n Student model = studentMapper.getModelFromEntity(entity);\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n}" }, { "code": null, "e": 6325, "s": 6277, "text": "Run the following command to test the mappings." }, { "code": null, "e": 6341, "s": 6325, "text": "mvn clean test\n" }, { "code": null, "e": 6388, "s": 6341, "text": "Once command is successful. Verify the output." }, { "code": null, "e": 6840, "s": 6388, "text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec\n...\n" }, { "code": null, "e": 6847, "s": 6840, "text": " Print" }, { "code": null, "e": 6858, "s": 6847, "text": " Add Notes" } ]
C++ Program to Find median in row wise sorted matrix
11 Jan, 2022 We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: Input : 1 3 5 2 6 9 3 6 9 Output : Median is 5 If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9) Input: 1 3 4 2 5 6 7 8 9 Output: Median is 5 Simple Method: The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers which are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach: Algorithm: First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max.For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number. First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row. Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max. For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number. Below is the implementation of the above approach: C++ // C++ program to find median of a matrix// sorted row wise#include<bits/stdc++.h>using namespace std; const int MAX = 100; // function to find median in the matrixint binaryMedian(int m[][MAX], int r ,int c){ int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min;} // driver program to check above functionsint main(){ int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << "Median is " << binaryMedian(m, r, c) << endl; return 0;} Output: Median is 5 Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations. Auxiliary Space : O(1) Please refer complete article on Find median in row wise sorted matrix for more details! Binary Search median-finding Order-Statistics statistical-algorithms C++ C++ Programs Matrix Matrix Binary Search CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 175, "s": 28, "text": "We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: " }, { "code": null, "e": 367, "s": 175, "text": "Input : 1 3 5\n 2 6 9\n 3 6 9\nOutput : Median is 5\nIf we put all the values in a sorted \narray A[] = 1 2 3 3 5 6 6 9 9)\n\nInput: 1 3 4\n 2 5 6\n 7 8 9\nOutput: Median is 5" }, { "code": null, "e": 1029, "s": 367, "text": "Simple Method: The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers which are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach: Algorithm: " }, { "code": null, "e": 1818, "s": 1029, "text": "First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max.For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number." }, { "code": null, "e": 2056, "s": 1818, "text": "First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row." }, { "code": null, "e": 2251, "s": 2056, "text": "Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than our mid. And accordingly change the min or max." }, { "code": null, "e": 2609, "s": 2251, "text": "For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number." }, { "code": null, "e": 2661, "s": 2609, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2665, "s": 2661, "text": "C++" }, { "code": "// C++ program to find median of a matrix// sorted row wise#include<bits/stdc++.h>using namespace std; const int MAX = 100; // function to find median in the matrixint binaryMedian(int m[][MAX], int r ,int c){ int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min;} // driver program to check above functionsint main(){ int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << \"Median is \" << binaryMedian(m, r, c) << endl; return 0;}", "e": 3712, "s": 2665, "text": null }, { "code": null, "e": 3722, "s": 3712, "text": "Output: " }, { "code": null, "e": 3734, "s": 3722, "text": "Median is 5" }, { "code": null, "e": 4027, "s": 3734, "text": "Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations. Auxiliary Space : O(1) " }, { "code": null, "e": 4116, "s": 4027, "text": "Please refer complete article on Find median in row wise sorted matrix for more details!" }, { "code": null, "e": 4130, "s": 4116, "text": "Binary Search" }, { "code": null, "e": 4145, "s": 4130, "text": "median-finding" }, { "code": null, "e": 4162, "s": 4145, "text": "Order-Statistics" }, { "code": null, "e": 4185, "s": 4162, "text": "statistical-algorithms" }, { "code": null, "e": 4189, "s": 4185, "text": "C++" }, { "code": null, "e": 4202, "s": 4189, "text": "C++ Programs" }, { "code": null, "e": 4209, "s": 4202, "text": "Matrix" }, { "code": null, "e": 4216, "s": 4209, "text": "Matrix" }, { "code": null, "e": 4230, "s": 4216, "text": "Binary Search" }, { "code": null, "e": 4234, "s": 4230, "text": "CPP" } ]
Sort the words in lexicographical order in Python
17 Aug, 2018 Given a strings, we need to sort the words in lexicographical order (dictionary order). Examples : Input : "hello python program how are you" Output : are hello how program python you Input : "Coders loves the algorithms" Output : Coders algorithms loves the Note: The words which have first letter is capital letter they will print according alphabetical manner. Approach :Approach used in this program is very simple. Split the strings using split() function. After that sort the words in lexicographical order using sort(). Iterate the words through loop and print each word, which are already sorted. # Python program to sort the words in lexicographical# order def sortLexo(my_string): # Split the my_string till where space is found. words = my_string.split() # sort() will sort the strings. words.sort() # Iterate i through 'words' to print the words # in alphabetical manner. for i in words: print( i ) # Driver code if __name__ == '__main__': my_string = "hello this is example how to sort " \ "the word in alphabetical manner" # Calling function sortLexo(my_string) Output : alphabetical example hello how in is manner sort the this to word lexicographic-ordering python-string Python Sorting Technical Scripter Sorting 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() Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Aug, 2018" }, { "code": null, "e": 140, "s": 52, "text": "Given a strings, we need to sort the words in lexicographical order (dictionary order)." }, { "code": null, "e": 151, "s": 140, "text": "Examples :" }, { "code": null, "e": 398, "s": 151, "text": "Input : \"hello python program how are you\"\nOutput : are\n hello\n how\n program\n python\n you\n\nInput : \"Coders loves the algorithms\"\nOutput : Coders\n algorithms\n loves\n the\n" }, { "code": null, "e": 503, "s": 398, "text": "Note: The words which have first letter is capital letter they will print according alphabetical manner." }, { "code": null, "e": 744, "s": 503, "text": "Approach :Approach used in this program is very simple. Split the strings using split() function. After that sort the words in lexicographical order using sort(). Iterate the words through loop and print each word, which are already sorted." }, { "code": "# Python program to sort the words in lexicographical# order def sortLexo(my_string): # Split the my_string till where space is found. words = my_string.split() # sort() will sort the strings. words.sort() # Iterate i through 'words' to print the words # in alphabetical manner. for i in words: print( i ) # Driver code if __name__ == '__main__': my_string = \"hello this is example how to sort \" \\ \"the word in alphabetical manner\" # Calling function sortLexo(my_string)", "e": 1284, "s": 744, "text": null }, { "code": null, "e": 1293, "s": 1284, "text": "Output :" }, { "code": null, "e": 1360, "s": 1293, "text": "alphabetical\nexample\nhello\nhow\nin\nis\nmanner\nsort\nthe\nthis\nto\nword\n" }, { "code": null, "e": 1383, "s": 1360, "text": "lexicographic-ordering" }, { "code": null, "e": 1397, "s": 1383, "text": "python-string" }, { "code": null, "e": 1404, "s": 1397, "text": "Python" }, { "code": null, "e": 1412, "s": 1404, "text": "Sorting" }, { "code": null, "e": 1431, "s": 1412, "text": "Technical Scripter" }, { "code": null, "e": 1439, "s": 1431, "text": "Sorting" }, { "code": null, "e": 1537, "s": 1439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1555, "s": 1537, "text": "Python Dictionary" }, { "code": null, "e": 1597, "s": 1555, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1619, "s": 1597, "text": "Enumerate() in Python" }, { "code": null, "e": 1654, "s": 1619, "text": "Read a file line by line in Python" }, { "code": null, "e": 1680, "s": 1654, "text": "Python String | replace()" }, { "code": null, "e": 1691, "s": 1680, "text": "Merge Sort" }, { "code": null, "e": 1713, "s": 1691, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 1723, "s": 1713, "text": "QuickSort" }, { "code": null, "e": 1738, "s": 1723, "text": "Insertion Sort" } ]
Node.js File System
08 Oct, 2021 Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js helps developers to write JavaScript code to run on the server-side, to generate dynamic content and deliver to the web clients. The two features that make Node.js stand-out are: Event-driven Non-blocking I/O model About Node.js file system: To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS (File System). Node.js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements. To use this File System module, use the require() method: var fs = require('fs'); Common use for File System module: Read Files Write Files Append Files Close Files Delete Files What is Synchronous and Asynchronous approach? Synchronous approach: They are called blocking functions as it waits for each operation to complete, only after that, it executes the next operation, hence blocking the next command from execution i.e. a command will not be executed until & unless the query has finished executing to get all the result from previous commands. Asynchronous approach: They are called non-blocking functions as it never waits for each operation to complete, rather it executes all operations in the first go itself. The result of each operation will be handled once the result is available i.e. each command will be executed soon after the execution of the previous command. While the previous command runs in the background and loads the result once it is finished processing the data. Use cases:If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.In an Asynchronous way, you can show some progress indicator to the user while in the background you can continue with your heavyweight works. This is an ideal scenario for GUI based apps. If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way. In an Asynchronous way, you can show some progress indicator to the user while in the background you can continue with your heavyweight works. This is an ideal scenario for GUI based apps. Example of asynchronous and synchronous: Create a text file named input.txt with the following content:GeeksforGeeks: A computer science portalNow let us create a js file named main.js with the following code:var fs = require("fs"); // Asynchronous readfs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString());});Output:Asynchronous read: GeeksforGeeks: A computer science portalvar fs = require("fs"); // Synchronous readvar data = fs.readFileSync('input.txt');console.log("Synchronous read: " + data.toString());Output:Synchronous read: GeeksforGeeks: A computer science portal GeeksforGeeks: A computer science portal Now let us create a js file named main.js with the following code: var fs = require("fs"); // Asynchronous readfs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString());}); Output: Asynchronous read: GeeksforGeeks: A computer science portal var fs = require("fs"); // Synchronous readvar data = fs.readFileSync('input.txt');console.log("Synchronous read: " + data.toString()); Output: Synchronous read: GeeksforGeeks: A computer science portal Open a File: The fs.open() method is used to create, read, or write a file. The fs.readFile() method is only for reading the file and fs.writeFile() method is only for writing to the file, whereas fs.open() method does several operations on a file. First, we need to load the fs class which is a module to access the physical file system. Syntax: fs.open(path, flags, mode, callback) Parameters: path: It holds the name of the file to read or the entire path if stored at other locations. flags: Flags indicate the behavior of the file to be opened. All possible values are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+). mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite. callback:It is a callback function that is called after reading a file. It takes two parameters: It is a callback function that is called after reading a file. It takes two parameters: err: If any error occurs. data: Contents of the file. It is called after the open operation is executed. Example: Let us create a js file named main.js having the following code to open a file input.txt for reading and writing. var fs = require("fs"); // Asynchronous - Opening Fileconsole.log("opening file!");fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File open successfully"); }); Output: opening file! File open successfully Reading a File: The fs.read() method is used to read the file specified by fd. This method reads the entire file into the buffer. Syntax: fs.read(fd, buffer, offset, length, position, callback) Parameters: fd: This is the file descriptor returned by fs.open() method. buffer: This is the buffer that the data will be written to. offset: This is the offset in the buffer to start writing at. length: This is an integer specifying the number of bytes to read. position: This is an integer specifying where to begin reading from in the file. If the position is null, data will be read from the current file position. callback: It is a callback function that is called after reading of the file. It takes two parameters:err: If any error occurs.data: Contents of the file. err: If any error occurs. data: Contents of the file. Example: Let us create a js file named main.js having the following code: var fs = require("fs");var buf = new Buffer(1024); console.log("opening an existing file");fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("reading the file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } console.log(bytes + " bytes read"); // Print only read bytes to avoid junk. if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } });}); Output: opening an existing file File opened successfully! reading the file GeeksforGeeks: A computer science portal Writing to a File: This method will overwrite the file if the file already exists. The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method. Syntax: fs.writeFile(path, data, options, callback) Parameters: path: It is a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to fs.write() method. data: It is a string, Buffer, TypedArray, or DataView that will be written to the file. options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer value that specifies the file mode. The default value is 0o666.flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’. encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’. mode: It is an integer value that specifies the file mode. The default value is 0o666. flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’. callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails. err: It is an error that would be thrown if the operation fails. Example: Let us create a js file named main.js having the following code: var fs = require("fs"); console.log("writing into existing file");fs.writeFile('input.txt', 'Geeks For Geeks', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("Let's read newly written data"); fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); });}); Output: writing into existing file Data written successfully! Let's read newly written data Asynchronous read: Geeks For Geeks Appending to a File: The fs.appendFile() method is used to synchronously append the data to the file. Syntax: fs.appendFile(filepath, data, options, callback); or fs.appendFileSync(filepath, data, options); Parameters: filepath: It is a String that specifies the file path. data: It is mandatory and it contains the data that you append to the file. options: It is an optional parameter that specifies the encoding/mode/flag. Callback: Function is mandatory and is called when appending data to file is completed. Example 1: Let us create a js file named main.js having the following code: var fs = require('fs'); var data = "\nLearn Node.js"; // Append data to filefs.appendFile('input.txt', data, 'utf8', // Callback function function(err) { if (err) throw err; // If no error console.log("Data is appended to file successfully.")}); Output: Data is appended to file successfully. Example 1: For synchronously appending var fs = require('fs'); var data = "\nLearn Node.js"; // Append data to filefs.appendFileSync('input.txt', data, 'utf8');console.log("Data is appended to file successfully.") Output: Data is appended to file successfully. Before Appending Data to input.txt file:GeeksforGeeks: A computer science portal GeeksforGeeks: A computer science portal After Appending Data to input.txt file:GeeksforGeeks: A computer science portal Learn Node.js GeeksforGeeks: A computer science portal Learn Node.js Closing the File: The fs.close() method is used to asynchronously close the given file descriptor thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for other files. Calling fs.close() on a file descriptor while some other operation is being performed on it may lead to undefined behavior. Syntax: fs.close(fd, callback) Parameters: fd: It is an integer that denotes the file descriptor of the file for which to be closed. callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails. err: It is an error that would be thrown if the method fails. Example: Let us create a js file named main.js having the following code: // Close the opened file.fs.close(fd, function(err) { if (err) { console.log(err); } console.log("File closed successfully.");} Output: File closed successfully. Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory. Syntax: fs.unlink(path, callback) Parameters: path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed. callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails. err: It is an error that would be thrown if the method fails. Example: Let us create a js file named main.js having the following code: var fs = require("fs"); console.log("deleting an existing file");fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log("File deleted successfully!");}); Output: deleting an existing file File deleted successfully! Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Oct, 2021" }, { "code": null, "e": 261, "s": 52, "text": "Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js helps developers to write JavaScript code to run on the server-side, to generate dynamic content and deliver to the web clients." }, { "code": null, "e": 311, "s": 261, "text": "The two features that make Node.js stand-out are:" }, { "code": null, "e": 324, "s": 311, "text": "Event-driven" }, { "code": null, "e": 347, "s": 324, "text": "Non-blocking I/O model" }, { "code": null, "e": 708, "s": 347, "text": "About Node.js file system: To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS (File System). Node.js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements." }, { "code": null, "e": 766, "s": 708, "text": "To use this File System module, use the require() method:" }, { "code": null, "e": 790, "s": 766, "text": "var fs = require('fs');" }, { "code": null, "e": 825, "s": 790, "text": "Common use for File System module:" }, { "code": null, "e": 836, "s": 825, "text": "Read Files" }, { "code": null, "e": 848, "s": 836, "text": "Write Files" }, { "code": null, "e": 861, "s": 848, "text": "Append Files" }, { "code": null, "e": 873, "s": 861, "text": "Close Files" }, { "code": null, "e": 886, "s": 873, "text": "Delete Files" }, { "code": null, "e": 933, "s": 886, "text": "What is Synchronous and Asynchronous approach?" }, { "code": null, "e": 1260, "s": 933, "text": "Synchronous approach: They are called blocking functions as it waits for each operation to complete, only after that, it executes the next operation, hence blocking the next command from execution i.e. a command will not be executed until & unless the query has finished executing to get all the result from previous commands." }, { "code": null, "e": 1701, "s": 1260, "text": "Asynchronous approach: They are called non-blocking functions as it never waits for each operation to complete, rather it executes all operations in the first go itself. The result of each operation will be handled once the result is available i.e. each command will be executed soon after the execution of the previous command. While the previous command runs in the background and loads the result once it is finished processing the data." }, { "code": null, "e": 2046, "s": 1701, "text": "Use cases:If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.In an Asynchronous way, you can show some progress indicator to the user while in the background you can continue with your heavyweight works. This is an ideal scenario for GUI based apps." }, { "code": null, "e": 2193, "s": 2046, "text": "If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way." }, { "code": null, "e": 2382, "s": 2193, "text": "In an Asynchronous way, you can show some progress indicator to the user while in the background you can continue with your heavyweight works. This is an ideal scenario for GUI based apps." }, { "code": null, "e": 3059, "s": 2382, "text": "Example of asynchronous and synchronous: Create a text file named input.txt with the following content:GeeksforGeeks: A computer science portalNow let us create a js file named main.js with the following code:var fs = require(\"fs\"); // Asynchronous readfs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log(\"Asynchronous read: \" + data.toString());});Output:Asynchronous read: GeeksforGeeks: A computer science portalvar fs = require(\"fs\"); // Synchronous readvar data = fs.readFileSync('input.txt');console.log(\"Synchronous read: \" + data.toString());Output:Synchronous read: GeeksforGeeks: A computer science portal" }, { "code": null, "e": 3100, "s": 3059, "text": "GeeksforGeeks: A computer science portal" }, { "code": null, "e": 3167, "s": 3100, "text": "Now let us create a js file named main.js with the following code:" }, { "code": "var fs = require(\"fs\"); // Asynchronous readfs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log(\"Asynchronous read: \" + data.toString());});", "e": 3368, "s": 3167, "text": null }, { "code": null, "e": 3376, "s": 3368, "text": "Output:" }, { "code": null, "e": 3436, "s": 3376, "text": "Asynchronous read: GeeksforGeeks: A computer science portal" }, { "code": "var fs = require(\"fs\"); // Synchronous readvar data = fs.readFileSync('input.txt');console.log(\"Synchronous read: \" + data.toString());", "e": 3573, "s": 3436, "text": null }, { "code": null, "e": 3581, "s": 3573, "text": "Output:" }, { "code": null, "e": 3640, "s": 3581, "text": "Synchronous read: GeeksforGeeks: A computer science portal" }, { "code": null, "e": 3979, "s": 3640, "text": "Open a File: The fs.open() method is used to create, read, or write a file. The fs.readFile() method is only for reading the file and fs.writeFile() method is only for writing to the file, whereas fs.open() method does several operations on a file. First, we need to load the fs class which is a module to access the physical file system." }, { "code": null, "e": 3987, "s": 3979, "text": "Syntax:" }, { "code": null, "e": 4024, "s": 3987, "text": "fs.open(path, flags, mode, callback)" }, { "code": null, "e": 4036, "s": 4024, "text": "Parameters:" }, { "code": null, "e": 4129, "s": 4036, "text": "path: It holds the name of the file to read or the entire path if stored at other locations." }, { "code": null, "e": 4265, "s": 4129, "text": "flags: Flags indicate the behavior of the file to be opened. All possible values are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+)." }, { "code": null, "e": 4363, "s": 4265, "text": "mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite." }, { "code": null, "e": 4460, "s": 4363, "text": "callback:It is a callback function that is called after reading a file. It takes two parameters:" }, { "code": null, "e": 4548, "s": 4460, "text": "It is a callback function that is called after reading a file. It takes two parameters:" }, { "code": null, "e": 4574, "s": 4548, "text": "err: If any error occurs." }, { "code": null, "e": 4653, "s": 4574, "text": "data: Contents of the file. It is called after the open operation is executed." }, { "code": null, "e": 4776, "s": 4653, "text": "Example: Let us create a js file named main.js having the following code to open a file input.txt for reading and writing." }, { "code": "var fs = require(\"fs\"); // Asynchronous - Opening Fileconsole.log(\"opening file!\");fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log(\"File open successfully\"); });", "e": 5005, "s": 4776, "text": null }, { "code": null, "e": 5013, "s": 5005, "text": "Output:" }, { "code": null, "e": 5050, "s": 5013, "text": "opening file!\nFile open successfully" }, { "code": null, "e": 5180, "s": 5050, "text": "Reading a File: The fs.read() method is used to read the file specified by fd. This method reads the entire file into the buffer." }, { "code": null, "e": 5188, "s": 5180, "text": "Syntax:" }, { "code": null, "e": 5244, "s": 5188, "text": "fs.read(fd, buffer, offset, length, position, callback)" }, { "code": null, "e": 5256, "s": 5244, "text": "Parameters:" }, { "code": null, "e": 5318, "s": 5256, "text": "fd: This is the file descriptor returned by fs.open() method." }, { "code": null, "e": 5379, "s": 5318, "text": "buffer: This is the buffer that the data will be written to." }, { "code": null, "e": 5441, "s": 5379, "text": "offset: This is the offset in the buffer to start writing at." }, { "code": null, "e": 5508, "s": 5441, "text": "length: This is an integer specifying the number of bytes to read." }, { "code": null, "e": 5664, "s": 5508, "text": "position: This is an integer specifying where to begin reading from in the file. If the position is null, data will be read from the current file position." }, { "code": null, "e": 5819, "s": 5664, "text": "callback: It is a callback function that is called after reading of the file. It takes two parameters:err: If any error occurs.data: Contents of the file." }, { "code": null, "e": 5845, "s": 5819, "text": "err: If any error occurs." }, { "code": null, "e": 5873, "s": 5845, "text": "data: Contents of the file." }, { "code": null, "e": 5947, "s": 5873, "text": "Example: Let us create a js file named main.js having the following code:" }, { "code": "var fs = require(\"fs\");var buf = new Buffer(1024); console.log(\"opening an existing file\");fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log(\"File opened successfully!\"); console.log(\"reading the file\"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } console.log(bytes + \" bytes read\"); // Print only read bytes to avoid junk. if(bytes > 0){ console.log(buf.slice(0, bytes).toString()); } });});", "e": 6509, "s": 5947, "text": null }, { "code": null, "e": 6517, "s": 6509, "text": "Output:" }, { "code": null, "e": 6626, "s": 6517, "text": "opening an existing file\nFile opened successfully!\nreading the file\nGeeksforGeeks: A computer science portal" }, { "code": null, "e": 6929, "s": 6626, "text": "Writing to a File: This method will overwrite the file if the file already exists. The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method." }, { "code": null, "e": 6937, "s": 6929, "text": "Syntax:" }, { "code": null, "e": 6981, "s": 6937, "text": "fs.writeFile(path, data, options, callback)" }, { "code": null, "e": 6993, "s": 6981, "text": "Parameters:" }, { "code": null, "e": 7194, "s": 6993, "text": "path: It is a string, Buffer, URL, or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similarly to fs.write() method." }, { "code": null, "e": 7282, "s": 7194, "text": "data: It is a string, Buffer, TypedArray, or DataView that will be written to the file." }, { "code": null, "e": 7721, "s": 7282, "text": "options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer value that specifies the file mode. The default value is 0o666.flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’." }, { "code": null, "e": 7822, "s": 7721, "text": "encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’." }, { "code": null, "e": 7909, "s": 7822, "text": "mode: It is an integer value that specifies the file mode. The default value is 0o666." }, { "code": null, "e": 8018, "s": 7909, "text": "flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’." }, { "code": null, "e": 8161, "s": 8018, "text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails." }, { "code": null, "e": 8226, "s": 8161, "text": "err: It is an error that would be thrown if the operation fails." }, { "code": null, "e": 8300, "s": 8226, "text": "Example: Let us create a js file named main.js having the following code:" }, { "code": "var fs = require(\"fs\"); console.log(\"writing into existing file\");fs.writeFile('input.txt', 'Geeks For Geeks', function(err) { if (err) { return console.error(err); } console.log(\"Data written successfully!\"); console.log(\"Let's read newly written data\"); fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log(\"Asynchronous read: \" + data.toString()); });});", "e": 8756, "s": 8300, "text": null }, { "code": null, "e": 8764, "s": 8756, "text": "Output:" }, { "code": null, "e": 8883, "s": 8764, "text": "writing into existing file\nData written successfully!\nLet's read newly written data\nAsynchronous read: Geeks For Geeks" }, { "code": null, "e": 8985, "s": 8883, "text": "Appending to a File: The fs.appendFile() method is used to synchronously append the data to the file." }, { "code": null, "e": 8993, "s": 8985, "text": "Syntax:" }, { "code": null, "e": 9043, "s": 8993, "text": "fs.appendFile(filepath, data, options, callback);" }, { "code": null, "e": 9046, "s": 9043, "text": "or" }, { "code": null, "e": 9090, "s": 9046, "text": "fs.appendFileSync(filepath, data, options);" }, { "code": null, "e": 9102, "s": 9090, "text": "Parameters:" }, { "code": null, "e": 9157, "s": 9102, "text": "filepath: It is a String that specifies the file path." }, { "code": null, "e": 9233, "s": 9157, "text": "data: It is mandatory and it contains the data that you append to the file." }, { "code": null, "e": 9309, "s": 9233, "text": "options: It is an optional parameter that specifies the encoding/mode/flag." }, { "code": null, "e": 9397, "s": 9309, "text": "Callback: Function is mandatory and is called when appending data to file is completed." }, { "code": null, "e": 9473, "s": 9397, "text": "Example 1: Let us create a js file named main.js having the following code:" }, { "code": "var fs = require('fs'); var data = \"\\nLearn Node.js\"; // Append data to filefs.appendFile('input.txt', data, 'utf8', // Callback function function(err) { if (err) throw err; // If no error console.log(\"Data is appended to file successfully.\")});", "e": 9756, "s": 9473, "text": null }, { "code": null, "e": 9764, "s": 9756, "text": "Output:" }, { "code": null, "e": 9803, "s": 9764, "text": "Data is appended to file successfully." }, { "code": null, "e": 9842, "s": 9803, "text": "Example 1: For synchronously appending" }, { "code": "var fs = require('fs'); var data = \"\\nLearn Node.js\"; // Append data to filefs.appendFileSync('input.txt', data, 'utf8');console.log(\"Data is appended to file successfully.\")", "e": 10021, "s": 9842, "text": null }, { "code": null, "e": 10029, "s": 10021, "text": "Output:" }, { "code": null, "e": 10068, "s": 10029, "text": "Data is appended to file successfully." }, { "code": null, "e": 10150, "s": 10068, "text": "Before Appending Data to input.txt file:GeeksforGeeks: A computer science portal " }, { "code": null, "e": 10192, "s": 10150, "text": "GeeksforGeeks: A computer science portal " }, { "code": null, "e": 10286, "s": 10192, "text": "After Appending Data to input.txt file:GeeksforGeeks: A computer science portal\nLearn Node.js" }, { "code": null, "e": 10341, "s": 10286, "text": "GeeksforGeeks: A computer science portal\nLearn Node.js" }, { "code": null, "e": 10683, "s": 10341, "text": "Closing the File: The fs.close() method is used to asynchronously close the given file descriptor thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for other files. Calling fs.close() on a file descriptor while some other operation is being performed on it may lead to undefined behavior." }, { "code": null, "e": 10691, "s": 10683, "text": "Syntax:" }, { "code": null, "e": 10714, "s": 10691, "text": "fs.close(fd, callback)" }, { "code": null, "e": 10726, "s": 10714, "text": "Parameters:" }, { "code": null, "e": 10816, "s": 10726, "text": "fd: It is an integer that denotes the file descriptor of the file for which to be closed." }, { "code": null, "e": 10954, "s": 10816, "text": "callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 11016, "s": 10954, "text": "err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 11090, "s": 11016, "text": "Example: Let us create a js file named main.js having the following code:" }, { "code": "// Close the opened file.fs.close(fd, function(err) { if (err) { console.log(err); } console.log(\"File closed successfully.\");}", "e": 11230, "s": 11090, "text": null }, { "code": null, "e": 11238, "s": 11230, "text": "Output:" }, { "code": null, "e": 11264, "s": 11238, "text": "File closed successfully." }, { "code": null, "e": 11478, "s": 11264, "text": "Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory." }, { "code": null, "e": 11486, "s": 11478, "text": "Syntax:" }, { "code": null, "e": 11512, "s": 11486, "text": "fs.unlink(path, callback)" }, { "code": null, "e": 11524, "s": 11512, "text": "Parameters:" }, { "code": null, "e": 11628, "s": 11524, "text": "path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed." }, { "code": null, "e": 11766, "s": 11628, "text": "callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 11828, "s": 11766, "text": "err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 11902, "s": 11828, "text": "Example: Let us create a js file named main.js having the following code:" }, { "code": "var fs = require(\"fs\"); console.log(\"deleting an existing file\");fs.unlink('input.txt', function(err) { if (err) { return console.error(err); } console.log(\"File deleted successfully!\");});", "e": 12104, "s": 11902, "text": null }, { "code": null, "e": 12112, "s": 12104, "text": "Output:" }, { "code": null, "e": 12165, "s": 12112, "text": "deleting an existing file\nFile deleted successfully!" }, { "code": null, "e": 12183, "s": 12165, "text": "Node.js-fs-module" }, { "code": null, "e": 12190, "s": 12183, "text": "Picked" }, { "code": null, "e": 12198, "s": 12190, "text": "Node.js" }, { "code": null, "e": 12215, "s": 12198, "text": "Web Technologies" }, { "code": null, "e": 12313, "s": 12215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12361, "s": 12313, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 12394, "s": 12361, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 12424, "s": 12394, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 12444, "s": 12424, "text": "How to update NPM ?" }, { "code": null, "e": 12498, "s": 12444, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 12560, "s": 12498, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 12621, "s": 12560, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 12671, "s": 12621, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 12714, "s": 12671, "text": "How to fetch data from an API in ReactJS ?" } ]
Prime numbers and Fibonacci
28 Sep, 2021 Given a number, find the numbers (smaller than or equal to n) which are both Fibonacci and prime. Examples: Input : n = 40 Output: 2 3 5 13 Explanation : Here, range(upper limit) = 40 Fibonacci series upto n is, 1, 1, 2, 3, 5, 8, 13, 21, 34. Prime numbers in above series = 2, 3, 5, 13. Input : n = 100 Output: 2 3 5 13 89 Explanation : Here, range(upper limit) = 40 Fibonacci series upto n are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. Prime numbers in Fibonacci upto n : 2, 3, 5, 13, 89. A simple solution is to iterate generate all fibonacci numbers smaller than or equal to n. For every Fibonacci number, check if it is prime or not. If prime, then print it. An efficient solution is to use Sieve to generate all Prime numbers up to n. After we have generated prime numbers, we can quickly check if a prime is Fibonacci or not by using the property that a number is Fibonacci if it is of the form 5i2 + 4 or in the form 5i2 – 4. Refer this for details. Below is the implementation of above steps C++ Java Python3 C# PHP Javascript // CPP program to print prime numbers present// in Fibonacci series.#include <bits/stdc++.h>using namespace std; // Function to check perfect squarebool isSquare(int n){ int sr = sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal to n that// are both Prime and Fibonacci.void printPrimeAndFib(int n){ // Using Sieve to generate all primes // less than or equal to n. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and print numbers // that are both prime and Fibonacci. for (int i=2; i<=n; i++) if (prime[i] && (isSquare(5 * i * i + 4) > 0 || isSquare(5 * i * i - 4) > 0)) cout << i << " ";} // Driver functionint main(){ int n = 30; printPrimeAndFib(n); return 0;} // Java program to print prime numbers// present in Fibonacci series.class PrimeAndFib{// Function to check perfect squareBoolean isSquare(int n){ int sr = (int)Math.sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.static void printPrimeAndFib(int n){ // Using Sieve to generate all // primes less than or equal to n. Boolean[] prime = new Boolean[n + 1]; // memset(prime, true, sizeof(prime)); for (int p = 0; p <= n; p++) prime[p] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (int i=2; i<=n; i++) { double sqrt = Math.sqrt(5 * i * i + 4); double sqrt1 = Math.sqrt(5 * i * i - 4); int x = (int) sqrt; int y = (int) sqrt1; if (prime[i]==true && (Math.pow(sqrt,2) == Math.pow(x,2) || Math.pow(sqrt1,2) == Math.pow(y,2))) System.out.print(i+" "); }} // driver programpublic static void main(String s[]){ int n = 30; printPrimeAndFib(n);}} // This code is contributed by Prerna Saini # Python 3 program to print# prime numbers present in# Fibonacci series.import math # Function to check perfect squaredef isSquare(n) : sr = (int)(math.sqrt(n)) return (sr * sr == n) # Prints all numbers less than# or equal to n that are# both Prime and Fibonacci.def printPrimeAndFib(n) : # Using Sieve to generate all # primes less than or equal to n. prime =[True] * (n + 1) p = 2 while(p * p <= n ): # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, n + 1, p) : prime[i] = False p = p + 1 # Now traverse through the range # and print numbers that are # both prime and Fibonacci. for i in range(2, n + 1) : if (prime[i] and (isSquare(5 * i * i + 4) > 0 or isSquare(5 * i * i - 4) > 0)) : print(i , " ",end="") # Driver functionn = 30printPrimeAndFib(n); # This code is contributed# by Nikita Tiwari. // C# program to print prime numbers// present in Fibonacci series.using System; class GFG { // Function to check perfect square static bool isSquare(int n) { int sr = (int)Math.Sqrt(n); return (sr * sr == n); } // Prints all numbers less than or equal // to n that are both Prime and Fibonacci. static void printPrimeAndFib(int n) { // Using Sieve to generate all // primes less than or equal to n. bool[] prime = new bool[n + 1]; // memset(prime, true, sizeof(prime)); for (int p = 0; p <= n; p++) prime[p] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (int i = 2; i <= n; i++) { double sqrt = Math.Sqrt(5 * i * i + 4); double sqrt1 = Math.Sqrt(5 * i * i - 4); int x = (int) sqrt; int y = (int) sqrt1; if (prime[i] == true && (Math.Pow(sqrt, 2) == Math.Pow(x, 2) || Math.Pow(sqrt1, 2) == Math.Pow(y, 2))) Console.Write(i + " "); } } // driver program public static void Main() { int n = 30; printPrimeAndFib(n); }} // This code is contributed by Anant Agarwal. <?php// PHP program to print prime numbers// present in Fibonacci series. // Function to check perfect squarefunction isSquare($n){ $sr = (int)sqrt($n); return ($sr * $sr == $n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.function printPrimeAndFib($n){ // Using Sieve to generate all primes // less than or equal to n. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Now traverse through the range // and print numbers that are both // prime and Fibonacci. for ($i = 2; $i <= $n; $i++) if ($prime[$i] && (isSquare(5 * $i * $i + 4) > 0 || isSquare(5 * $i * $i - 4) > 0)) echo $i . " ";} // Driver Code$n = 30;printPrimeAndFib($n); // This code is contributed by mits?> <script> // Javascript program to print prime numbers// present in Fibonacci series. // Function to check perfect squarefunction isSquare(n){ let sr = Math.sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.function prletPrimeAndFib(n){ // Using Sieve to generate all // primes less than or equal to n. let prime = []; // memset(prime, true, sizeof(prime)); for (let p = 0; p <= n; p++) prime[p] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (let i=2; i<=n; i++) { let sqrt = Math.sqrt(5 * i * i + 4); let sqrt1 = Math.sqrt(5 * i * i - 4); let x = Math.floor(sqrt); let y = Math.floor(sqrt1); if (prime[i]==true && (Math.pow(sqrt,2) == Math.pow(x,2) || Math.pow(sqrt1,2) == Math.pow(y,2))) document.write(i+" "); }} // Driver code let n = 30; printPrimeAndFib(n); </script> Output: 2 3 5 13 Mithun Kumar sanjoy_62 simranarora5sos Fibonacci number-theory Prime Number sieve Mathematical number-theory Mathematical Prime Number Fibonacci sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Modulo 10^9+7 (1000000007) Program for factorial of a number Program to print prime numbers from 1 to N. Program to find sum of elements in a given array
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Sep, 2021" }, { "code": null, "e": 150, "s": 52, "text": "Given a number, find the numbers (smaller than or equal to n) which are both Fibonacci and prime." }, { "code": null, "e": 161, "s": 150, "text": "Examples: " }, { "code": null, "e": 543, "s": 161, "text": "Input : n = 40\nOutput: 2 3 5 13\nExplanation :\nHere, range(upper limit) = 40\nFibonacci series upto n is, 1, \n1, 2, 3, 5, 8, 13, 21, 34.\nPrime numbers in above series = 2, 3, 5, 13.\n\nInput : n = 100\nOutput: 2 3 5 13 89\nExplanation :\nHere, range(upper limit) = 40\nFibonacci series upto n are 1, 1, 2, \n3, 5, 8, 13, 21, 34, 55, 89.\nPrime numbers in Fibonacci upto n : 2, 3, \n5, 13, 89." }, { "code": null, "e": 716, "s": 543, "text": "A simple solution is to iterate generate all fibonacci numbers smaller than or equal to n. For every Fibonacci number, check if it is prime or not. If prime, then print it." }, { "code": null, "e": 1010, "s": 716, "text": "An efficient solution is to use Sieve to generate all Prime numbers up to n. After we have generated prime numbers, we can quickly check if a prime is Fibonacci or not by using the property that a number is Fibonacci if it is of the form 5i2 + 4 or in the form 5i2 – 4. Refer this for details." }, { "code": null, "e": 1055, "s": 1010, "text": "Below is the implementation of above steps " }, { "code": null, "e": 1059, "s": 1055, "text": "C++" }, { "code": null, "e": 1064, "s": 1059, "text": "Java" }, { "code": null, "e": 1072, "s": 1064, "text": "Python3" }, { "code": null, "e": 1075, "s": 1072, "text": "C#" }, { "code": null, "e": 1079, "s": 1075, "text": "PHP" }, { "code": null, "e": 1090, "s": 1079, "text": "Javascript" }, { "code": "// CPP program to print prime numbers present// in Fibonacci series.#include <bits/stdc++.h>using namespace std; // Function to check perfect squarebool isSquare(int n){ int sr = sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal to n that// are both Prime and Fibonacci.void printPrimeAndFib(int n){ // Using Sieve to generate all primes // less than or equal to n. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and print numbers // that are both prime and Fibonacci. for (int i=2; i<=n; i++) if (prime[i] && (isSquare(5 * i * i + 4) > 0 || isSquare(5 * i * i - 4) > 0)) cout << i << \" \";} // Driver functionint main(){ int n = 30; printPrimeAndFib(n); return 0;}", "e": 2180, "s": 1090, "text": null }, { "code": "// Java program to print prime numbers// present in Fibonacci series.class PrimeAndFib{// Function to check perfect squareBoolean isSquare(int n){ int sr = (int)Math.sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.static void printPrimeAndFib(int n){ // Using Sieve to generate all // primes less than or equal to n. Boolean[] prime = new Boolean[n + 1]; // memset(prime, true, sizeof(prime)); for (int p = 0; p <= n; p++) prime[p] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (int i=2; i<=n; i++) { double sqrt = Math.sqrt(5 * i * i + 4); double sqrt1 = Math.sqrt(5 * i * i - 4); int x = (int) sqrt; int y = (int) sqrt1; if (prime[i]==true && (Math.pow(sqrt,2) == Math.pow(x,2) || Math.pow(sqrt1,2) == Math.pow(y,2))) System.out.print(i+\" \"); }} // driver programpublic static void main(String s[]){ int n = 30; printPrimeAndFib(n);}} // This code is contributed by Prerna Saini", "e": 3568, "s": 2180, "text": null }, { "code": "# Python 3 program to print# prime numbers present in# Fibonacci series.import math # Function to check perfect squaredef isSquare(n) : sr = (int)(math.sqrt(n)) return (sr * sr == n) # Prints all numbers less than# or equal to n that are# both Prime and Fibonacci.def printPrimeAndFib(n) : # Using Sieve to generate all # primes less than or equal to n. prime =[True] * (n + 1) p = 2 while(p * p <= n ): # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, n + 1, p) : prime[i] = False p = p + 1 # Now traverse through the range # and print numbers that are # both prime and Fibonacci. for i in range(2, n + 1) : if (prime[i] and (isSquare(5 * i * i + 4) > 0 or isSquare(5 * i * i - 4) > 0)) : print(i , \" \",end=\"\") # Driver functionn = 30printPrimeAndFib(n); # This code is contributed# by Nikita Tiwari.", "e": 4627, "s": 3568, "text": null }, { "code": "// C# program to print prime numbers// present in Fibonacci series.using System; class GFG { // Function to check perfect square static bool isSquare(int n) { int sr = (int)Math.Sqrt(n); return (sr * sr == n); } // Prints all numbers less than or equal // to n that are both Prime and Fibonacci. static void printPrimeAndFib(int n) { // Using Sieve to generate all // primes less than or equal to n. bool[] prime = new bool[n + 1]; // memset(prime, true, sizeof(prime)); for (int p = 0; p <= n; p++) prime[p] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (int i = 2; i <= n; i++) { double sqrt = Math.Sqrt(5 * i * i + 4); double sqrt1 = Math.Sqrt(5 * i * i - 4); int x = (int) sqrt; int y = (int) sqrt1; if (prime[i] == true && (Math.Pow(sqrt, 2) == Math.Pow(x, 2) || Math.Pow(sqrt1, 2) == Math.Pow(y, 2))) Console.Write(i + \" \"); } } // driver program public static void Main() { int n = 30; printPrimeAndFib(n); }} // This code is contributed by Anant Agarwal.", "e": 6327, "s": 4627, "text": null }, { "code": "<?php// PHP program to print prime numbers// present in Fibonacci series. // Function to check perfect squarefunction isSquare($n){ $sr = (int)sqrt($n); return ($sr * $sr == $n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.function printPrimeAndFib($n){ // Using Sieve to generate all primes // less than or equal to n. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Now traverse through the range // and print numbers that are both // prime and Fibonacci. for ($i = 2; $i <= $n; $i++) if ($prime[$i] && (isSquare(5 * $i * $i + 4) > 0 || isSquare(5 * $i * $i - 4) > 0)) echo $i . \" \";} // Driver Code$n = 30;printPrimeAndFib($n); // This code is contributed by mits?>", "e": 7393, "s": 6327, "text": null }, { "code": "<script> // Javascript program to print prime numbers// present in Fibonacci series. // Function to check perfect squarefunction isSquare(n){ let sr = Math.sqrt(n); return (sr * sr == n);} // Prints all numbers less than or equal// to n that are both Prime and Fibonacci.function prletPrimeAndFib(n){ // Using Sieve to generate all // primes less than or equal to n. let prime = []; // memset(prime, true, sizeof(prime)); for (let p = 0; p <= n; p++) prime[p] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Now traverse through the range and // print numbers that are both prime // and Fibonacci. for (let i=2; i<=n; i++) { let sqrt = Math.sqrt(5 * i * i + 4); let sqrt1 = Math.sqrt(5 * i * i - 4); let x = Math.floor(sqrt); let y = Math.floor(sqrt1); if (prime[i]==true && (Math.pow(sqrt,2) == Math.pow(x,2) || Math.pow(sqrt1,2) == Math.pow(y,2))) document.write(i+\" \"); }} // Driver code let n = 30; printPrimeAndFib(n); </script>", "e": 8700, "s": 7393, "text": null }, { "code": null, "e": 8709, "s": 8700, "text": "Output: " }, { "code": null, "e": 8718, "s": 8709, "text": "2 3 5 13" }, { "code": null, "e": 8733, "s": 8720, "text": "Mithun Kumar" }, { "code": null, "e": 8743, "s": 8733, "text": "sanjoy_62" }, { "code": null, "e": 8759, "s": 8743, "text": "simranarora5sos" }, { "code": null, "e": 8769, "s": 8759, "text": "Fibonacci" }, { "code": null, "e": 8783, "s": 8769, "text": "number-theory" }, { "code": null, "e": 8796, "s": 8783, "text": "Prime Number" }, { "code": null, "e": 8802, "s": 8796, "text": "sieve" }, { "code": null, "e": 8815, "s": 8802, "text": "Mathematical" }, { "code": null, "e": 8829, "s": 8815, "text": "number-theory" }, { "code": null, "e": 8842, "s": 8829, "text": "Mathematical" }, { "code": null, "e": 8855, "s": 8842, "text": "Prime Number" }, { "code": null, "e": 8865, "s": 8855, "text": "Fibonacci" }, { "code": null, "e": 8871, "s": 8865, "text": "sieve" }, { "code": null, "e": 8969, "s": 8871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8990, "s": 8969, "text": "Operators in C / C++" }, { "code": null, "e": 9043, "s": 8990, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9080, "s": 9043, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9112, "s": 9080, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9155, "s": 9112, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9198, "s": 9155, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 9225, "s": 9198, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9259, "s": 9225, "text": "Program for factorial of a number" }, { "code": null, "e": 9303, "s": 9259, "text": "Program to print prime numbers from 1 to N." } ]
Integration in MATLAB
28 Apr, 2021 Integration is defined as the process of finding the anti derivative of a function. It is used to calculate area, volume, displacement, and many more. In this article, we will see how to perform integration on expressions in MATLAB. There are two types of Integration: Indefinite integral: Let f(x) be a function. Then the family of all antiderivatives is called the indefinite integral of a function f(x) and it is denoted by ∫f(x)dx. The symbol ∫f(x)dx is read as the indefinite integral of f(x) with respect to x. Thus ∫f(x)dx= ∅(x) + C. Thus, the process of finding the indefinite integral of a function is called the integration of the function. Definite integrals: Definite integrals are the extension after indefinite integrals, definite integrals have limits [a, b]. It gives the area of a curve bounded between given limits. It is denoted by ∫f(x)dx under the limit of a and b, it denotes the area of curve F(x) bounded between a and b, where a is the lower limit and b is the upper limit. Before moving to Integration, we first need to assign an expression to a variable in MATLAB which can be done by using the inline() function. It creates a function to contain the expression. Syntax: f = inline(expr, var) Here f is the inline function created to contain the expression, expr can be any expression and var is the variable in that expression. Now, after assigning the expression using the inline() function, we need to integrate the expression. This task can be performed using the int() function. The int() function is used to integrate expressions in MATLAB. Syntax: int(f,v) Parameters: f: Expression v: Variable Indefinite integrals are those integrals that do not have any limit and containing an arbitrary constant. Step-wise Approach: Step 1: Use Inline function for the creation of the function for integration. Matlab % create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); Step 2: Create a symbolic function. Matlab % create a symbolic functionsyms x;syms y; Step 3: Use int to find out the integration. Matlab % for the integration use int() % and pass the parameters% (expression, variable)% variable= variable for integrationp=int (f(x),x);q=int (g(y),y); Complete Code: Matlab % create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); % create a symbolic functionsyms x;syms y; % variable= variable for% integrationp=int (f(x),x);q=int (g(y),y); % displaypq Output: Definite integrals are those integrals that have an upper limit and a lower limit. Let’s take the above example and add the limits. Step-wise Approach: Step 1: Use the Inline function for the creation of the function for integration. Matlab % create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); Step 2: Create a symbolic function. Matlab % create a symbolic functionsyms x;syms y; Step 3: Use int to find out the integration and pass down the values of the lower limit, upper limit. Matlab %for the integration use int() % and pass the parameters%(expression, lower limit, % upper limit)p=int (f(x),1,4);q=int (g(y),1,3); % use double to know the value% in decimaldouble(q); Complete Code: Matlab % create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); % create a symbolic functionsyms x;syms y; % for the integration use int() and pass the parameters% (expression, lower limit, upper limit)p=int (f(x),1,4);q=int (g(y),1,3);double(q); % displaypq Output: MATLAB-Maths Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Double Integral in MATLAB Classes and Object in MATLAB How to remove space in a string in MATLAB? Forward and Inverse Fourier Transform of an Image in MATLAB How to Normalize a Histogram in MATLAB?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 261, "s": 28, "text": "Integration is defined as the process of finding the anti derivative of a function. It is used to calculate area, volume, displacement, and many more. In this article, we will see how to perform integration on expressions in MATLAB." }, { "code": null, "e": 297, "s": 261, "text": "There are two types of Integration:" }, { "code": null, "e": 679, "s": 297, "text": "Indefinite integral: Let f(x) be a function. Then the family of all antiderivatives is called the indefinite integral of a function f(x) and it is denoted by ∫f(x)dx. The symbol ∫f(x)dx is read as the indefinite integral of f(x) with respect to x. Thus ∫f(x)dx= ∅(x) + C. Thus, the process of finding the indefinite integral of a function is called the integration of the function." }, { "code": null, "e": 1027, "s": 679, "text": "Definite integrals: Definite integrals are the extension after indefinite integrals, definite integrals have limits [a, b]. It gives the area of a curve bounded between given limits. It is denoted by ∫f(x)dx under the limit of a and b, it denotes the area of curve F(x) bounded between a and b, where a is the lower limit and b is the upper limit." }, { "code": null, "e": 1218, "s": 1027, "text": "Before moving to Integration, we first need to assign an expression to a variable in MATLAB which can be done by using the inline() function. It creates a function to contain the expression." }, { "code": null, "e": 1226, "s": 1218, "text": "Syntax:" }, { "code": null, "e": 1248, "s": 1226, "text": "f = inline(expr, var)" }, { "code": null, "e": 1384, "s": 1248, "text": "Here f is the inline function created to contain the expression, expr can be any expression and var is the variable in that expression." }, { "code": null, "e": 1602, "s": 1384, "text": "Now, after assigning the expression using the inline() function, we need to integrate the expression. This task can be performed using the int() function. The int() function is used to integrate expressions in MATLAB." }, { "code": null, "e": 1610, "s": 1602, "text": "Syntax:" }, { "code": null, "e": 1619, "s": 1610, "text": "int(f,v)" }, { "code": null, "e": 1631, "s": 1619, "text": "Parameters:" }, { "code": null, "e": 1645, "s": 1631, "text": "f: Expression" }, { "code": null, "e": 1657, "s": 1645, "text": "v: Variable" }, { "code": null, "e": 1763, "s": 1657, "text": "Indefinite integrals are those integrals that do not have any limit and containing an arbitrary constant." }, { "code": null, "e": 1783, "s": 1763, "text": "Step-wise Approach:" }, { "code": null, "e": 1861, "s": 1783, "text": "Step 1: Use Inline function for the creation of the function for integration." }, { "code": null, "e": 1868, "s": 1861, "text": "Matlab" }, { "code": "% create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y');", "e": 1956, "s": 1868, "text": null }, { "code": null, "e": 1992, "s": 1956, "text": "Step 2: Create a symbolic function." }, { "code": null, "e": 1999, "s": 1992, "text": "Matlab" }, { "code": "% create a symbolic functionsyms x;syms y;", "e": 2042, "s": 1999, "text": null }, { "code": null, "e": 2087, "s": 2042, "text": "Step 3: Use int to find out the integration." }, { "code": null, "e": 2094, "s": 2087, "text": "Matlab" }, { "code": "% for the integration use int() % and pass the parameters% (expression, variable)% variable= variable for integrationp=int (f(x),x);q=int (g(y),y);", "e": 2243, "s": 2094, "text": null }, { "code": null, "e": 2258, "s": 2243, "text": "Complete Code:" }, { "code": null, "e": 2265, "s": 2258, "text": "Matlab" }, { "code": "% create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); % create a symbolic functionsyms x;syms y; % variable= variable for% integrationp=int (f(x),x);q=int (g(y),y); % displaypq", "e": 2479, "s": 2265, "text": null }, { "code": null, "e": 2488, "s": 2479, "text": "Output: " }, { "code": null, "e": 2620, "s": 2488, "text": "Definite integrals are those integrals that have an upper limit and a lower limit. Let’s take the above example and add the limits." }, { "code": null, "e": 2640, "s": 2620, "text": "Step-wise Approach:" }, { "code": null, "e": 2722, "s": 2640, "text": "Step 1: Use the Inline function for the creation of the function for integration." }, { "code": null, "e": 2729, "s": 2722, "text": "Matlab" }, { "code": "% create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y');", "e": 2817, "s": 2729, "text": null }, { "code": null, "e": 2853, "s": 2817, "text": "Step 2: Create a symbolic function." }, { "code": null, "e": 2860, "s": 2853, "text": "Matlab" }, { "code": "% create a symbolic functionsyms x;syms y;", "e": 2903, "s": 2860, "text": null }, { "code": null, "e": 3005, "s": 2903, "text": "Step 3: Use int to find out the integration and pass down the values of the lower limit, upper limit." }, { "code": null, "e": 3012, "s": 3005, "text": "Matlab" }, { "code": "%for the integration use int() % and pass the parameters%(expression, lower limit, % upper limit)p=int (f(x),1,4);q=int (g(y),1,3); % use double to know the value% in decimaldouble(q);", "e": 3198, "s": 3012, "text": null }, { "code": null, "e": 3214, "s": 3198, "text": " Complete Code:" }, { "code": null, "e": 3221, "s": 3214, "text": "Matlab" }, { "code": "% create a inline functionf=inline('x^2+3*x' ,'x');g=inline( 'sin(y) + cos(y)^2', 'y'); % create a symbolic functionsyms x;syms y; % for the integration use int() and pass the parameters% (expression, lower limit, upper limit)p=int (f(x),1,4);q=int (g(y),1,3);double(q); % displaypq", "e": 3507, "s": 3221, "text": null }, { "code": null, "e": 3515, "s": 3507, "text": "Output:" }, { "code": null, "e": 3528, "s": 3515, "text": "MATLAB-Maths" }, { "code": null, "e": 3535, "s": 3528, "text": "Picked" }, { "code": null, "e": 3542, "s": 3535, "text": "MATLAB" }, { "code": null, "e": 3640, "s": 3542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3719, "s": 3640, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 3784, "s": 3719, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 3849, "s": 3784, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 3882, "s": 3849, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 3956, "s": 3882, "text": "How to detect duplicate values and its indices within an array in MATLAB?" }, { "code": null, "e": 3982, "s": 3956, "text": "Double Integral in MATLAB" }, { "code": null, "e": 4011, "s": 3982, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 4054, "s": 4011, "text": "How to remove space in a string in MATLAB?" }, { "code": null, "e": 4114, "s": 4054, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" } ]
Probability that a N digit number is palindrome
22 Jun, 2022 Given an integer N, the task is to find the probability that a number with a number of digits as N is a palindrome. The number may have leading zeros.Examples: Input: N = 5 Output: 1 / 100Input: N = 6 Output: 1 / 1000 Solution: As leading zeroes are allowed a total number of N digit numbers is 10N. A number is a palindrome when the first N/2 digits match with the last N/2 digits in reverse order. For an even number of digits, we can pick the first N/2 digits and then duplicate them to form the rest of N/2 digits so we can choose (N)/2 digits. For an odd number of digits, we can pick first (N-1)/2 digits and then duplicate them to form the rest of (N-1)/2 digits so we can choose (N+1)/2 digits. So the probability that an N digit number is palindrome is 10ceil( N / 2 ) / 10N or 1 / 10floor( N / 2 ) Below is the implementation of the approach: C++ Java Python3 C# Javascript // C++ code of above approach#include <bits/stdc++.h>using namespace std; // Find the probability that a// n digit number is palindromevoid solve(int n){ int n_2 = n / 2; // Denominator string den; den = "1"; // Assign 10^(floor(n/2)) to // denominator while (n_2--) den += '0'; // Display the answer cout << 1 << "/" << den << "\n";} // Driver codeint main(){ int N = 5; solve(N); return 0;} // Java code of above approachimport java.util.*; class GFG{ // Find the probability that a// n digit number is palindromestatic void solve(int n){ int n_2 = n / 2; // Denominator String den; den = "1"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer System.out.println(1 + "/" + den);} // Driver codepublic static void main(String[] args){ int N = 5; solve(N);}} // This code is contributed by Rajput-Ji # Python3 code of above approach # Find the probability that a# n digit number is palindromedef solve(n) : n_2 = n // 2; # Denominator den = "1"; # Assign 10^(floor(n/2)) to # denominator while (n_2) : den += '0'; n_2 -= 1 # Display the answer print(str(1) + "/" + str(den)) # Driver codeif __name__ == "__main__" : N = 5; solve(N); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Find the probability that a// n digit number is palindromestatic void solve(int n){ int n_2 = n / 2; // Denominator String den; den = "1"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer Console.WriteLine(1 + "/" + den);} // Driver codepublic static void Main(String[] args){ int N = 5; solve(N);}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Find the probability that a // n digit number is palindrome function solve(n) { let n_2 = parseInt(n / 2, 10); // Denominator let den; den = "1"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer document.write(1 + "/" + den + "</br>"); } let N = 5; solve(N); // This code is contributed by divyeshrabadiya07.</script> 1/100 Time Complexity: O(N), as we are using a loop to traverse N times.Auxiliary Space: O(1), as we are not using any extra space. ankthon Rajput-Ji princiraj1992 nidhi_biet divyeshrabadiya07 rohitsingh57 Numbers Probability Mathematical Mathematical Numbers Probability Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Product of Array except itself Find Union and Intersection of two unsorted arrays Median of two sorted arrays of same size
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 215, "s": 54, "text": "Given an integer N, the task is to find the probability that a number with a number of digits as N is a palindrome. The number may have leading zeros.Examples: " }, { "code": null, "e": 274, "s": 215, "text": "Input: N = 5 Output: 1 / 100Input: N = 6 Output: 1 / 1000 " }, { "code": null, "e": 285, "s": 274, "text": "Solution: " }, { "code": null, "e": 357, "s": 285, "text": "As leading zeroes are allowed a total number of N digit numbers is 10N." }, { "code": null, "e": 457, "s": 357, "text": "A number is a palindrome when the first N/2 digits match with the last N/2 digits in reverse order." }, { "code": null, "e": 606, "s": 457, "text": "For an even number of digits, we can pick the first N/2 digits and then duplicate them to form the rest of N/2 digits so we can choose (N)/2 digits." }, { "code": null, "e": 760, "s": 606, "text": "For an odd number of digits, we can pick first (N-1)/2 digits and then duplicate them to form the rest of (N-1)/2 digits so we can choose (N+1)/2 digits." }, { "code": null, "e": 865, "s": 760, "text": "So the probability that an N digit number is palindrome is 10ceil( N / 2 ) / 10N or 1 / 10floor( N / 2 )" }, { "code": null, "e": 912, "s": 865, "text": "Below is the implementation of the approach: " }, { "code": null, "e": 916, "s": 912, "text": "C++" }, { "code": null, "e": 921, "s": 916, "text": "Java" }, { "code": null, "e": 929, "s": 921, "text": "Python3" }, { "code": null, "e": 932, "s": 929, "text": "C#" }, { "code": null, "e": 943, "s": 932, "text": "Javascript" }, { "code": "// C++ code of above approach#include <bits/stdc++.h>using namespace std; // Find the probability that a// n digit number is palindromevoid solve(int n){ int n_2 = n / 2; // Denominator string den; den = \"1\"; // Assign 10^(floor(n/2)) to // denominator while (n_2--) den += '0'; // Display the answer cout << 1 << \"/\" << den << \"\\n\";} // Driver codeint main(){ int N = 5; solve(N); return 0;}", "e": 1385, "s": 943, "text": null }, { "code": "// Java code of above approachimport java.util.*; class GFG{ // Find the probability that a// n digit number is palindromestatic void solve(int n){ int n_2 = n / 2; // Denominator String den; den = \"1\"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer System.out.println(1 + \"/\" + den);} // Driver codepublic static void main(String[] args){ int N = 5; solve(N);}} // This code is contributed by Rajput-Ji", "e": 1882, "s": 1385, "text": null }, { "code": "# Python3 code of above approach # Find the probability that a# n digit number is palindromedef solve(n) : n_2 = n // 2; # Denominator den = \"1\"; # Assign 10^(floor(n/2)) to # denominator while (n_2) : den += '0'; n_2 -= 1 # Display the answer print(str(1) + \"/\" + str(den)) # Driver codeif __name__ == \"__main__\" : N = 5; solve(N); # This code is contributed by AnkitRai01", "e": 2327, "s": 1882, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Find the probability that a// n digit number is palindromestatic void solve(int n){ int n_2 = n / 2; // Denominator String den; den = \"1\"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer Console.WriteLine(1 + \"/\" + den);} // Driver codepublic static void Main(String[] args){ int N = 5; solve(N);}} // This code is contributed by PrinciRaj1992", "e": 2827, "s": 2327, "text": null }, { "code": "<script> // Javascript implementation of the approach // Find the probability that a // n digit number is palindrome function solve(n) { let n_2 = parseInt(n / 2, 10); // Denominator let den; den = \"1\"; // Assign 10^(floor(n/2)) to // denominator while (n_2-- > 0) den += '0'; // Display the answer document.write(1 + \"/\" + den + \"</br>\"); } let N = 5; solve(N); // This code is contributed by divyeshrabadiya07.</script>", "e": 3363, "s": 2827, "text": null }, { "code": null, "e": 3369, "s": 3363, "text": "1/100" }, { "code": null, "e": 3497, "s": 3371, "text": "Time Complexity: O(N), as we are using a loop to traverse N times.Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 3505, "s": 3497, "text": "ankthon" }, { "code": null, "e": 3515, "s": 3505, "text": "Rajput-Ji" }, { "code": null, "e": 3529, "s": 3515, "text": "princiraj1992" }, { "code": null, "e": 3540, "s": 3529, "text": "nidhi_biet" }, { "code": null, "e": 3558, "s": 3540, "text": "divyeshrabadiya07" }, { "code": null, "e": 3571, "s": 3558, "text": "rohitsingh57" }, { "code": null, "e": 3579, "s": 3571, "text": "Numbers" }, { "code": null, "e": 3591, "s": 3579, "text": "Probability" }, { "code": null, "e": 3604, "s": 3591, "text": "Mathematical" }, { "code": null, "e": 3617, "s": 3604, "text": "Mathematical" }, { "code": null, "e": 3625, "s": 3617, "text": "Numbers" }, { "code": null, "e": 3637, "s": 3625, "text": "Probability" }, { "code": null, "e": 3735, "s": 3637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3767, "s": 3735, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3811, "s": 3767, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 3857, "s": 3811, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 3899, "s": 3857, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 3924, "s": 3899, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 3956, "s": 3924, "text": "Check if a number is Palindrome" }, { "code": null, "e": 3991, "s": 3956, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 4022, "s": 3991, "text": "Product of Array except itself" }, { "code": null, "e": 4073, "s": 4022, "text": "Find Union and Intersection of two unsorted arrays" } ]
Trie | (Delete)
11 Aug, 2021 In the previous post on trie we have described how to insert and search a node in trie. Here is an algorithm how to delete a node from trie.During delete operation we delete the key in bottom up manner using recursion. The following are possible conditions when deleting key from trie, Key may not be there in trie. Delete operation should not modify trie.Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in trie). Delete all the nodes.Key is prefix key of another long key in trie. Unmark the leaf node.Key present in trie, having atleast one other key as prefix key. Delete nodes from end of key until first leaf node of longest prefix key. Key may not be there in trie. Delete operation should not modify trie. Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in trie). Delete all the nodes. Key is prefix key of another long key in trie. Unmark the leaf node. Key present in trie, having atleast one other key as prefix key. Delete nodes from end of key until first leaf node of longest prefix key. The below code presents algorithm to implement above conditions. C++ Java Javascript // C++ implementation of delete// operations on Trie#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else// falsebool search(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord);} // Returns true if root has no children, else falsebool isEmpty(TrieNode* root){ for (int i = 0; i < ALPHABET_SIZE; i++) if (root->children[i]) return false; return true;} // Recursive function to delete a key from given TrieTrieNode* remove(TrieNode* root, string key, int depth = 0){ // If tree is empty if (!root) return NULL; // If last character of key is being processed if (depth == key.size()) { // This node is no more end of word after // removal of given key if (root->isEndOfWord) root->isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { delete (root); root = NULL; } return root; } // If not last character, recur for the child // obtained using ASCII value int index = key[depth] - 'a'; root->children[index] = remove(root->children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root->isEndOfWord == false) { delete (root); root = NULL; } return root;} // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) string keys[] = { "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane" }; int n = sizeof(keys) / sizeof(keys[0]); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys search(root, "the") ? cout << "Yes\n" : cout << "No\n"; search(root, "these") ? cout << "Yes\n" : cout << "No\n"; remove(root, "heroplane"); search(root, "hero") ? cout << "Yes\n" : cout << "No\n"; return 0;} // Java implementation of delete// operations on Trieimport java.util.*; public class GFG{ static int ALPHABET_SIZE = 26; // trie node static class TrieNode { TrieNode children[] = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; } // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key presents in trie, else // false static boolean search(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord); } // Returns true if root has no children, else false static boolean isEmpty(TrieNode root) { for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null) return false; return true; } // Recursive function to delete a key from given Trie static TrieNode remove(TrieNode root, String key, int depth) { // If tree is empty if (root == null) return null; // If last character of key is being processed if (depth == key.length()) { // This node is no more end of word after // removal of given key if (root.isEndOfWord) root.isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { root = null; } return root; } // If not last character, recur for the child // obtained using ASCII value int index = key.charAt(depth) - 'a'; root.children[index] = remove(root.children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root.isEndOfWord == false){ root = null; } return root; } // Driver public static void main(String args[]) { // Input keys (use only 'a' through 'z' // and lower case) String keys[] = { "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane" }; int n = keys.length; TrieNode root = new TrieNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys if(search(root, "the")) System.out.println("Yes"); else System.out.println("No"); if(search(root, "these")) System.out.println("Yes"); else System.out.println("No"); remove(root, "heroplane", 0); if(search(root, "hero")) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by aditypande88. <script>// Javascript implementation of delete// operations on Trie let ALPHABET_SIZE = 26; // trie nodeclass TrieNode{ constructor() { this.children=new Array(ALPHABET_SIZE); this.isEndOfWord=false; }} // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf nodefunction insert(root,key){ let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true;} // Returns true if key presents in trie, else // falsefunction search(root,key){ let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Returns true if root has no children, else falsefunction isEmpty(root){ for (let i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null) return false; return true;} // Recursive function to delete a key from given Triefunction remove(root,key,depth){ // If tree is empty if (root == null) return null; // If last character of key is being processed if (depth == key.length) { // This node is no more end of word after // removal of given key if (root.isEndOfWord) root.isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { root = null; } return root; } // If not last character, recur for the child // obtained using ASCII value let index = key[depth].charCodeAt(0) - 'a'.charCodeAt(0); root.children[index] = remove(root.children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root.isEndOfWord == false){ root = null; } return root;} // Driver// Input keys (use only 'a' through 'z'// and lower case)let keys = [ "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane" ];let n = keys.length; let root = new TrieNode(); // Construct triefor (let i = 0; i < n; i++) insert(root, keys[i]); // Search for different keysif(search(root, "the")) document.write("Yes<br>");else document.write("No<br>"); if(search(root, "these")) document.write("Yes<br>");else document.write("No<br>"); remove(root, "heroplane", 0); if(search(root, "hero")) document.write("Yes<br>");else document.write("No<br>"); // This code is contributed by patel2127</script> Yes No Yes Time Complexity: The time complexity of the deletion operation is O(n) where n is the key length. https://youtu.be/XK8MD9N9WUA— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. manoj_26 adityapande88 varaprasadh gopinath_mb patel2127 Trie Advanced Data Structure Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Agents in Artificial Intelligence Red-Black Tree | Set 1 (Introduction) Decision Tree Introduction with example Binary Indexed Tree or Fenwick Tree AVL Tree | Set 2 (Deletion) Disjoint Set Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 339, "s": 52, "text": "In the previous post on trie we have described how to insert and search a node in trie. Here is an algorithm how to delete a node from trie.During delete operation we delete the key in bottom up manner using recursion. The following are possible conditions when deleting key from trie, " }, { "code": null, "e": 764, "s": 339, "text": "Key may not be there in trie. Delete operation should not modify trie.Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in trie). Delete all the nodes.Key is prefix key of another long key in trie. Unmark the leaf node.Key present in trie, having atleast one other key as prefix key. Delete nodes from end of key until first leaf node of longest prefix key." }, { "code": null, "e": 835, "s": 764, "text": "Key may not be there in trie. Delete operation should not modify trie." }, { "code": null, "e": 984, "s": 835, "text": "Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in trie). Delete all the nodes." }, { "code": null, "e": 1053, "s": 984, "text": "Key is prefix key of another long key in trie. Unmark the leaf node." }, { "code": null, "e": 1192, "s": 1053, "text": "Key present in trie, having atleast one other key as prefix key. Delete nodes from end of key until first leaf node of longest prefix key." }, { "code": null, "e": 1258, "s": 1192, "text": "The below code presents algorithm to implement above conditions. " }, { "code": null, "e": 1262, "s": 1258, "text": "C++" }, { "code": null, "e": 1267, "s": 1262, "text": "Java" }, { "code": null, "e": 1278, "s": 1267, "text": "Javascript" }, { "code": "// C++ implementation of delete// operations on Trie#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // trie nodestruct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode* getNode(void){ struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else// falsebool search(struct TrieNode* root, string key){ struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord);} // Returns true if root has no children, else falsebool isEmpty(TrieNode* root){ for (int i = 0; i < ALPHABET_SIZE; i++) if (root->children[i]) return false; return true;} // Recursive function to delete a key from given TrieTrieNode* remove(TrieNode* root, string key, int depth = 0){ // If tree is empty if (!root) return NULL; // If last character of key is being processed if (depth == key.size()) { // This node is no more end of word after // removal of given key if (root->isEndOfWord) root->isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { delete (root); root = NULL; } return root; } // If not last character, recur for the child // obtained using ASCII value int index = key[depth] - 'a'; root->children[index] = remove(root->children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root->isEndOfWord == false) { delete (root); root = NULL; } return root;} // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) string keys[] = { \"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\", \"hero\", \"heroplane\" }; int n = sizeof(keys) / sizeof(keys[0]); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys search(root, \"the\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; search(root, \"these\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; remove(root, \"heroplane\"); search(root, \"hero\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 4499, "s": 1278, "text": null }, { "code": "// Java implementation of delete// operations on Trieimport java.util.*; public class GFG{ static int ALPHABET_SIZE = 26; // trie node static class TrieNode { TrieNode children[] = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; } // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key presents in trie, else // false static boolean search(TrieNode root, String key) { TrieNode pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key.charAt(i) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord); } // Returns true if root has no children, else false static boolean isEmpty(TrieNode root) { for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null) return false; return true; } // Recursive function to delete a key from given Trie static TrieNode remove(TrieNode root, String key, int depth) { // If tree is empty if (root == null) return null; // If last character of key is being processed if (depth == key.length()) { // This node is no more end of word after // removal of given key if (root.isEndOfWord) root.isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { root = null; } return root; } // If not last character, recur for the child // obtained using ASCII value int index = key.charAt(depth) - 'a'; root.children[index] = remove(root.children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root.isEndOfWord == false){ root = null; } return root; } // Driver public static void main(String args[]) { // Input keys (use only 'a' through 'z' // and lower case) String keys[] = { \"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\", \"hero\", \"heroplane\" }; int n = keys.length; TrieNode root = new TrieNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys if(search(root, \"the\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); if(search(root, \"these\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); remove(root, \"heroplane\", 0); if(search(root, \"hero\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by aditypande88.", "e": 8061, "s": 4499, "text": null }, { "code": "<script>// Javascript implementation of delete// operations on Trie let ALPHABET_SIZE = 26; // trie nodeclass TrieNode{ constructor() { this.children=new Array(ALPHABET_SIZE); this.isEndOfWord=false; }} // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf nodefunction insert(root,key){ let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true;} // Returns true if key presents in trie, else // falsefunction search(root,key){ let pCrawl = root; for (let i = 0; i < key.length; i++) { let index = key[i].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl != null && pCrawl.isEndOfWord);} // Returns true if root has no children, else falsefunction isEmpty(root){ for (let i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null) return false; return true;} // Recursive function to delete a key from given Triefunction remove(root,key,depth){ // If tree is empty if (root == null) return null; // If last character of key is being processed if (depth == key.length) { // This node is no more end of word after // removal of given key if (root.isEndOfWord) root.isEndOfWord = false; // If given is not prefix of any other word if (isEmpty(root)) { root = null; } return root; } // If not last character, recur for the child // obtained using ASCII value let index = key[depth].charCodeAt(0) - 'a'.charCodeAt(0); root.children[index] = remove(root.children[index], key, depth + 1); // If root does not have any child (its only child got // deleted), and it is not end of another word. if (isEmpty(root) && root.isEndOfWord == false){ root = null; } return root;} // Driver// Input keys (use only 'a' through 'z'// and lower case)let keys = [ \"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\", \"hero\", \"heroplane\" ];let n = keys.length; let root = new TrieNode(); // Construct triefor (let i = 0; i < n; i++) insert(root, keys[i]); // Search for different keysif(search(root, \"the\")) document.write(\"Yes<br>\");else document.write(\"No<br>\"); if(search(root, \"these\")) document.write(\"Yes<br>\");else document.write(\"No<br>\"); remove(root, \"heroplane\", 0); if(search(root, \"hero\")) document.write(\"Yes<br>\");else document.write(\"No<br>\"); // This code is contributed by patel2127</script>", "e": 11138, "s": 8061, "text": null }, { "code": null, "e": 11149, "s": 11138, "text": "Yes\nNo\nYes" }, { "code": null, "e": 11249, "s": 11151, "text": "Time Complexity: The time complexity of the deletion operation is O(n) where n is the key length." }, { "code": null, "e": 11411, "s": 11249, "text": "https://youtu.be/XK8MD9N9WUA— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 11420, "s": 11411, "text": "manoj_26" }, { "code": null, "e": 11434, "s": 11420, "text": "adityapande88" }, { "code": null, "e": 11446, "s": 11434, "text": "varaprasadh" }, { "code": null, "e": 11458, "s": 11446, "text": "gopinath_mb" }, { "code": null, "e": 11468, "s": 11458, "text": "patel2127" }, { "code": null, "e": 11473, "s": 11468, "text": "Trie" }, { "code": null, "e": 11497, "s": 11473, "text": "Advanced Data Structure" }, { "code": null, "e": 11502, "s": 11497, "text": "Trie" }, { "code": null, "e": 11600, "s": 11502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11629, "s": 11600, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 11656, "s": 11629, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 11681, "s": 11656, "text": "LRU Cache Implementation" }, { "code": null, "e": 11704, "s": 11681, "text": "Introduction of B-Tree" }, { "code": null, "e": 11738, "s": 11704, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 11776, "s": 11738, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 11816, "s": 11776, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 11852, "s": 11816, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 11880, "s": 11852, "text": "AVL Tree | Set 2 (Deletion)" } ]
How to print the content of an object in JavaScript ?
09 May, 2019 The JSON.stringify() method is used to print the JavaScript object.JSON.stringify() Method: The JSON.stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it. While developing an application using JavaScript many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server. The data has to be in the form of the strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() function. Syntax: JSON.stringify(value, replacer, space) Example 1: This example converting the object to a string by simply traversing it and appending the object property and value to the string. <!DOCTYPE html> <html> <head> <title> Print the content of object using JavaScript </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> Print JavaScript Object. </p> <button onclick = "gfg_Run()"> print object </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); var GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13' }; var printObj = function(obj) { var string = ''; for(var prop in obj) { if(typeof obj[prop] == 'string') { string+= prop + ': ' + obj[prop]+'; </br>'; } else { string+= prop + ': { </br>' + print(obj[prop]) + '}'; } } return string; } function gfg_Run() { el_down.innerHTML = printObj(GFG_object); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example using the JSON.stringify() method to convert the object to string. <!DOCTYPE html> <html> <head> <title> JavaScript | Print content of object </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p> Print JavaScript Object. </p> <button onclick = "gfg_Run()"> print object </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_down = document.getElementById("GFG_DOWN"); var GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13' }; function gfg_Run() { el_down.innerHTML = JSON.stringify(GFG_object); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n09 May, 2019" }, { "code": null, "e": 610, "s": 53, "text": "The JSON.stringify() method is used to print the JavaScript object.JSON.stringify() Method: The JSON.stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it. While developing an application using JavaScript many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server. The data has to be in the form of the strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() function." }, { "code": null, "e": 618, "s": 610, "text": "Syntax:" }, { "code": null, "e": 657, "s": 618, "text": "JSON.stringify(value, replacer, space)" }, { "code": null, "e": 798, "s": 657, "text": "Example 1: This example converting the object to a string by simply traversing it and appending the object property and value to the string." }, { "code": "<!DOCTYPE html> <html> <head> <title> Print the content of object using JavaScript </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p> Print JavaScript Object. </p> <button onclick = \"gfg_Run()\"> print object </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); var GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13' }; var printObj = function(obj) { var string = ''; for(var prop in obj) { if(typeof obj[prop] == 'string') { string+= prop + ': ' + obj[prop]+'; </br>'; } else { string+= prop + ': { </br>' + print(obj[prop]) + '}'; } } return string; } function gfg_Run() { el_down.innerHTML = printObj(GFG_object); } </script> </body> </html> ", "e": 2214, "s": 798, "text": null }, { "code": null, "e": 2222, "s": 2214, "text": "Output:" }, { "code": null, "e": 2253, "s": 2222, "text": "Before clicking on the button:" }, { "code": null, "e": 2283, "s": 2253, "text": "After clicking on the button:" }, { "code": null, "e": 2374, "s": 2283, "text": "Example 2: This example using the JSON.stringify() method to convert the object to string." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Print content of object </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p> Print JavaScript Object. </p> <button onclick = \"gfg_Run()\"> print object </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); var GFG_object = { prop_1: 'val_11', prop_2: 'val_12', prop_3: 'val_13' }; function gfg_Run() { el_down.innerHTML = JSON.stringify(GFG_object); } </script> </body> </html> ", "e": 3363, "s": 2374, "text": null }, { "code": null, "e": 3371, "s": 3363, "text": "Output:" }, { "code": null, "e": 3402, "s": 3371, "text": "Before clicking on the button:" }, { "code": null, "e": 3432, "s": 3402, "text": "After clicking on the button:" }, { "code": null, "e": 3443, "s": 3432, "text": "JavaScript" }, { "code": null, "e": 3460, "s": 3443, "text": "Web Technologies" }, { "code": null, "e": 3487, "s": 3460, "text": "Web technologies Questions" }, { "code": null, "e": 3585, "s": 3487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3646, "s": 3585, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3718, "s": 3646, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3758, "s": 3718, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3800, "s": 3758, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3841, "s": 3800, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3874, "s": 3841, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3936, "s": 3874, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3997, "s": 3936, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4047, "s": 3997, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create a copy of an object in PHP?
01 Dec, 2021 An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.Syntax: $copy_object_name = clone $object_to_be_copied Program 1: Program to create copy of an object. php <?php // Program to create copy of an object // Creating classclass GFG { public $data1; public $data2; public $data3;} // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Set values of $obj object$obj->data1 = "Geeks";$obj->data2 = "for";$obj->data3 = "Geeks"; // Set values of copied object$copy->data1 = "Computer ";$copy->data2 = "science ";$copy->data3 = "portal"; // Print values of $obj objectecho "$obj->data1$obj->data2$obj->data3\n"; // Print values of $copy objectecho "$copy->data1$copy->data2$copy->data3\n"; ?> GeeksforGeeks Computer science portal Example 2: Below program distinguishes clone from assignment ( = ) operator. php <?php // Program to create copy of an object // Creating classclass GFG { public $data1; public $data2; public $data3; } // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Creating object without clone keyword$obj_ref = $obj; // Set values of $obj object$obj->data1 = "Geeks";$obj->data2 = "for";$obj->data3 = "Geeks"; // Set values of copied object$copy->data1 = "Python ";$copy->data2 = "for ";$copy->data3 = "Machine learning"; // Print values of $obj objectecho "$obj->data1$obj->data2$obj->data3\n"; // Print values of $copy objectecho "$copy->data1$copy->data2$copy->data3\n"; // Print values of without clone objectecho "$obj_ref->data1$obj_ref->data2$obj_ref->data3\n"; ?> GeeksforGeeks Python for Machine learning GeeksforGeeks Note: It is clear that cloned object have different values than original object but original and referenced object created by using ‘=’ operator have same value. References:https://www.php.net/manual/en/language.oop5.cloning.php surindertarika1234 Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP? Comparing two dates in PHP
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2021" }, { "code": null, "e": 373, "s": 28, "text": "An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.Syntax: " }, { "code": null, "e": 420, "s": 373, "text": "$copy_object_name = clone $object_to_be_copied" }, { "code": null, "e": 469, "s": 420, "text": "Program 1: Program to create copy of an object. " }, { "code": null, "e": 473, "s": 469, "text": "php" }, { "code": "<?php // Program to create copy of an object // Creating classclass GFG { public $data1; public $data2; public $data3;} // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Set values of $obj object$obj->data1 = \"Geeks\";$obj->data2 = \"for\";$obj->data3 = \"Geeks\"; // Set values of copied object$copy->data1 = \"Computer \";$copy->data2 = \"science \";$copy->data3 = \"portal\"; // Print values of $obj objectecho \"$obj->data1$obj->data2$obj->data3\\n\"; // Print values of $copy objectecho \"$copy->data1$copy->data2$copy->data3\\n\"; ?>", "e": 1049, "s": 473, "text": null }, { "code": null, "e": 1087, "s": 1049, "text": "GeeksforGeeks\nComputer science portal" }, { "code": null, "e": 1167, "s": 1089, "text": "Example 2: Below program distinguishes clone from assignment ( = ) operator. " }, { "code": null, "e": 1171, "s": 1167, "text": "php" }, { "code": "<?php // Program to create copy of an object // Creating classclass GFG { public $data1; public $data2; public $data3; } // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Creating object without clone keyword$obj_ref = $obj; // Set values of $obj object$obj->data1 = \"Geeks\";$obj->data2 = \"for\";$obj->data3 = \"Geeks\"; // Set values of copied object$copy->data1 = \"Python \";$copy->data2 = \"for \";$copy->data3 = \"Machine learning\"; // Print values of $obj objectecho \"$obj->data1$obj->data2$obj->data3\\n\"; // Print values of $copy objectecho \"$copy->data1$copy->data2$copy->data3\\n\"; // Print values of without clone objectecho \"$obj_ref->data1$obj_ref->data2$obj_ref->data3\\n\"; ?>", "e": 1908, "s": 1171, "text": null }, { "code": null, "e": 1964, "s": 1908, "text": "GeeksforGeeks\nPython for Machine learning\nGeeksforGeeks" }, { "code": null, "e": 2195, "s": 1966, "text": "Note: It is clear that cloned object have different values than original object but original and referenced object created by using ‘=’ operator have same value. References:https://www.php.net/manual/en/language.oop5.cloning.php" }, { "code": null, "e": 2214, "s": 2195, "text": "surindertarika1234" }, { "code": null, "e": 2221, "s": 2214, "text": "Picked" }, { "code": null, "e": 2225, "s": 2221, "text": "PHP" }, { "code": null, "e": 2238, "s": 2225, "text": "PHP Programs" }, { "code": null, "e": 2255, "s": 2238, "text": "Web Technologies" }, { "code": null, "e": 2282, "s": 2255, "text": "Web technologies Questions" }, { "code": null, "e": 2286, "s": 2282, "text": "PHP" }, { "code": null, "e": 2384, "s": 2286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2434, "s": 2384, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2474, "s": 2434, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2524, "s": 2474, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2569, "s": 2524, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2596, "s": 2569, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2646, "s": 2596, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2686, "s": 2646, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2738, "s": 2686, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 2788, "s": 2738, "text": "How to check whether an array is empty using PHP?" } ]
Django project – Creating a Basic E-commerce Website for Displaying Products
24 Feb, 2022 Project Title – Basic Ecommerce Website using Django Django is a powerful framework based on python. Here we will see how to create a basic e-commerce website in Django. This project includes storing products in the database and show them on the website. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now when you have successfully installed Django. Create a new project – django-admin startproject ecom Now create a new app called frontend inside the ecom project. Now we have 1 project and 1 app inside of that project.] django-admin startapp frontend Directory structure – In ecom> urls.py add the following lines. This file handles main project URLs. But we don’t want to disturb it, so we will do our work in frontend > URLs.py. And for that we need to include frontend > URLs inside the ecom> URLs. urlpatterns = [ path('admin/', admin.site.urls), path('', include('frontend.urls')), ] Add a product model here. class Product(models.Model): productname = models.CharField(max_length=200) price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField() image = models.CharField(max_length=5000, null=True, blank=True) To know more about Django models, check out – Django Models Just after creating model, we should register that form into admin.py. from django.contrib import admin from .models import * admin.site.register(Product) In frontend > views.py we write a function to get and display products from our database. from django.shortcuts import render from .models import * def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) Here we will set dynamic URL which can be useful to display our products. In frontend > urls.py from django.urls import path from . import views urlpatterns = [ path('products/', views.products, name='products'), ] Creating template depends upon how you want to display products on website. For displaying products we have shared a simple code. Add it in frontend > templates > products.html {% for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.productname }}</h5> <p class="card-text">{{ product.description }}</p> <p class="card-text">Price - {{ product.price }}</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> {% endfor %} Now its time to migrate our model into database. First, we have to create migrations. For that type following code into terminal. python manage.py makemigrations After creating migrations type following code to apply those migrations python manage.py migrate To know more about makemigrations and migrate, check out – Basic App Model – Makemigrations and Migrate Now, create Django superuser for handling admin stuff. Type following command in terminal django-admin createsuperuser Then it will ask for username, email and password. After creating superuser, in terminal type, python manage.py runserver to start the server and go to admin panel (http://localhost:8000/admin) and add some products to the database. Thats it. Your basic eCommerce site is ready where you can display your products sooda367 gabaa406 avtarkumar719 Python Django Python Framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2022" }, { "code": null, "e": 108, "s": 54, "text": "Project Title – Basic Ecommerce Website using Django " }, { "code": null, "e": 311, "s": 108, "text": "Django is a powerful framework based on python. Here we will see how to create a basic e-commerce website in Django. This project includes storing products in the database and show them on the website. " }, { "code": null, "e": 398, "s": 311, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 449, "s": 398, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 482, "s": 449, "text": "How to Create an App in Django ?" }, { "code": null, "e": 555, "s": 482, "text": "Now when you have successfully installed Django. Create a new project – " }, { "code": null, "e": 587, "s": 555, "text": "django-admin startproject ecom " }, { "code": null, "e": 706, "s": 587, "text": "Now create a new app called frontend inside the ecom project. Now we have 1 project and 1 app inside of that project.]" }, { "code": null, "e": 737, "s": 706, "text": "django-admin startapp frontend" }, { "code": null, "e": 761, "s": 737, "text": "Directory structure – " }, { "code": null, "e": 993, "s": 763, "text": "In ecom> urls.py add the following lines. This file handles main project URLs. But we don’t want to disturb it, so we will do our work in frontend > URLs.py. And for that we need to include frontend > URLs inside the ecom> URLs. " }, { "code": null, "e": 1088, "s": 993, "text": "urlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('frontend.urls')),\n]" }, { "code": null, "e": 1115, "s": 1088, "text": "Add a product model here. " }, { "code": null, "e": 1365, "s": 1115, "text": "class Product(models.Model):\n productname = models.CharField(max_length=200)\n price = models.DecimalField(max_digits=5, decimal_places=2)\n description = models.TextField()\n image = models.CharField(max_length=5000, null=True, blank=True)" }, { "code": null, "e": 1425, "s": 1365, "text": "To know more about Django models, check out – Django Models" }, { "code": null, "e": 1497, "s": 1425, "text": "Just after creating model, we should register that form into admin.py. " }, { "code": null, "e": 1583, "s": 1497, "text": "from django.contrib import admin\nfrom .models import *\n\n\nadmin.site.register(Product)" }, { "code": null, "e": 1674, "s": 1583, "text": "In frontend > views.py we write a function to get and display products from our database. " }, { "code": null, "e": 1860, "s": 1674, "text": "from django.shortcuts import render\nfrom .models import *\n\ndef products(request):\n products = Product.objects.all()\n return render(request, 'products.html', {'products':products})" }, { "code": null, "e": 1957, "s": 1860, "text": " Here we will set dynamic URL which can be useful to display our products. In frontend > urls.py" }, { "code": null, "e": 2083, "s": 1957, "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n path('products/', views.products, name='products'),\n\n]" }, { "code": null, "e": 2260, "s": 2083, "text": "Creating template depends upon how you want to display products on website. For displaying products we have shared a simple code. Add it in frontend > templates > products.html" }, { "code": null, "e": 2684, "s": 2260, "text": "{% for product in products %}\n<div class=\"card\" style=\"width: 18rem;\">\n <img class=\"card-img-top\" src=\"{{ product.image }}\" alt=\"Card image cap\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">{{ product.productname }}</h5>\n <p class=\"card-text\">{{ product.description }}</p>\n <p class=\"card-text\">Price - {{ product.price }}</p>\n <a href=\"#\" class=\"btn btn-primary\">Buy Now</a>\n </div>\n</div>\n{% endfor %}" }, { "code": null, "e": 2814, "s": 2684, "text": "Now its time to migrate our model into database. First, we have to create migrations. For that type following code into terminal." }, { "code": null, "e": 2846, "s": 2814, "text": "python manage.py makemigrations" }, { "code": null, "e": 2918, "s": 2846, "text": "After creating migrations type following code to apply those migrations" }, { "code": null, "e": 2943, "s": 2918, "text": "python manage.py migrate" }, { "code": null, "e": 3047, "s": 2943, "text": "To know more about makemigrations and migrate, check out – Basic App Model – Makemigrations and Migrate" }, { "code": null, "e": 3138, "s": 3047, "text": "Now, create Django superuser for handling admin stuff. Type following command in terminal " }, { "code": null, "e": 3167, "s": 3138, "text": "django-admin createsuperuser" }, { "code": null, "e": 3219, "s": 3167, "text": "Then it will ask for username, email and password. " }, { "code": null, "e": 3263, "s": 3219, "text": "After creating superuser, in terminal type," }, { "code": null, "e": 3290, "s": 3263, "text": "python manage.py runserver" }, { "code": null, "e": 3403, "s": 3290, "text": " to start the server and go to admin panel (http://localhost:8000/admin) and add some products to the database." }, { "code": null, "e": 3485, "s": 3403, "text": "Thats it. Your basic eCommerce site is ready where you can display your products " }, { "code": null, "e": 3494, "s": 3485, "text": "sooda367" }, { "code": null, "e": 3503, "s": 3494, "text": "gabaa406" }, { "code": null, "e": 3517, "s": 3503, "text": "avtarkumar719" }, { "code": null, "e": 3531, "s": 3517, "text": "Python Django" }, { "code": null, "e": 3548, "s": 3531, "text": "Python Framework" }, { "code": null, "e": 3555, "s": 3548, "text": "Python" }, { "code": null, "e": 3653, "s": 3555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3671, "s": 3653, "text": "Python Dictionary" }, { "code": null, "e": 3713, "s": 3671, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3735, "s": 3713, "text": "Enumerate() in Python" }, { "code": null, "e": 3770, "s": 3735, "text": "Read a file line by line in Python" }, { "code": null, "e": 3796, "s": 3770, "text": "Python String | replace()" }, { "code": null, "e": 3828, "s": 3796, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3857, "s": 3828, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3884, "s": 3857, "text": "Python Classes and Objects" }, { "code": null, "e": 3914, "s": 3884, "text": "Iterate over a list in Python" } ]
Program for addition of two matrices
23 Jun, 2022 The below program adds two square matrices of size 4*4, we can change N for different dimensions. Implementation: C++ C Java Python3 C# PHP Javascript // C++ program for addition// of two matrices#include <bits/stdc++.h>using namespace std;#define N 4 // This function adds A[][] and B[][], and stores// the result in C[][]void add(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; add(A, B, C); cout << "Result matrix is " << endl; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << C[i][j] << " "; cout << endl; } return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#define N 4 // This function adds A[][] and B[][], and stores// the result in C[][]void add(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; add(A, B, C); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", C[i][j]); printf("\n"); } return 0;} // Java program for addition// of two matrices class GFG{ static final int N = 4; // This function adds A[][] and B[][], and stores // the result in C[][] static void add(int A[][], int B[][], int C[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int C[][] = new int[N][N]; int i, j; add(A, B, C); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(C[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal. # Python3 program for addition# of two matrices N = 4 # This function adds A[][]# and B[][], and stores# the result in C[][]def add(A,B,C): for i in range(N): for j in range(N): C[i][j] = A[i][j] + B[i][j] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] C=A[:][:] # To store result add(A, B, C) print("Result matrix is")for i in range(N): for j in range(N): print(C[i][j], " ", end='') print() # This code is contributed# by Anant Agarwal. // C# program for addition// of two matricesusing System; class GFG{ static int N = 4; // This function adds A[][] and B[][], and stores // the result in C[][] static void add(int[,] A, int [,]B, int [,]C) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i,j] = A[i,j] + B[i,j]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int [,]C = new int[N,N]; int i, j; add(A, B, C); Console.WriteLine("Result matrix is "); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) Console.Write(C[i,j] + " "); Console.WriteLine(); } }} // This code is contributed by vt_m. <?php// This function adds A[][] and// B[][], and stores the result in C[][]function add(&$A, &$B, &$C){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $C[$i][$j] = $A[$i][$j] + $B[$i][$j];} // Driver code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $N = 4;add($A, $B, $C); echo "Result matrix is \n";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $C[$i][$j]; echo " "; } echo "\n" ;} // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript program for addition// of two matrices let N = 4; // This function adds A[][] and B[][], and stores// the result in C[][]function add(A, B, C){ let i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} // Driver code let A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; let B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; // To store result let C = new Array(N); for (let k = 0; k < N; k++) C[k] = new Array(N); let i, j; add(A, B, C); document.write("Result matrix is <br>"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(C[i][j] + " "); document.write("<br>"); } </script> Output: Result matrix is 2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8 The program can be extended for rectangular matrices. The following post can be useful for extending this program. How to pass a 2D array as a parameter in C? Time complexity: O(n2). Auxiliary space: O(n2). Shivi_Aggarwal rathbhupendra subhammahato348 rishavmahato348 hardikkoriintern Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 151, "s": 52, "text": "The below program adds two square matrices of size 4*4, we can change N for different dimensions. " }, { "code": null, "e": 167, "s": 151, "text": "Implementation:" }, { "code": null, "e": 171, "s": 167, "text": "C++" }, { "code": null, "e": 173, "s": 171, "text": "C" }, { "code": null, "e": 178, "s": 173, "text": "Java" }, { "code": null, "e": 186, "s": 178, "text": "Python3" }, { "code": null, "e": 189, "s": 186, "text": "C#" }, { "code": null, "e": 193, "s": 189, "text": "PHP" }, { "code": null, "e": 204, "s": 193, "text": "Javascript" }, { "code": "// C++ program for addition// of two matrices#include <bits/stdc++.h>using namespace std;#define N 4 // This function adds A[][] and B[][], and stores// the result in C[][]void add(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; add(A, B, C); cout << \"Result matrix is \" << endl; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << C[i][j] << \" \"; cout << endl; } return 0;} // This code is contributed by rathbhupendra", "e": 1114, "s": 204, "text": null }, { "code": "#include <stdio.h>#define N 4 // This function adds A[][] and B[][], and stores// the result in C[][]void add(int A[][N], int B[][N], int C[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[N][N]; // To store result int i, j; add(A, B, C); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", C[i][j]); printf(\"\\n\"); } return 0;}", "e": 1891, "s": 1114, "text": null }, { "code": "// Java program for addition// of two matrices class GFG{ static final int N = 4; // This function adds A[][] and B[][], and stores // the result in C[][] static void add(int A[][], int B[][], int C[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int C[][] = new int[N][N]; int i, j; add(A, B, C); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(C[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.", "e": 2990, "s": 1891, "text": null }, { "code": "# Python3 program for addition# of two matrices N = 4 # This function adds A[][]# and B[][], and stores# the result in C[][]def add(A,B,C): for i in range(N): for j in range(N): C[i][j] = A[i][j] + B[i][j] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] C=A[:][:] # To store result add(A, B, C) print(\"Result matrix is\")for i in range(N): for j in range(N): print(C[i][j], \" \", end='') print() # This code is contributed# by Anant Agarwal.", "e": 3579, "s": 2990, "text": null }, { "code": "// C# program for addition// of two matricesusing System; class GFG{ static int N = 4; // This function adds A[][] and B[][], and stores // the result in C[][] static void add(int[,] A, int [,]B, int [,]C) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i,j] = A[i,j] + B[i,j]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; // To store result int [,]C = new int[N,N]; int i, j; add(A, B, C); Console.WriteLine(\"Result matrix is \"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) Console.Write(C[i,j] + \" \"); Console.WriteLine(); } }} // This code is contributed by vt_m.", "e": 4639, "s": 3579, "text": null }, { "code": "<?php// This function adds A[][] and// B[][], and stores the result in C[][]function add(&$A, &$B, &$C){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $C[$i][$j] = $A[$i][$j] + $B[$i][$j];} // Driver code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $B = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $N = 4;add($A, $B, $C); echo \"Result matrix is \\n\";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $C[$i][$j]; echo \" \"; } echo \"\\n\" ;} // This code is contributed// by Shivi_Aggarwal?>", "e": 5373, "s": 4639, "text": null }, { "code": "<script> // Javascript program for addition// of two matrices let N = 4; // This function adds A[][] and B[][], and stores// the result in C[][]function add(A, B, C){ let i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j];} // Driver code let A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; let B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]; // To store result let C = new Array(N); for (let k = 0; k < N; k++) C[k] = new Array(N); let i, j; add(A, B, C); document.write(\"Result matrix is <br>\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(C[i][j] + \" \"); document.write(\"<br>\"); } </script>", "e": 6264, "s": 5373, "text": null }, { "code": null, "e": 6273, "s": 6264, "text": "Output: " }, { "code": null, "e": 6322, "s": 6273, "text": "Result matrix is\n2 2 2 2\n4 4 4 4\n6 6 6 6\n8 8 8 8" }, { "code": null, "e": 6438, "s": 6322, "text": "The program can be extended for rectangular matrices. The following post can be useful for extending this program. " }, { "code": null, "e": 6482, "s": 6438, "text": "How to pass a 2D array as a parameter in C?" }, { "code": null, "e": 6530, "s": 6482, "text": "Time complexity: O(n2). Auxiliary space: O(n2)." }, { "code": null, "e": 6545, "s": 6530, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6559, "s": 6545, "text": "rathbhupendra" }, { "code": null, "e": 6575, "s": 6559, "text": "subhammahato348" }, { "code": null, "e": 6591, "s": 6575, "text": "rishavmahato348" }, { "code": null, "e": 6608, "s": 6591, "text": "hardikkoriintern" }, { "code": null, "e": 6615, "s": 6608, "text": "Matrix" }, { "code": null, "e": 6634, "s": 6615, "text": "School Programming" }, { "code": null, "e": 6641, "s": 6634, "text": "Matrix" } ]
What is CSS flexbox ?
31 Oct, 2021 CSS Flexible Layout Box, popularly known as Flexbox is a powerful one-dimensional layout model. It helps to lay, align and distribute items (children) efficiently inside a container (parent). Important Features: One-dimensional layout model: Flex is a one-dimensional layout model as it can only deal with items either horizontally as rows or vertically as columns. On the contrary, the CSS Grid layout can handle rows and columns together. Creates flexible and responsive layouts: Flexbox gives flex container the ability to customize the items within it, depending on different screen sizes. A flex container can expand its children’s items to fill the available space or it can also shrink them to prevent overflow. Direction-agnostic: Flexbox is free from any directional constraints unlike Block (vertically biased) and Inline (horizontally biased). Super easy to use: It is easy to align items in Flexbox, unlike using float and positioning which are a little frustrating and sometimes difficult to use. Flexbox Architecture: There are two aspects of a Flexbox: Flex container and Flex item The flex items can be laid out either along the main axis (starting from the main start and ending at the main end) or along the cross axis (starting from the cross start and ending at the cross end). Main axis: Flex items are laid out along this axis, either horizontally or vertically based upon the flex-direction. Cross axis: It is perpendicular to the main axis and its direction depends on the direction of the main axis. Main size: It is the width/height of the flex item depending on the main dimension. Cross size: It is the width/height of the flex item depending on the cross dimension. To understand the different Flexbox properties, let us take an example by creating an HTML file, along with a CSS file. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>CSS Flexbox</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="container"> <div class="item item-1">1</div> <div class="item item-2">2</div> <div class="item item-3">3</div> <div class="item item-4">4</div> </div></body> </html> This is our CSS code in which we will be styling the flex-container and flex-item. CSS .container { border: 5px solid rgb(0, 0, 0); background-color: rgb(245 197 221);}.item { border: 5px solid rgb(0, 0, 0); background-color: rgb(141, 178, 226); margin: 10px; padding: 20px; height: 100px; width: 100px; font-weight: bold; font-size: 45px;} Output: From the above output, the items are aligned vertically, by default, and the default display is block-level. The pink area is the container and the blue boxes within it are the items. Properties for the Parent/Flex Container: display: Let’s make the container flex by setting its display to flex inside the .container of our CSS file. .container{ display: flex; border: 5px solid rgb(0, 0, 0); background-color: rgb(245 197 221); } Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>CSS Flexbox</title> <style> .container { display: flex; border: 5px solid rgb(0, 0, 0); background-color: rgb(245 197 221); } .item { border: 5px solid rgb(0, 0, 0); background-color: rgb(141, 178, 226); margin: 10px; padding: 20px; height: 100px; width: 100px; font-weight: bold; font-size: 45px; } </style></head> <body> <div class="container"> <div class="item item-1">1</div> <div class="item item-2">2</div> <div class="item item-3">3</div> <div class="item item-4">4</div> </div></body> </html> Output: As you can see, after applying the display: flex property, the items have been aligned horizontally as the default flex-direction of flexbox is row. display: flex flex-direction: It sets the direction of the flex container’s main axis and specifies how items will be placed inside the container. Syntax: flex-direction: attribute value Attribute Values: row: Flex items are displayed horizontally along a row. column: Flex items are displayed vertically along a column. row reverse: Flex items are displayed horizontally along a row but in reverse order. column reverse: Flex items are displayed vertically along a column but in reverse order. Note: The display direction, by default, is row. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex-direction</title> <link rel="stylesheet" href="style_flex-direction.css" /> </head> <body> <ul class="container row"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> </ul> <ul class="container column"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> </ul> <ul class="container row-reverse"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> </ul> <ul class="container column-reverse"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 5px; padding: 0; float: left; height: 270px; width: 170px; border: 2px solid black; display: flex;}.row { flex-direction: row;}.column { flex-direction: column;}.row-reverse { flex-direction: row-reverse;}.column-reverse { flex-direction: column-reverse;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; height: 40px; width: 40px; margin: 2px; padding: 2px; font-weight: bold; border: 2px solid black;} Output: row, column, row-reverse, column-reverse flex-wrap: It specifies whether the flex container will have a single line or have multiple lines. Syntax: flex-wrap: attribute value Attribute values: nowrap (default): It specifies that the flex items will not wrap and will be laid out in a single line. It may cause the flex container to overflow. wrap: It specifies that the flex items will wrap if necessary, and will be laid out in multiple lines. wrap-reverse: It is the same as a wrap, but the flex items will wrap in reverse order in this case. initial: It represents the value specified as the property’s initial value. inherit: It represents the computed value of the property on the element’s parent. Note: We have increased the number of items inside the container to understand the flex-wrap effect better. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex-wrap</title> <link rel="stylesheet" href="style_flex-wrap.css" /> </head> <body> <ul class="container no-wrap"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> <li class="item"> <p>6</p> </li> <li class="item"> <p>7</p> </li> <li class="item"> <p>8</p> </li> </ul> <ul class="container wrap"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> <li class="item"> <p>6</p> </li> <li class="item"> <p>7</p> </li> <li class="item"> <p>8</p> </li> </ul> <ul class="container wrap-reverse"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> <li class="item"> <p>6</p> </li> <li class="item"> <p>7</p> </li> <li class="item"> <p>8</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 5px; padding: 0; float: left; width: 250px; border: 2px solid black; display: flex;}.no-wrap { flex-wrap: nowrap;}.wrap { flex-wrap: wrap;}.wrap-reverse { flex-wrap: wrap-reverse;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; height: 40px; width: 40px; margin: 2px; padding: 2px; font-weight: bold; border: 2px solid black;} Output: nowrap, wrap, wrap-reverse flex-flow: It is a shorthand for flex-direction and flex-wrap. By default, flex-direction is row, and flex-wrap is nowrap. Syntax: flex-flow: flex-direction flex-wrap For example, we can specify flex-direction as a row and flex-wrap as a wrap. .container{ flex-flow: row wrap; } row wrap justify-content: It defines how items are positioned along the main/primary axis of the current line. Syntax: justify-content: attribute value Attribute values: flex-start (default): Flex items are positioned at the beginning of the container. flex-end: Flex items are positioned at the end of the container. center: Flex items are positioned in the center of the container. space-between: Flex items are distributed with even spacing, the first item will be at the start and the last item will be at the end of the container. space-around: Flex items are distributed with even spacing, with half the amount of space at the start of the first item and at the end of the last item. space-evenly: Flex items are evenly distributed within the alignment container along the main axis. initial: It represents the value specified as the property’s initial value. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>justify-content</title> <link rel="stylesheet" href="style_justify-content.css" /> </head> <body> <ul class="container flexStart"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container flexEnd"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container center"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container spaceBetween"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container spaceAround"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container spaceEvenly"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 5px; padding: 0; border: 2px solid black; display: flex;}.flexStart { justify-content: flex-start;}.flexEnd { justify-content: flex-end;}.center { justify-content: center;}.spaceBetween { justify-content: space-between;}.spaceAround { justify-content: space-around;}.spaceEvenly { justify-content: space-evenly;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); width: 50px; height: 50px; margin: 5px; line-height: 10px; font-weight: bold; border: 2px solid black;} Output: flex-start, flex-end, center, space between, space-around, space-evenly align-content: When there is extra space in the cross-axis, align-content aligns multiple lines within the container. It is similar to justify-content which aligns individual items within the main axis. Note: This property only works when the Flexbox has multiple lines. Syntax: align-content: attribute value Attribute values: flex-start: Lines are aligned towards the beginning of the container. flex-end: Lines are aligned towards the end of the container. center: Lines are aligned towards the center of the container. space-between: Lines are evenly distributed, the first item will be at the start and the last item will be at the end of the container. space-around: Lines are evenly distributed, with half the amount of space at the start of the first item and at the end of the last item. stretch(default): Line stretches to take up the remaining space. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>align-content</title> <link rel="stylesheet" href="style_align-content.css" /></head> <body> <ul class="container flexStart"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container flexEnd"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container center"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container spaceBetween"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container spaceAround"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container stretch"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 5px; float: left; height: 500px; width: 50px; border: 2px solid black; display: flex; flex-wrap: wrap; flex-direction: row;}.flexStart { align-content: flex-start;}.flexEnd { align-content: flex-end;}.center { align-content: center;}.spaceBetween { align-content: space-between;}.spaceAround { align-content: space-around;}.stretch { align-content: stretch;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 50px; margin: 5px; line-height: 10px; font-weight: bold; border: 2px solid black;} Output: flex-start, flex-end, center, space-between, space-around, stretch align-items: It defines how flex items will be aligned along the cross axis of the current line of the container. Syntax: align-items: stretch|center|flex-start|flex-end|baseline|initial| inherit; Attribute Values: flex-start: Items are aligned along the cross-start line. flex-end: Items are aligned along the cross-end line. center: The items are centered in the cross-axis. baseline: The items are aligned in a line in such a matter that their baselines align. stretch(default): The items stretch to fill the container. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>align-item</title> <link rel="stylesheet" href="style_align-item.css" /> </head> <body> <ul class="container flexStart"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container flexEnd"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container center"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container baseline"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul> <ul class="container stretch"> <li class="item"> <p>1</p> </li> <li class="item"> <p>2</p> </li> <li class="item"> <p>3</p> </li> <li class="item"> <p>4</p> </li> <li class="item"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 5px; float: left; height: 300px; width: 150px; border: 2px solid black; display: flex; flex-direction: row;}.flexStart { align-items: flex-start;}.flexEnd { align-items: flex-end;}.center { align-items: center;}.baseline { align-items: baseline;}.stretch { align-items: stretch;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 50px; line-height: 10px; font-weight: bold; border: 2px solid black;} Output: flex-start ,flex-end, center, baseline, stretch Please refer to the Difference between align-content and align-items article for the detailed differences. Properties for the Child/Flex Item: order: It assigns the order in which children of a flex container appear within the flex container. Syntax: order: <integer> Flex items have a default order value of 0. That is why items assigned with values greater than 0 appear after items for which no value has been set. The reverse applies for items with values lesser than 0, they appear before the items having default order value or order value more than 0. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>order</title> <link rel="stylesheet" href="style_order.css" /> </head> <body> <ul class="container"> <li class="item item-1"> <p>1</p> </li> <li class="item item-2"> <p>2</p> </li> <li class="item item-3"> <p>3</p> </li> <li class="item item-4"> <p>4</p> </li> <li class="item item-5"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 0; padding: 0; float: left; height: 200px; width: 400px; border: 2px solid black; display: flex; flex-wrap: wrap; flex-direction: row;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { order: 3;}.item-4 { order: -3;} Output: As item 1 has order 3, its order is higher than every item’s order so it is placed at the end and item 4 is placed at the beginning as its order (-3) is the lowest order among other items. flex: It specifies the components of a flexible length and it is a shorthand property for: flex-grow: It specifies how much the item will grow compared to other items inside that container. flex-shrink: It specifies how much the item will shrink compared to other items inside that container. flex-basis: It specifies the initial size of the flexible item. Syntax: flex: flex-grow flex-shrink flex-basis|auto|initial|inherit; Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex</title> <link rel="stylesheet" href="style_flex.css" /> </head> <body> <ul class="container"> <li class="item item-1"> <p>1</p> </li> <li class="item item-2"> <p>2</p> </li> <li class="item item-3"> <p>3</p> </li> <li class="item item-4"> <p>4</p> </li> <li class="item item-5"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 500px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex: 0 1 auto;}.item-2 { flex: 2 2 auto;}.item-3 { flex: 0 1 auto;}.item-4 { flex: 0 1 auto;}.item-5 { flex: 0 1 auto;} Output: As we can clearly see, item 2 with the highest flex-grow and flex-shrink value expand and shrinks the most. It has flex-grow value and shrinks value both as 2, while other items have 0 and 1 flex-grow and flex-shrink values respectively. The flex-basis for all items have been set as auto. flex-grow: It sets the flex-grow property of a flex item and defines its ability to grow. Default flex-grow value is 0. Syntax: flex-grow: <number> Note: Negative numbers are invalid. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex-grow</title> <link rel="stylesheet" href="style_flex-grow.css" /> </head> <body> <ul class="container"> <li class="item item-1"> <p>1</p> </li> <li class="item item-2"> <p>2</p> </li> <li class="item item-3"> <p>3</p> </li> <li class="item item-4"> <p>4</p> </li> <li class="item item-5"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex-grow: 0;}.item-2 { flex-grow: 2;}.item-3 { flex-grow: 0;}.item-4 { flex-grow: 0;}.item-5 { flex-grow: 0;} Output: As we can clearly see, item 2 with flex-grow value more than others expands more than the other four items. flex-shrink: It sets the flex-shrink property for a flex item and defines the ability for a flex item to shrink. Default flex-grow value is 1. Syntax: flex-shrink: <number> Note: Negative numbers are invalid. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex-shrink</title> <link rel="stylesheet" href="style_flex-shrink.css" /> </head> <body> <ul class="container"> <li class="item item-1"> <p>1</p> </li> <li class="item item-2"> <p>2</p> </li> <li class="item item-3"> <p>3</p> </li> <li class="item item-4"> <p>4</p> </li> <li class="item item-5"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex-shrink: 1;}.item-2 { flex-shrink: 2;}.item-3 { flex-shrink: 1;}.item-4 { flex-shrink: 1;}.item-5 { flex-shrink: 1;} Output: As we can clearly see, item 2 with flex-shrink value more than others shrinks more than the other four items. flex-basis: It defines the initial size of a flex item. Syntax: flex-basis: content | <'width'> Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>flex-basis</title> <link rel="stylesheet" href="style_flex-basis.css" /> </head> <body> <ul class="container"> <li class="item px"> <p>px</p> </li> <li class="item percentage"> <p>percentage</p> </li> <li class="item auto"> <p>auto</p> </li> <li class="item initial"> <p>initial</p> </li> <li class="item inherit"> <p>inherit</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); padding: 0; margin: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.px { flex-basis: 50px;}.percentage { flex-basis: 75%;}.auto { flex-basis: auto;}.initial { flex-basis: initial;}.inherit { flex-basis: inherit;} Output: align-self: It defines how individual flex items are aligned along the cross-axis. Syntax: align-self: auto|stretch|center|flex-start|flex-end|baseline| initial|inherit; Attribute Value: flex-start: Aligns items at the beginning of the container. flex-end: Aligns items at the end of the container. center: Aligns items at the center of the container. stretch: Aligns items to fit the container. baseline: Aligns items to the baseline of the container. auto (default): Item inherits the align-items property of parent container. initial: Sets to the default value. inherit: Item inherits align-self property from its parent element. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>align-self</title> <link rel="stylesheet" href="style_align-self.css" /> </head> <body> <ul class="container"> <li class="item flex-start"> <p>1</p> </li> <li class="item flex-end"> <p>2</p> </li> <li class="item center"> <p>3</p> </li> <li class="item stretch"> <p>4</p> </li> <li class="item baseline"> <p>5</p> </li> </ul></body> </html> CSS Code: CSS .container { background-color: rgb(245 197 221); padding: 0; margin: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 100px; margin: 5px; line-height: 100px; font-weight: bold; border: 2px solid black;}.flex-start { align-self: flex-start;}.flex-end { align-self: flex-end;}.center { align-self: center;}.stretch { align-self: stretch;}.baseline { align-self: baseline;} Output: flex-start, flex-end, center, stretch, baseline Supported Browsers: Google Chrome 29.0 Firefox 22.0 Microsoft Edge 12.0 Internet Explorer 11+ Opera 48.0 Safari 10.0 CSS-Properties CSS-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2021" }, { "code": null, "e": 222, "s": 28, "text": "CSS Flexible Layout Box, popularly known as Flexbox is a powerful one-dimensional layout model. It helps to lay, align and distribute items (children) efficiently inside a container (parent). " }, { "code": null, "e": 242, "s": 222, "text": "Important Features:" }, { "code": null, "e": 471, "s": 242, "text": "One-dimensional layout model: Flex is a one-dimensional layout model as it can only deal with items either horizontally as rows or vertically as columns. On the contrary, the CSS Grid layout can handle rows and columns together." }, { "code": null, "e": 749, "s": 471, "text": "Creates flexible and responsive layouts: Flexbox gives flex container the ability to customize the items within it, depending on different screen sizes. A flex container can expand its children’s items to fill the available space or it can also shrink them to prevent overflow." }, { "code": null, "e": 885, "s": 749, "text": "Direction-agnostic: Flexbox is free from any directional constraints unlike Block (vertically biased) and Inline (horizontally biased)." }, { "code": null, "e": 1040, "s": 885, "text": "Super easy to use: It is easy to align items in Flexbox, unlike using float and positioning which are a little frustrating and sometimes difficult to use." }, { "code": null, "e": 1062, "s": 1040, "text": "Flexbox Architecture:" }, { "code": null, "e": 1127, "s": 1062, "text": "There are two aspects of a Flexbox: Flex container and Flex item" }, { "code": null, "e": 1328, "s": 1127, "text": "The flex items can be laid out either along the main axis (starting from the main start and ending at the main end) or along the cross axis (starting from the cross start and ending at the cross end)." }, { "code": null, "e": 1445, "s": 1328, "text": "Main axis: Flex items are laid out along this axis, either horizontally or vertically based upon the flex-direction." }, { "code": null, "e": 1555, "s": 1445, "text": "Cross axis: It is perpendicular to the main axis and its direction depends on the direction of the main axis." }, { "code": null, "e": 1639, "s": 1555, "text": "Main size: It is the width/height of the flex item depending on the main dimension." }, { "code": null, "e": 1725, "s": 1639, "text": "Cross size: It is the width/height of the flex item depending on the cross dimension." }, { "code": null, "e": 1845, "s": 1725, "text": "To understand the different Flexbox properties, let us take an example by creating an HTML file, along with a CSS file." }, { "code": null, "e": 1854, "s": 1845, "text": "Example:" }, { "code": null, "e": 1859, "s": 1854, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>CSS Flexbox</title> <link rel=\"stylesheet\" href=\"style.css\" /> </head> <body> <div class=\"container\"> <div class=\"item item-1\">1</div> <div class=\"item item-2\">2</div> <div class=\"item item-3\">3</div> <div class=\"item item-4\">4</div> </div></body> </html>", "e": 2386, "s": 1859, "text": null }, { "code": null, "e": 2469, "s": 2386, "text": "This is our CSS code in which we will be styling the flex-container and flex-item." }, { "code": null, "e": 2473, "s": 2469, "text": "CSS" }, { "code": ".container { border: 5px solid rgb(0, 0, 0); background-color: rgb(245 197 221);}.item { border: 5px solid rgb(0, 0, 0); background-color: rgb(141, 178, 226); margin: 10px; padding: 20px; height: 100px; width: 100px; font-weight: bold; font-size: 45px;}", "e": 2737, "s": 2473, "text": null }, { "code": null, "e": 2747, "s": 2739, "text": "Output:" }, { "code": null, "e": 2931, "s": 2747, "text": "From the above output, the items are aligned vertically, by default, and the default display is block-level. The pink area is the container and the blue boxes within it are the items." }, { "code": null, "e": 2973, "s": 2931, "text": "Properties for the Parent/Flex Container:" }, { "code": null, "e": 3082, "s": 2973, "text": "display: Let’s make the container flex by setting its display to flex inside the .container of our CSS file." }, { "code": null, "e": 3191, "s": 3082, "text": ".container{\n display: flex;\n border: 5px solid rgb(0, 0, 0);\n background-color: rgb(245 197 221);\n}" }, { "code": null, "e": 3200, "s": 3191, "text": "Example:" }, { "code": null, "e": 3205, "s": 3200, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>CSS Flexbox</title> <style> .container { display: flex; border: 5px solid rgb(0, 0, 0); background-color: rgb(245 197 221); } .item { border: 5px solid rgb(0, 0, 0); background-color: rgb(141, 178, 226); margin: 10px; padding: 20px; height: 100px; width: 100px; font-weight: bold; font-size: 45px; } </style></head> <body> <div class=\"container\"> <div class=\"item item-1\">1</div> <div class=\"item item-2\">2</div> <div class=\"item item-3\">3</div> <div class=\"item item-4\">4</div> </div></body> </html>", "e": 4075, "s": 3205, "text": null }, { "code": null, "e": 4232, "s": 4075, "text": "Output: As you can see, after applying the display: flex property, the items have been aligned horizontally as the default flex-direction of flexbox is row." }, { "code": null, "e": 4246, "s": 4232, "text": "display: flex" }, { "code": null, "e": 4379, "s": 4246, "text": "flex-direction: It sets the direction of the flex container’s main axis and specifies how items will be placed inside the container." }, { "code": null, "e": 4388, "s": 4379, "text": "Syntax: " }, { "code": null, "e": 4420, "s": 4388, "text": "flex-direction: attribute value" }, { "code": null, "e": 4438, "s": 4420, "text": "Attribute Values:" }, { "code": null, "e": 4494, "s": 4438, "text": "row: Flex items are displayed horizontally along a row." }, { "code": null, "e": 4555, "s": 4494, "text": "column: Flex items are displayed vertically along a column." }, { "code": null, "e": 4640, "s": 4555, "text": "row reverse: Flex items are displayed horizontally along a row but in reverse order." }, { "code": null, "e": 4729, "s": 4640, "text": "column reverse: Flex items are displayed vertically along a column but in reverse order." }, { "code": null, "e": 4778, "s": 4729, "text": "Note: The display direction, by default, is row." }, { "code": null, "e": 4789, "s": 4780, "text": "Example:" }, { "code": null, "e": 4794, "s": 4789, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex-direction</title> <link rel=\"stylesheet\" href=\"style_flex-direction.css\" /> </head> <body> <ul class=\"container row\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> </ul> <ul class=\"container column\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> </ul> <ul class=\"container row-reverse\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> </ul> <ul class=\"container column-reverse\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> </ul></body> </html>", "e": 6250, "s": 4794, "text": null }, { "code": null, "e": 6260, "s": 6250, "text": "CSS Code:" }, { "code": null, "e": 6264, "s": 6260, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 5px; padding: 0; float: left; height: 270px; width: 170px; border: 2px solid black; display: flex;}.row { flex-direction: row;}.column { flex-direction: column;}.row-reverse { flex-direction: row-reverse;}.column-reverse { flex-direction: column-reverse;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; height: 40px; width: 40px; margin: 2px; padding: 2px; font-weight: bold; border: 2px solid black;}", "e": 6779, "s": 6264, "text": null }, { "code": null, "e": 6787, "s": 6779, "text": "Output:" }, { "code": null, "e": 6828, "s": 6787, "text": "row, column, row-reverse, column-reverse" }, { "code": null, "e": 6927, "s": 6828, "text": "flex-wrap: It specifies whether the flex container will have a single line or have multiple lines." }, { "code": null, "e": 6935, "s": 6927, "text": "Syntax:" }, { "code": null, "e": 6962, "s": 6935, "text": "flex-wrap: attribute value" }, { "code": null, "e": 6980, "s": 6962, "text": "Attribute values:" }, { "code": null, "e": 7129, "s": 6980, "text": "nowrap (default): It specifies that the flex items will not wrap and will be laid out in a single line. It may cause the flex container to overflow." }, { "code": null, "e": 7232, "s": 7129, "text": "wrap: It specifies that the flex items will wrap if necessary, and will be laid out in multiple lines." }, { "code": null, "e": 7332, "s": 7232, "text": "wrap-reverse: It is the same as a wrap, but the flex items will wrap in reverse order in this case." }, { "code": null, "e": 7408, "s": 7332, "text": "initial: It represents the value specified as the property’s initial value." }, { "code": null, "e": 7491, "s": 7408, "text": "inherit: It represents the computed value of the property on the element’s parent." }, { "code": null, "e": 7599, "s": 7491, "text": "Note: We have increased the number of items inside the container to understand the flex-wrap effect better." }, { "code": null, "e": 7610, "s": 7601, "text": "Example:" }, { "code": null, "e": 7615, "s": 7610, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex-wrap</title> <link rel=\"stylesheet\" href=\"style_flex-wrap.css\" /> </head> <body> <ul class=\"container no-wrap\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> <li class=\"item\"> <p>6</p> </li> <li class=\"item\"> <p>7</p> </li> <li class=\"item\"> <p>8</p> </li> </ul> <ul class=\"container wrap\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> <li class=\"item\"> <p>6</p> </li> <li class=\"item\"> <p>7</p> </li> <li class=\"item\"> <p>8</p> </li> </ul> <ul class=\"container wrap-reverse\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> <li class=\"item\"> <p>6</p> </li> <li class=\"item\"> <p>7</p> </li> <li class=\"item\"> <p>8</p> </li> </ul></body> </html>", "e": 9476, "s": 7615, "text": null }, { "code": null, "e": 9486, "s": 9476, "text": "CSS Code:" }, { "code": null, "e": 9490, "s": 9486, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 5px; padding: 0; float: left; width: 250px; border: 2px solid black; display: flex;}.no-wrap { flex-wrap: nowrap;}.wrap { flex-wrap: wrap;}.wrap-reverse { flex-wrap: wrap-reverse;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; height: 40px; width: 40px; margin: 2px; padding: 2px; font-weight: bold; border: 2px solid black;}", "e": 9928, "s": 9490, "text": null }, { "code": null, "e": 9936, "s": 9928, "text": "Output:" }, { "code": null, "e": 9963, "s": 9936, "text": "nowrap, wrap, wrap-reverse" }, { "code": null, "e": 10086, "s": 9963, "text": "flex-flow: It is a shorthand for flex-direction and flex-wrap. By default, flex-direction is row, and flex-wrap is nowrap." }, { "code": null, "e": 10095, "s": 10086, "text": "Syntax: " }, { "code": null, "e": 10131, "s": 10095, "text": "flex-flow: flex-direction flex-wrap" }, { "code": null, "e": 10208, "s": 10131, "text": "For example, we can specify flex-direction as a row and flex-wrap as a wrap." }, { "code": null, "e": 10243, "s": 10208, "text": ".container{\nflex-flow: row wrap;\n}" }, { "code": null, "e": 10252, "s": 10243, "text": "row wrap" }, { "code": null, "e": 10354, "s": 10252, "text": "justify-content: It defines how items are positioned along the main/primary axis of the current line." }, { "code": null, "e": 10362, "s": 10354, "text": "Syntax:" }, { "code": null, "e": 10395, "s": 10362, "text": "justify-content: attribute value" }, { "code": null, "e": 10413, "s": 10395, "text": "Attribute values:" }, { "code": null, "e": 10496, "s": 10413, "text": "flex-start (default): Flex items are positioned at the beginning of the container." }, { "code": null, "e": 10561, "s": 10496, "text": "flex-end: Flex items are positioned at the end of the container." }, { "code": null, "e": 10627, "s": 10561, "text": "center: Flex items are positioned in the center of the container." }, { "code": null, "e": 10779, "s": 10627, "text": "space-between: Flex items are distributed with even spacing, the first item will be at the start and the last item will be at the end of the container." }, { "code": null, "e": 10934, "s": 10779, "text": "space-around: Flex items are distributed with even spacing, with half the amount of space at the start of the first item and at the end of the last item." }, { "code": null, "e": 11034, "s": 10934, "text": "space-evenly: Flex items are evenly distributed within the alignment container along the main axis." }, { "code": null, "e": 11110, "s": 11034, "text": "initial: It represents the value specified as the property’s initial value." }, { "code": null, "e": 11119, "s": 11110, "text": "Example:" }, { "code": null, "e": 11124, "s": 11119, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>justify-content</title> <link rel=\"stylesheet\" href=\"style_justify-content.css\" /> </head> <body> <ul class=\"container flexStart\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container flexEnd\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container center\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container spaceBetween\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container spaceAround\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container spaceEvenly\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul></body> </html>", "e": 13490, "s": 11124, "text": null }, { "code": null, "e": 13500, "s": 13490, "text": "CSS Code:" }, { "code": null, "e": 13504, "s": 13500, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 5px; padding: 0; border: 2px solid black; display: flex;}.flexStart { justify-content: flex-start;}.flexEnd { justify-content: flex-end;}.center { justify-content: center;}.spaceBetween { justify-content: space-between;}.spaceAround { justify-content: space-around;}.spaceEvenly { justify-content: space-evenly;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); width: 50px; height: 50px; margin: 5px; line-height: 10px; font-weight: bold; border: 2px solid black;}", "e": 14065, "s": 13504, "text": null }, { "code": null, "e": 14073, "s": 14065, "text": "Output:" }, { "code": null, "e": 14145, "s": 14073, "text": "flex-start, flex-end, center, space between, space-around, space-evenly" }, { "code": null, "e": 14348, "s": 14145, "text": "align-content: When there is extra space in the cross-axis, align-content aligns multiple lines within the container. It is similar to justify-content which aligns individual items within the main axis." }, { "code": null, "e": 14416, "s": 14348, "text": "Note: This property only works when the Flexbox has multiple lines." }, { "code": null, "e": 14425, "s": 14416, "text": "Syntax: " }, { "code": null, "e": 14456, "s": 14425, "text": "align-content: attribute value" }, { "code": null, "e": 14474, "s": 14456, "text": "Attribute values:" }, { "code": null, "e": 14545, "s": 14474, "text": "flex-start: Lines are aligned towards the beginning of the container." }, { "code": null, "e": 14608, "s": 14545, "text": "flex-end: Lines are aligned towards the end of the container." }, { "code": null, "e": 14671, "s": 14608, "text": "center: Lines are aligned towards the center of the container." }, { "code": null, "e": 14807, "s": 14671, "text": "space-between: Lines are evenly distributed, the first item will be at the start and the last item will be at the end of the container." }, { "code": null, "e": 14945, "s": 14807, "text": "space-around: Lines are evenly distributed, with half the amount of space at the start of the first item and at the end of the last item." }, { "code": null, "e": 15010, "s": 14945, "text": "stretch(default): Line stretches to take up the remaining space." }, { "code": null, "e": 15019, "s": 15010, "text": "Example:" }, { "code": null, "e": 15024, "s": 15019, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>align-content</title> <link rel=\"stylesheet\" href=\"style_align-content.css\" /></head> <body> <ul class=\"container flexStart\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container flexEnd\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container center\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container spaceBetween\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container spaceAround\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container stretch\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul></body> </html>", "e": 17385, "s": 15024, "text": null }, { "code": null, "e": 17395, "s": 17385, "text": "CSS Code:" }, { "code": null, "e": 17399, "s": 17395, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 5px; float: left; height: 500px; width: 50px; border: 2px solid black; display: flex; flex-wrap: wrap; flex-direction: row;}.flexStart { align-content: flex-start;}.flexEnd { align-content: flex-end;}.center { align-content: center;}.spaceBetween { align-content: space-between;}.spaceAround { align-content: space-around;}.stretch { align-content: stretch;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 50px; margin: 5px; line-height: 10px; font-weight: bold; border: 2px solid black;}", "e": 18010, "s": 17399, "text": null }, { "code": null, "e": 18018, "s": 18010, "text": "Output:" }, { "code": null, "e": 18085, "s": 18018, "text": "flex-start, flex-end, center, space-between, space-around, stretch" }, { "code": null, "e": 18199, "s": 18085, "text": "align-items: It defines how flex items will be aligned along the cross axis of the current line of the container." }, { "code": null, "e": 18208, "s": 18199, "text": "Syntax: " }, { "code": null, "e": 18283, "s": 18208, "text": "align-items: stretch|center|flex-start|flex-end|baseline|initial|\ninherit;" }, { "code": null, "e": 18301, "s": 18283, "text": "Attribute Values:" }, { "code": null, "e": 18359, "s": 18301, "text": "flex-start: Items are aligned along the cross-start line." }, { "code": null, "e": 18413, "s": 18359, "text": "flex-end: Items are aligned along the cross-end line." }, { "code": null, "e": 18463, "s": 18413, "text": "center: The items are centered in the cross-axis." }, { "code": null, "e": 18550, "s": 18463, "text": "baseline: The items are aligned in a line in such a matter that their baselines align." }, { "code": null, "e": 18609, "s": 18550, "text": "stretch(default): The items stretch to fill the container." }, { "code": null, "e": 18618, "s": 18609, "text": "Example:" }, { "code": null, "e": 18623, "s": 18618, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>align-item</title> <link rel=\"stylesheet\" href=\"style_align-item.css\" /> </head> <body> <ul class=\"container flexStart\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container flexEnd\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container center\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container baseline\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul> <ul class=\"container stretch\"> <li class=\"item\"> <p>1</p> </li> <li class=\"item\"> <p>2</p> </li> <li class=\"item\"> <p>3</p> </li> <li class=\"item\"> <p>4</p> </li> <li class=\"item\"> <p>5</p> </li> </ul></body> </html>", "e": 20629, "s": 18623, "text": null }, { "code": null, "e": 20639, "s": 20629, "text": "CSS Code:" }, { "code": null, "e": 20643, "s": 20639, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 5px; float: left; height: 300px; width: 150px; border: 2px solid black; display: flex; flex-direction: row;}.flexStart { align-items: flex-start;}.flexEnd { align-items: flex-end;}.center { align-items: center;}.baseline { align-items: baseline;}.stretch { align-items: stretch;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 50px; line-height: 10px; font-weight: bold; border: 2px solid black;}", "e": 21159, "s": 20643, "text": null }, { "code": null, "e": 21167, "s": 21159, "text": "Output:" }, { "code": null, "e": 21215, "s": 21167, "text": "flex-start ,flex-end, center, baseline, stretch" }, { "code": null, "e": 21322, "s": 21215, "text": "Please refer to the Difference between align-content and align-items article for the detailed differences." }, { "code": null, "e": 21358, "s": 21322, "text": "Properties for the Child/Flex Item:" }, { "code": null, "e": 21458, "s": 21358, "text": "order: It assigns the order in which children of a flex container appear within the flex container." }, { "code": null, "e": 21467, "s": 21458, "text": "Syntax: " }, { "code": null, "e": 21484, "s": 21467, "text": "order: <integer>" }, { "code": null, "e": 21775, "s": 21484, "text": "Flex items have a default order value of 0. That is why items assigned with values greater than 0 appear after items for which no value has been set. The reverse applies for items with values lesser than 0, they appear before the items having default order value or order value more than 0." }, { "code": null, "e": 21784, "s": 21775, "text": "Example:" }, { "code": null, "e": 21789, "s": 21784, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>order</title> <link rel=\"stylesheet\" href=\"style_order.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item item-1\"> <p>1</p> </li> <li class=\"item item-2\"> <p>2</p> </li> <li class=\"item item-3\"> <p>3</p> </li> <li class=\"item item-4\"> <p>4</p> </li> <li class=\"item item-5\"> <p>5</p> </li> </ul></body> </html>", "e": 22479, "s": 21789, "text": null }, { "code": null, "e": 22489, "s": 22479, "text": "CSS Code:" }, { "code": null, "e": 22493, "s": 22489, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 0; padding: 0; float: left; height: 200px; width: 400px; border: 2px solid black; display: flex; flex-wrap: wrap; flex-direction: row;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { order: 3;}.item-4 { order: -3;}", "e": 22914, "s": 22493, "text": null }, { "code": null, "e": 23111, "s": 22914, "text": "Output: As item 1 has order 3, its order is higher than every item’s order so it is placed at the end and item 4 is placed at the beginning as its order (-3) is the lowest order among other items." }, { "code": null, "e": 23202, "s": 23111, "text": "flex: It specifies the components of a flexible length and it is a shorthand property for:" }, { "code": null, "e": 23301, "s": 23202, "text": "flex-grow: It specifies how much the item will grow compared to other items inside that container." }, { "code": null, "e": 23404, "s": 23301, "text": "flex-shrink: It specifies how much the item will shrink compared to other items inside that container." }, { "code": null, "e": 23468, "s": 23404, "text": "flex-basis: It specifies the initial size of the flexible item." }, { "code": null, "e": 23476, "s": 23468, "text": "Syntax:" }, { "code": null, "e": 23538, "s": 23476, "text": " flex: flex-grow flex-shrink flex-basis|auto|initial|inherit;" }, { "code": null, "e": 23547, "s": 23538, "text": "Example:" }, { "code": null, "e": 23552, "s": 23547, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex</title> <link rel=\"stylesheet\" href=\"style_flex.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item item-1\"> <p>1</p> </li> <li class=\"item item-2\"> <p>2</p> </li> <li class=\"item item-3\"> <p>3</p> </li> <li class=\"item item-4\"> <p>4</p> </li> <li class=\"item item-5\"> <p>5</p> </li> </ul></body> </html>", "e": 24231, "s": 23552, "text": null }, { "code": null, "e": 24241, "s": 24231, "text": "CSS Code:" }, { "code": null, "e": 24245, "s": 24241, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 500px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex: 0 1 auto;}.item-2 { flex: 2 2 auto;}.item-3 { flex: 0 1 auto;}.item-4 { flex: 0 1 auto;}.item-5 { flex: 0 1 auto;}", "e": 24689, "s": 24245, "text": null }, { "code": null, "e": 24987, "s": 24689, "text": "Output: As we can clearly see, item 2 with the highest flex-grow and flex-shrink value expand and shrinks the most. It has flex-grow value and shrinks value both as 2, while other items have 0 and 1 flex-grow and flex-shrink values respectively. The flex-basis for all items have been set as auto." }, { "code": null, "e": 25107, "s": 24987, "text": "flex-grow: It sets the flex-grow property of a flex item and defines its ability to grow. Default flex-grow value is 0." }, { "code": null, "e": 25116, "s": 25107, "text": "Syntax: " }, { "code": null, "e": 25137, "s": 25116, "text": "flex-grow: <number> " }, { "code": null, "e": 25173, "s": 25137, "text": "Note: Negative numbers are invalid." }, { "code": null, "e": 25182, "s": 25173, "text": "Example:" }, { "code": null, "e": 25187, "s": 25182, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex-grow</title> <link rel=\"stylesheet\" href=\"style_flex-grow.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item item-1\"> <p>1</p> </li> <li class=\"item item-2\"> <p>2</p> </li> <li class=\"item item-3\"> <p>3</p> </li> <li class=\"item item-4\"> <p>4</p> </li> <li class=\"item item-5\"> <p>5</p> </li> </ul></body> </html>", "e": 25885, "s": 25187, "text": null }, { "code": null, "e": 25895, "s": 25885, "text": "CSS Code:" }, { "code": null, "e": 25899, "s": 25895, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex-grow: 0;}.item-2 { flex-grow: 2;}.item-3 { flex-grow: 0;}.item-4 { flex-grow: 0;}.item-5 { flex-grow: 0;}", "e": 26333, "s": 25899, "text": null }, { "code": null, "e": 26449, "s": 26333, "text": "Output: As we can clearly see, item 2 with flex-grow value more than others expands more than the other four items." }, { "code": null, "e": 26592, "s": 26449, "text": "flex-shrink: It sets the flex-shrink property for a flex item and defines the ability for a flex item to shrink. Default flex-grow value is 1." }, { "code": null, "e": 26601, "s": 26592, "text": "Syntax: " }, { "code": null, "e": 26624, "s": 26601, "text": "flex-shrink: <number> " }, { "code": null, "e": 26660, "s": 26624, "text": "Note: Negative numbers are invalid." }, { "code": null, "e": 26669, "s": 26660, "text": "Example:" }, { "code": null, "e": 26674, "s": 26669, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex-shrink</title> <link rel=\"stylesheet\" href=\"style_flex-shrink.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item item-1\"> <p>1</p> </li> <li class=\"item item-2\"> <p>2</p> </li> <li class=\"item item-3\"> <p>3</p> </li> <li class=\"item item-4\"> <p>4</p> </li> <li class=\"item item-5\"> <p>5</p> </li> </ul></body> </html>", "e": 27367, "s": 26674, "text": null }, { "code": null, "e": 27377, "s": 27367, "text": "CSS Code:" }, { "code": null, "e": 27381, "s": 27377, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); margin: 0; padding: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.item-1 { flex-shrink: 1;}.item-2 { flex-shrink: 2;}.item-3 { flex-shrink: 1;}.item-4 { flex-shrink: 1;}.item-5 { flex-shrink: 1;}", "e": 27825, "s": 27381, "text": null }, { "code": null, "e": 27943, "s": 27825, "text": "Output: As we can clearly see, item 2 with flex-shrink value more than others shrinks more than the other four items." }, { "code": null, "e": 27999, "s": 27943, "text": "flex-basis: It defines the initial size of a flex item." }, { "code": null, "e": 28007, "s": 27999, "text": "Syntax:" }, { "code": null, "e": 28039, "s": 28007, "text": "flex-basis: content | <'width'>" }, { "code": null, "e": 28048, "s": 28039, "text": "Example:" }, { "code": null, "e": 28053, "s": 28048, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>flex-basis</title> <link rel=\"stylesheet\" href=\"style_flex-basis.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item px\"> <p>px</p> </li> <li class=\"item percentage\"> <p>percentage</p> </li> <li class=\"item auto\"> <p>auto</p> </li> <li class=\"item initial\"> <p>initial</p> </li> <li class=\"item inherit\"> <p>inherit</p> </li> </ul></body> </html>", "e": 28769, "s": 28053, "text": null }, { "code": null, "e": 28779, "s": 28769, "text": "CSS Code:" }, { "code": null, "e": 28783, "s": 28779, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); padding: 0; margin: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; margin: 5px; width: 50px; height: 50px; font-weight: bold; border: 2px solid black;}.px { flex-basis: 50px;}.percentage { flex-basis: 75%;}.auto { flex-basis: auto;}.initial { flex-basis: initial;}.inherit { flex-basis: inherit;}", "e": 29244, "s": 28783, "text": null }, { "code": null, "e": 29252, "s": 29244, "text": "Output:" }, { "code": null, "e": 29335, "s": 29252, "text": "align-self: It defines how individual flex items are aligned along the cross-axis." }, { "code": null, "e": 29344, "s": 29335, "text": "Syntax: " }, { "code": null, "e": 29423, "s": 29344, "text": "align-self: auto|stretch|center|flex-start|flex-end|baseline|\ninitial|inherit;" }, { "code": null, "e": 29440, "s": 29423, "text": "Attribute Value:" }, { "code": null, "e": 29500, "s": 29440, "text": "flex-start: Aligns items at the beginning of the container." }, { "code": null, "e": 29553, "s": 29500, "text": "flex-end: Aligns items at the end of the container." }, { "code": null, "e": 29607, "s": 29553, "text": "center: Aligns items at the center of the container." }, { "code": null, "e": 29652, "s": 29607, "text": "stretch: Aligns items to fit the container." }, { "code": null, "e": 29710, "s": 29652, "text": "baseline: Aligns items to the baseline of the container." }, { "code": null, "e": 29786, "s": 29710, "text": "auto (default): Item inherits the align-items property of parent container." }, { "code": null, "e": 29822, "s": 29786, "text": "initial: Sets to the default value." }, { "code": null, "e": 29890, "s": 29822, "text": "inherit: Item inherits align-self property from its parent element." }, { "code": null, "e": 29899, "s": 29890, "text": "Example:" }, { "code": null, "e": 29904, "s": 29899, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>align-self</title> <link rel=\"stylesheet\" href=\"style_align-self.css\" /> </head> <body> <ul class=\"container\"> <li class=\"item flex-start\"> <p>1</p> </li> <li class=\"item flex-end\"> <p>2</p> </li> <li class=\"item center\"> <p>3</p> </li> <li class=\"item stretch\"> <p>4</p> </li> <li class=\"item baseline\"> <p>5</p> </li> </ul></body> </html>", "e": 30604, "s": 29904, "text": null }, { "code": null, "e": 30614, "s": 30604, "text": "CSS Code:" }, { "code": null, "e": 30618, "s": 30614, "text": "CSS" }, { "code": ".container { background-color: rgb(245 197 221); padding: 0; margin: 0; height: 250px; border: 2px solid black; display: flex;}ul { list-style: none;}.item { background-color: rgb(141, 178, 226); padding: 5px; width: 100px; margin: 5px; line-height: 100px; font-weight: bold; border: 2px solid black;}.flex-start { align-self: flex-start;}.flex-end { align-self: flex-end;}.center { align-self: center;}.stretch { align-self: stretch;}.baseline { align-self: baseline;}", "e": 31107, "s": 30618, "text": null }, { "code": null, "e": 31115, "s": 31107, "text": "Output:" }, { "code": null, "e": 31163, "s": 31115, "text": "flex-start, flex-end, center, stretch, baseline" }, { "code": null, "e": 31183, "s": 31163, "text": "Supported Browsers:" }, { "code": null, "e": 31202, "s": 31183, "text": "Google Chrome 29.0" }, { "code": null, "e": 31215, "s": 31202, "text": "Firefox 22.0" }, { "code": null, "e": 31235, "s": 31215, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 31257, "s": 31235, "text": "Internet Explorer 11+" }, { "code": null, "e": 31268, "s": 31257, "text": "Opera 48.0" }, { "code": null, "e": 31280, "s": 31268, "text": "Safari 10.0" }, { "code": null, "e": 31295, "s": 31280, "text": "CSS-Properties" }, { "code": null, "e": 31309, "s": 31295, "text": "CSS-Questions" }, { "code": null, "e": 31316, "s": 31309, "text": "Picked" }, { "code": null, "e": 31320, "s": 31316, "text": "CSS" }, { "code": null, "e": 31325, "s": 31320, "text": "HTML" }, { "code": null, "e": 31342, "s": 31325, "text": "Web Technologies" }, { "code": null, "e": 31347, "s": 31342, "text": "HTML" } ]
How does the functools cmp_to_key function works in Python?
12 Nov, 2020 There has been a change in Python’s sorted() function, it now takes three values namely, the iterable, key, and reverse. Out of these last two are optional but this article emphasizes the key part of the sorted() function. What key does is, it helps in the comparison of iterable elements while sorting. Python already had cmp() function that used to compare two values and return 1, -1, or 0. But as of Python 3.0 and above, this function has been deprecated and a new function cmp_to_key() has been introduced. The following article discusses the application and explanation of this function. cmp_to_key() uses a key to compare elements It is built into functools module, thus functools has to be imported first in order to use the function Used with tools that accept key functions such as min(), max(), sorted() etc. Takes only one argument which strictly should be a callable This function returns a special key that can be used to compare elements Syntax: functools.cmp_to_key(callable) Each element is compared with every other element of the list until a sorted list is obtained Every element apparently calls mycmp() function with the other element of the list mycmp() function returns a key after comparing the numbers This key is eventually helping sorted() to arrange elements in ascending order Below is the Implementation. Example 1: Program that sorts a list using a key provided by cmp_to_key() function Python3 import functools def mycmp(a, b): print("comparing ", a, " and ", b) if a > b: return 1 elif a < b: return -1 else: return 0 print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp))) Output: comparing 2 and 1 comparing 4 and 2 comparing 2 and 4 comparing 2 and 2 comparing 2 and 4 [1, 2, 2, 4] Example 2: Program that prints maximum and minimum numbers from a list using key provided by cmp_to_key() function Python3 import functools def mycmp(a, b): print("comparing ", a, " and ", b) if a > b: return 1 elif a < b: return -1 else: return 0 print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))print(max([45, 78, 813], key=functools.cmp_to_key(mycmp))) Output: comparing 78 and 45 comparing 813 and 45 45 comparing 78 and 45 comparing 813 and 78 813 Python functools-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Deque in Python Defaultdict in Python Queue in Python Rotate axis tick labels in Seaborn and Matplotlib Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib Python OOPs Concepts How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Nov, 2020" }, { "code": null, "e": 650, "s": 54, "text": "There has been a change in Python’s sorted() function, it now takes three values namely, the iterable, key, and reverse. Out of these last two are optional but this article emphasizes the key part of the sorted() function. What key does is, it helps in the comparison of iterable elements while sorting. Python already had cmp() function that used to compare two values and return 1, -1, or 0. But as of Python 3.0 and above, this function has been deprecated and a new function cmp_to_key() has been introduced. The following article discusses the application and explanation of this function." }, { "code": null, "e": 694, "s": 650, "text": "cmp_to_key() uses a key to compare elements" }, { "code": null, "e": 798, "s": 694, "text": "It is built into functools module, thus functools has to be imported first in order to use the function" }, { "code": null, "e": 876, "s": 798, "text": "Used with tools that accept key functions such as min(), max(), sorted() etc." }, { "code": null, "e": 936, "s": 876, "text": "Takes only one argument which strictly should be a callable" }, { "code": null, "e": 1009, "s": 936, "text": "This function returns a special key that can be used to compare elements" }, { "code": null, "e": 1017, "s": 1009, "text": "Syntax:" }, { "code": null, "e": 1048, "s": 1017, "text": "functools.cmp_to_key(callable)" }, { "code": null, "e": 1142, "s": 1048, "text": "Each element is compared with every other element of the list until a sorted list is obtained" }, { "code": null, "e": 1225, "s": 1142, "text": "Every element apparently calls mycmp() function with the other element of the list" }, { "code": null, "e": 1284, "s": 1225, "text": "mycmp() function returns a key after comparing the numbers" }, { "code": null, "e": 1363, "s": 1284, "text": "This key is eventually helping sorted() to arrange elements in ascending order" }, { "code": null, "e": 1392, "s": 1363, "text": "Below is the Implementation." }, { "code": null, "e": 1475, "s": 1392, "text": "Example 1: Program that sorts a list using a key provided by cmp_to_key() function" }, { "code": null, "e": 1483, "s": 1475, "text": "Python3" }, { "code": "import functools def mycmp(a, b): print(\"comparing \", a, \" and \", b) if a > b: return 1 elif a < b: return -1 else: return 0 print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp)))", "e": 1708, "s": 1483, "text": null }, { "code": null, "e": 1716, "s": 1708, "text": "Output:" }, { "code": null, "e": 1835, "s": 1716, "text": "comparing 2 and 1\ncomparing 4 and 2\ncomparing 2 and 4\ncomparing 2 and 2\ncomparing 2 and 4\n[1, 2, 2, 4]\n" }, { "code": null, "e": 1950, "s": 1835, "text": "Example 2: Program that prints maximum and minimum numbers from a list using key provided by cmp_to_key() function" }, { "code": null, "e": 1958, "s": 1950, "text": "Python3" }, { "code": "import functools def mycmp(a, b): print(\"comparing \", a, \" and \", b) if a > b: return 1 elif a < b: return -1 else: return 0 print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))", "e": 2239, "s": 1958, "text": null }, { "code": null, "e": 2247, "s": 2239, "text": "Output:" }, { "code": null, "e": 2349, "s": 2247, "text": "comparing 78 and 45\ncomparing 813 and 45\n45\ncomparing 78 and 45\ncomparing 813 and 78\n813\n" }, { "code": null, "e": 2373, "s": 2349, "text": "Python functools-module" }, { "code": null, "e": 2380, "s": 2373, "text": "Python" }, { "code": null, "e": 2478, "s": 2380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2523, "s": 2478, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2539, "s": 2523, "text": "Deque in Python" }, { "code": null, "e": 2561, "s": 2539, "text": "Defaultdict in Python" }, { "code": null, "e": 2577, "s": 2561, "text": "Queue in Python" }, { "code": null, "e": 2627, "s": 2577, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2669, "s": 2627, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2696, "s": 2669, "text": "Python Classes and Objects" }, { "code": null, "e": 2719, "s": 2696, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 2740, "s": 2719, "text": "Python OOPs Concepts" } ]
Stream findFirst() in Java with examples
06 Dec, 2018 Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. Syntax : Optional<T> findFirst() Where, Optional is a container object which may or may not contain a non-null value and T is the type of objects and the function returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. Exception : If the element selected is null, NullPointerException is thrown. Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns first element satisfying the intermediate operations. Example 1 : findFirst() function on Stream of Integers. // Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Integers List<Integer> list = Arrays.asList(3, 5, 7, 9, 11); // Using Stream findFirst() Optional<Integer> answer = list.stream().findFirst(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println("no value"); } }} Output : 3 Example 2 : findFirst() function on Stream of Strings. // Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList("GeeksforGeeks", "for", "GeeksQuiz", "GFG"); // Using Stream findFirst() Optional<String> answer = list.stream().findFirst(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println("no value"); } }} Output : GeeksforGeeks Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 296, "s": 28, "text": "Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned." }, { "code": null, "e": 305, "s": 296, "text": "Syntax :" }, { "code": null, "e": 573, "s": 305, "text": "Optional<T> findFirst()\n\nWhere, Optional is a container object which\nmay or may not contain a non-null value \nand T is the type of objects and the function\nreturns an Optional describing the first element \nof this stream, or an empty Optional if the stream is empty.\n" }, { "code": null, "e": 650, "s": 573, "text": "Exception : If the element selected is null, NullPointerException is thrown." }, { "code": null, "e": 803, "s": 650, "text": "Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns first element satisfying the intermediate operations." }, { "code": null, "e": 859, "s": 803, "text": "Example 1 : findFirst() function on Stream of Integers." }, { "code": "// Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Integers List<Integer> list = Arrays.asList(3, 5, 7, 9, 11); // Using Stream findFirst() Optional<Integer> answer = list.stream().findFirst(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println(\"no value\"); } }}", "e": 1549, "s": 859, "text": null }, { "code": null, "e": 1558, "s": 1549, "text": "Output :" }, { "code": null, "e": 1561, "s": 1558, "text": "3\n" }, { "code": null, "e": 1616, "s": 1561, "text": "Example 2 : findFirst() function on Stream of Strings." }, { "code": "// Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList(\"GeeksforGeeks\", \"for\", \"GeeksQuiz\", \"GFG\"); // Using Stream findFirst() Optional<String> answer = list.stream().findFirst(); // if the stream is empty, an empty // Optional is returned. if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println(\"no value\"); } }}", "e": 2372, "s": 1616, "text": null }, { "code": null, "e": 2381, "s": 2372, "text": "Output :" }, { "code": null, "e": 2396, "s": 2381, "text": "GeeksforGeeks\n" }, { "code": null, "e": 2416, "s": 2396, "text": "Java - util package" }, { "code": null, "e": 2431, "s": 2416, "text": "Java-Functions" }, { "code": null, "e": 2443, "s": 2431, "text": "java-stream" }, { "code": null, "e": 2465, "s": 2443, "text": "Java-Stream interface" }, { "code": null, "e": 2470, "s": 2465, "text": "Java" }, { "code": null, "e": 2475, "s": 2470, "text": "Java" }, { "code": null, "e": 2573, "s": 2475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2624, "s": 2573, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2655, "s": 2624, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2674, "s": 2655, "text": "Interfaces in Java" }, { "code": null, "e": 2704, "s": 2674, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2722, "s": 2704, "text": "ArrayList in Java" }, { "code": null, "e": 2742, "s": 2722, "text": "Collections in Java" }, { "code": null, "e": 2774, "s": 2742, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2798, "s": 2774, "text": "Singleton Class in Java" }, { "code": null, "e": 2810, "s": 2798, "text": "Set in Java" } ]
Transform the string
30 Jun, 2022 Given a string s, change the string s according to the rules provided below: Delete all the vowels from the string. Insert # in front of all the consonants. Change the case of all the letters of the string. Examples: Input : aBAcAba Output :#b#C#B Input :SunshinE!! Output :#s#N#S#H#N!! Approach : First, create a new string by removing all the vowels from the given original string. Now, change the case of every alphabet in this string. Finally, add # in front of every alphabet in the string and this is required string. C++ Java Python3 C# PHP Javascript // CPP code to transform string#include <bits/stdc++.h>using namespace std; // Function to change// character's casestring change_case(string a){ int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is lowercase // change to uppercase if(a[i] >= 'a' && a[i] <= 'z') a[i] = a[i] - 32; // If character is uppercase // change to lowercase else if(a[i] >= 'A' && a[i] <= 'Z') a[i] = a[i] + 32; } return a; } // Function to delete vowelsstring delete_vowels(string a){ string temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { //If character is consonant if(a[i] != 'a' && a[i] != 'e' && a[i] != 'i' && a[i] != 'o' && a[i] != 'u' && a[i] != 'A' && a[i] != 'E' && a[i] != 'O' && a[i] != 'U'&& a[i] != 'I') temp += a[i]; } return temp; } // Function to insert "#"string insert_hash(string a){ string temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is not special if((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z')) temp = temp + '#' + a[i]; else temp = temp + a[i]; } return temp; } // Function to transform stringvoid transformSting(string a){ string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); //corner case // when all the words of string are vowel then string empty after deletion if(d=="") cout<<"-1"<<endl; else cout << d<<endl;} // Driver functionint main(){ string a = "SunshinE!!"; string b = "aeiou"; // Calling function transformSting(a); transformSting(b); return 0;} // Java code to transform stringimport java.io.*; class Gfg{ // Function to change // character's case public static String change_case(String a) { String temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { char ch=a.charAt(i); // If character is lowercase // change to uppercase if(ch >= 'a' &&ch <= 'z') ch = (char)(65 + (int)(ch - 'a')); // If character is uppercase // change to lowercase else if(ch >= 'A' &&ch <= 'Z') ch = (char)(97 + (int)(ch - 'A')); temp += ch; } return temp; } // Function to delete vowels public static String delete_vowels(String a) { String temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { char ch = a.charAt(i); // If character is consonant if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U'&&ch != 'I') temp += ch; } return temp; } // Function to insert "#" public static String insert_hash(String a) { String temp = ""; int l = a.length(); char hash = '#'; for(int i = 0 ; i < l ; i++) { char ch=a.charAt(i); // If character is not // special character if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) temp = temp + hash + ch; else temp = temp + ch; } return temp; } // Function to transform string public static void transformString(String a) { String b = delete_vowels(a); String c = change_case(b); String d = insert_hash(c); if(d=="") System.out.println("-1"); else System.out.println(d); } // Driver function public static void main (String args[]) { String a = "SunshinE!!"; String b = "aeiou"; // Calling function transformString(a); transformString(b); }} # Python code to# transform string # def to change# character's casedef change_case(s) : a = list(s) l = len(s) for i in range(0, l) : # If character is # lowercase change # to uppercase if(a[i] >= 'a' and a[i] <= 'z') : a[i] = s[i].upper() # If character is uppercase # change to lowercase elif(a[i] >= 'A' and a[i] <= 'Z') : a[i] = s[i].lower() return a # def to delete vowelsdef delete_vowels(s) : temp = "" a = list(s) l = len(s) for i in range(0, l) : # If character # is consonant if(a[i] != 'a' and a[i] != 'e' and a[i] != 'i' and a[i] != 'o' and a[i] != 'u' and a[i] != 'A' and a[i] != 'E' and a[i] != 'O' and a[i] != 'U' and a[i] != 'I') : temp = temp + a[i] return temp # def to insert "#"def insert_hash(s) : temp = "" a = list(s) l = len(s) for i in range(0, l) : # If character is # not special if((a[i] >= 'a' and a[i] <= 'z') or (a[i] >= 'A' and a[i] <= 'Z')) : temp = temp + '#' + a[i] else : temp = temp + a[i] return temp # def to# transform stringdef transformSting(a) : b = delete_vowels(a) c = change_case(b) d = insert_hash(c) print (d) # Driver Codea = "SunshinE!!" # Calling deftransformSting(a) # This code is contributed by# Manish Shaw(manishshaw1) // C# code to transform stringusing System; class Gfg{ // Function to change // character's case public static String change_case(string a) { string temp = ""; int l = a.Length; for(int i = 0 ; i < l ; i++) { char ch=a[i]; // If character is lowercase // change to uppercase if(ch >= 'a' &&ch <= 'z') ch = (char)(65 + (int)(ch - 'a')); // If character is uppercase // change to lowercase else if(ch >= 'A' &&ch <= 'Z') ch = (char)(97 + (int)(ch - 'A')); temp += ch; } return temp; } // Function to delete vowels public static String delete_vowels(String a) { String temp = ""; int l = a.Length; for(int i = 0 ; i < l ; i++) { char ch = a[i]; // If character is consonant if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U'&&ch != 'I') temp += ch; } return temp; } // Function to insert "#" public static String insert_hash(String a) { String temp = ""; int l = a.Length; char hash = '#'; for(int i = 0 ; i < l ; i++) { char ch=a[i]; // If character is not // special character if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) temp = temp + hash + ch; else temp = temp + ch; } return temp; } // Function to transform string public static void transformString(string a) { string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); Console.WriteLine(d); } // Driver function public static void Main () { string a = "SunshinE!!"; // Calling function transformString(a); }} // This code is contributed by vt_m. <?php// PHP code to transform string // Function to change// character's casefunction change_case($a){ $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character is lowercase // change to uppercase if($a[$i] >= 'a' && $a[$i] <= 'z') $a[$i] = chr(65 + (ord($a[$i]) - ord('a'))); // If character is uppercase // change to lowercase else if($a[$i] >= 'A' && $a[$i] <= 'Z') $a[$i] = chr(97 + (ord($a[$i]) - ord('a'))); } return $a;} // Function to delete vowelsfunction delete_vowels($a){ $temp = ""; $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character // is consonant if($a[$i] != 'a' && $a[$i] != 'e' && $a[$i] != 'i' && $a[$i] != 'o' && $a[$i] != 'u' && $a[$i] != 'A' && $a[$i] != 'E' && $a[$i] != 'O' && $a[$i] != 'U' && $a[$i] != 'I') $temp = $temp.$a[$i]; } return $temp; } // Function to insert "#"function insert_hash($a){ $temp = ""; $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character is // not special if(($a[$i] >= 'a' && $a[$i] <= 'z') || ($a[$i] >= 'A' && $a[$i] <= 'Z')) $temp = $temp . '#' . $a[$i]; else $temp = $temp.$a[$i]; } return $temp; } // Function to// transform stringfunction transformSting($a){ $b = delete_vowels($a); $c = change_case($b); $d = insert_hash($c); echo ($d);} // Driver Code$a = "SunshinE!!"; // Calling functiontransformSting($a); // This code is contributed by// Manish Shaw(manishshaw1)?> // Function to change// character's casefunction change_case(a){ var temp = ""; var l = a.length; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is lowercase // change to uppercase if (ch >= 'a' && ch <= 'z') { ch = String.fromCharCode((65 + parseInt((ch.charCodeAt(0) - 'a'.charCodeAt(0))))); } else if (ch >= 'A' && ch <= 'Z') { ch = String.fromCharCode((97 + parseInt((ch.charCodeAt(0) - 'A'.charCodeAt(0))))); } temp += ch; } return temp;}// Function to delete vowelsfunction delete_vowels(a){ var temp = ""; var l = a.length; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is consonant if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U' && ch != 'I') { temp += ch; } } return temp;}// Function to insert "#"function insert_hash(a){ var temp = ""; var l = a.length; var hash = '#'; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is not // special character if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { temp = temp + hash + ch; } else { temp = temp + ch; } } return temp;}// Function to transform stringfunction transformString(a){ var b = delete_vowels(a); var c = change_case(b); var d = insert_hash(c); if(d=="") console.log("-1"); else console.log(d);} // Driver functionvar a = "SunshinE!!";var b = "aeiou";// Calling functiontransformString(a);transformString(b); // This code is contributed by Aarti_Rathi #s#N#S#H#N!! -1 Time complexity: O(n), where n is the length of the string Auxiliary Space: O(n), where n is the length of the string manishshaw1 abhishek0719kadiyan surbhikumaridav geekygirl2001 rohitmishra051000 codewithrathi Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Convert string to char array in C++ Check whether two strings are anagram of each other
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 133, "s": 54, "text": "Given a string s, change the string s according to the rules provided below: " }, { "code": null, "e": 172, "s": 133, "text": "Delete all the vowels from the string." }, { "code": null, "e": 213, "s": 172, "text": "Insert # in front of all the consonants." }, { "code": null, "e": 263, "s": 213, "text": "Change the case of all the letters of the string." }, { "code": null, "e": 275, "s": 263, "text": "Examples: " }, { "code": null, "e": 346, "s": 275, "text": "Input : aBAcAba\nOutput :#b#C#B\n\nInput :SunshinE!!\nOutput :#s#N#S#H#N!!" }, { "code": null, "e": 586, "s": 348, "text": "Approach : First, create a new string by removing all the vowels from the given original string. Now, change the case of every alphabet in this string. Finally, add # in front of every alphabet in the string and this is required string. " }, { "code": null, "e": 590, "s": 586, "text": "C++" }, { "code": null, "e": 595, "s": 590, "text": "Java" }, { "code": null, "e": 603, "s": 595, "text": "Python3" }, { "code": null, "e": 606, "s": 603, "text": "C#" }, { "code": null, "e": 610, "s": 606, "text": "PHP" }, { "code": null, "e": 621, "s": 610, "text": "Javascript" }, { "code": "// CPP code to transform string#include <bits/stdc++.h>using namespace std; // Function to change// character's casestring change_case(string a){ int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is lowercase // change to uppercase if(a[i] >= 'a' && a[i] <= 'z') a[i] = a[i] - 32; // If character is uppercase // change to lowercase else if(a[i] >= 'A' && a[i] <= 'Z') a[i] = a[i] + 32; } return a; } // Function to delete vowelsstring delete_vowels(string a){ string temp = \"\"; int l = a.length(); for(int i = 0 ; i < l ; i++) { //If character is consonant if(a[i] != 'a' && a[i] != 'e' && a[i] != 'i' && a[i] != 'o' && a[i] != 'u' && a[i] != 'A' && a[i] != 'E' && a[i] != 'O' && a[i] != 'U'&& a[i] != 'I') temp += a[i]; } return temp; } // Function to insert \"#\"string insert_hash(string a){ string temp = \"\"; int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is not special if((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z')) temp = temp + '#' + a[i]; else temp = temp + a[i]; } return temp; } // Function to transform stringvoid transformSting(string a){ string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); //corner case // when all the words of string are vowel then string empty after deletion if(d==\"\") cout<<\"-1\"<<endl; else cout << d<<endl;} // Driver functionint main(){ string a = \"SunshinE!!\"; string b = \"aeiou\"; // Calling function transformSting(a); transformSting(b); return 0;}", "e": 2429, "s": 621, "text": null }, { "code": "// Java code to transform stringimport java.io.*; class Gfg{ // Function to change // character's case public static String change_case(String a) { String temp = \"\"; int l = a.length(); for(int i = 0 ; i < l ; i++) { char ch=a.charAt(i); // If character is lowercase // change to uppercase if(ch >= 'a' &&ch <= 'z') ch = (char)(65 + (int)(ch - 'a')); // If character is uppercase // change to lowercase else if(ch >= 'A' &&ch <= 'Z') ch = (char)(97 + (int)(ch - 'A')); temp += ch; } return temp; } // Function to delete vowels public static String delete_vowels(String a) { String temp = \"\"; int l = a.length(); for(int i = 0 ; i < l ; i++) { char ch = a.charAt(i); // If character is consonant if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U'&&ch != 'I') temp += ch; } return temp; } // Function to insert \"#\" public static String insert_hash(String a) { String temp = \"\"; int l = a.length(); char hash = '#'; for(int i = 0 ; i < l ; i++) { char ch=a.charAt(i); // If character is not // special character if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) temp = temp + hash + ch; else temp = temp + ch; } return temp; } // Function to transform string public static void transformString(String a) { String b = delete_vowels(a); String c = change_case(b); String d = insert_hash(c); if(d==\"\") System.out.println(\"-1\"); else System.out.println(d); } // Driver function public static void main (String args[]) { String a = \"SunshinE!!\"; String b = \"aeiou\"; // Calling function transformString(a); transformString(b); }}", "e": 4818, "s": 2429, "text": null }, { "code": "# Python code to# transform string # def to change# character's casedef change_case(s) : a = list(s) l = len(s) for i in range(0, l) : # If character is # lowercase change # to uppercase if(a[i] >= 'a' and a[i] <= 'z') : a[i] = s[i].upper() # If character is uppercase # change to lowercase elif(a[i] >= 'A' and a[i] <= 'Z') : a[i] = s[i].lower() return a # def to delete vowelsdef delete_vowels(s) : temp = \"\" a = list(s) l = len(s) for i in range(0, l) : # If character # is consonant if(a[i] != 'a' and a[i] != 'e' and a[i] != 'i' and a[i] != 'o' and a[i] != 'u' and a[i] != 'A' and a[i] != 'E' and a[i] != 'O' and a[i] != 'U' and a[i] != 'I') : temp = temp + a[i] return temp # def to insert \"#\"def insert_hash(s) : temp = \"\" a = list(s) l = len(s) for i in range(0, l) : # If character is # not special if((a[i] >= 'a' and a[i] <= 'z') or (a[i] >= 'A' and a[i] <= 'Z')) : temp = temp + '#' + a[i] else : temp = temp + a[i] return temp # def to# transform stringdef transformSting(a) : b = delete_vowels(a) c = change_case(b) d = insert_hash(c) print (d) # Driver Codea = \"SunshinE!!\" # Calling deftransformSting(a) # This code is contributed by# Manish Shaw(manishshaw1)", "e": 6346, "s": 4818, "text": null }, { "code": "// C# code to transform stringusing System; class Gfg{ // Function to change // character's case public static String change_case(string a) { string temp = \"\"; int l = a.Length; for(int i = 0 ; i < l ; i++) { char ch=a[i]; // If character is lowercase // change to uppercase if(ch >= 'a' &&ch <= 'z') ch = (char)(65 + (int)(ch - 'a')); // If character is uppercase // change to lowercase else if(ch >= 'A' &&ch <= 'Z') ch = (char)(97 + (int)(ch - 'A')); temp += ch; } return temp; } // Function to delete vowels public static String delete_vowels(String a) { String temp = \"\"; int l = a.Length; for(int i = 0 ; i < l ; i++) { char ch = a[i]; // If character is consonant if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U'&&ch != 'I') temp += ch; } return temp; } // Function to insert \"#\" public static String insert_hash(String a) { String temp = \"\"; int l = a.Length; char hash = '#'; for(int i = 0 ; i < l ; i++) { char ch=a[i]; // If character is not // special character if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) temp = temp + hash + ch; else temp = temp + ch; } return temp; } // Function to transform string public static void transformString(string a) { string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); Console.WriteLine(d); } // Driver function public static void Main () { string a = \"SunshinE!!\"; // Calling function transformString(a); }} // This code is contributed by vt_m.", "e": 8591, "s": 6346, "text": null }, { "code": "<?php// PHP code to transform string // Function to change// character's casefunction change_case($a){ $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character is lowercase // change to uppercase if($a[$i] >= 'a' && $a[$i] <= 'z') $a[$i] = chr(65 + (ord($a[$i]) - ord('a'))); // If character is uppercase // change to lowercase else if($a[$i] >= 'A' && $a[$i] <= 'Z') $a[$i] = chr(97 + (ord($a[$i]) - ord('a'))); } return $a;} // Function to delete vowelsfunction delete_vowels($a){ $temp = \"\"; $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character // is consonant if($a[$i] != 'a' && $a[$i] != 'e' && $a[$i] != 'i' && $a[$i] != 'o' && $a[$i] != 'u' && $a[$i] != 'A' && $a[$i] != 'E' && $a[$i] != 'O' && $a[$i] != 'U' && $a[$i] != 'I') $temp = $temp.$a[$i]; } return $temp; } // Function to insert \"#\"function insert_hash($a){ $temp = \"\"; $l = strlen($a); for($i = 0 ; $i < $l ; $i++) { // If character is // not special if(($a[$i] >= 'a' && $a[$i] <= 'z') || ($a[$i] >= 'A' && $a[$i] <= 'Z')) $temp = $temp . '#' . $a[$i]; else $temp = $temp.$a[$i]; } return $temp; } // Function to// transform stringfunction transformSting($a){ $b = delete_vowels($a); $c = change_case($b); $d = insert_hash($c); echo ($d);} // Driver Code$a = \"SunshinE!!\"; // Calling functiontransformSting($a); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 10392, "s": 8591, "text": null }, { "code": "// Function to change// character's casefunction change_case(a){ var temp = \"\"; var l = a.length; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is lowercase // change to uppercase if (ch >= 'a' && ch <= 'z') { ch = String.fromCharCode((65 + parseInt((ch.charCodeAt(0) - 'a'.charCodeAt(0))))); } else if (ch >= 'A' && ch <= 'Z') { ch = String.fromCharCode((97 + parseInt((ch.charCodeAt(0) - 'A'.charCodeAt(0))))); } temp += ch; } return temp;}// Function to delete vowelsfunction delete_vowels(a){ var temp = \"\"; var l = a.length; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is consonant if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' && ch != 'A' && ch != 'E' && ch != 'O' && ch != 'U' && ch != 'I') { temp += ch; } } return temp;}// Function to insert \"#\"function insert_hash(a){ var temp = \"\"; var l = a.length; var hash = '#'; for (var i=0; i < l; i++) { var ch = a.charAt(i); // If character is not // special character if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { temp = temp + hash + ch; } else { temp = temp + ch; } } return temp;}// Function to transform stringfunction transformString(a){ var b = delete_vowels(a); var c = change_case(b); var d = insert_hash(c); if(d==\"\") console.log(\"-1\"); else console.log(d);} // Driver functionvar a = \"SunshinE!!\";var b = \"aeiou\";// Calling functiontransformString(a);transformString(b); // This code is contributed by Aarti_Rathi", "e": 12158, "s": 10392, "text": null }, { "code": null, "e": 12174, "s": 12158, "text": "#s#N#S#H#N!!\n-1" }, { "code": null, "e": 12235, "s": 12174, "text": "Time complexity: O(n), where n is the length of the string" }, { "code": null, "e": 12295, "s": 12235, "text": "Auxiliary Space: O(n), where n is the length of the string " }, { "code": null, "e": 12307, "s": 12295, "text": "manishshaw1" }, { "code": null, "e": 12327, "s": 12307, "text": "abhishek0719kadiyan" }, { "code": null, "e": 12343, "s": 12327, "text": "surbhikumaridav" }, { "code": null, "e": 12357, "s": 12343, "text": "geekygirl2001" }, { "code": null, "e": 12375, "s": 12357, "text": "rohitmishra051000" }, { "code": null, "e": 12389, "s": 12375, "text": "codewithrathi" }, { "code": null, "e": 12397, "s": 12389, "text": "Strings" }, { "code": null, "e": 12405, "s": 12397, "text": "Strings" }, { "code": null, "e": 12503, "s": 12405, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12578, "s": 12503, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 12623, "s": 12578, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 12680, "s": 12623, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 12716, "s": 12680, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 12754, "s": 12716, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 12815, "s": 12754, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 12860, "s": 12815, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 12924, "s": 12860, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12960, "s": 12924, "text": "Convert string to char array in C++" } ]
JavaScript Array.of() function
01 Nov, 2021 The array.of() function is an inbuilt function in JavaScript that creates a new array instance with variables present as the argument of the function. Syntax: Array.of(element0, element1, ....) Parameters: Parameters present are element0, element1, .... which are basically an element for which the array creation is done. Return Value: It simply returns a new Array instance. Browser Support: Here 2nd column contained int values are versions of the corresponding browser. Examples: Input: Array.of(10, 20, 30) Output: > Array [10, 20, 30] Explanation: Here in input arguments of the array.of() function is numbers converted into an array containing the same argument shown in the output. Input: Array.of("Ram","Geeta") Output: > Array ["Ram", "Geeta"] Explanation: Here in input arguments of the array.of() function is string converted into an array containing the same argument shown in the output.Let’s see JavaScripts program on Array.of() function: JavaScript <script> // Here the Array.of() method creates a new Array instance with // a variable number of arguments, regardless of // number or type of the arguments. console.log(Array.of(0, 0, 0)); console.log(Array.of(11, 21, 33)); console.log(Array.of("Ram","Geeta")); console.log(Array.of('geeksforgeeks')); console.log(Array.of(2,3,4,'Sheeta'));</script> Output: > Array [0, 0, 0] > Array [11, 21, 33] > Array ["Ram", "Geeta"] > Array ["geeksforgeeks"] > Array [2, 3, 4, "Sheeta"] Application: Whenever we need to get elements of an array that time we take the help of the Array.of( ) method in JavaScript. JavaScript <script> console.log(Array.of(['Ram', 'Rahim', 'Geeta', 'Sheeta']));</script> Output: > Array [Array ["Ram", "Rahim", "Geeta", "Sheeta"]] Polyfills provide a way to implement new features into old browsers that do not support the newest updated version of JavaScript code. Array.of( ) function does not support by Internet Explorer browser. As a developer, it’s your responsibility to provide a code that runs everywhere ( browser in this case ). So let’s see how to create a polyfill for Array.of( ) Steps : Check if Array.of( ) function is supported in browser or not. Now create a function expression named Array.of( ) . This function takes the items of the array. Now create an array and push all the argument items into it. Now return the array created by you. Javascript <script> // check if Array.of( ) feature present in your browser or not if(!Array.of){ // Create a function Array.of = function() { let newArr = []; // Pushing all the arguments into newArr for(let items in arguments){ newArr.push(arguments[items]); } // return the array return newArr; } } </script> Output : > Array.of(1, 2, 3, 4, 5, 6) > [1, 2, 3, 4, 5, 6] > Array.of("John", "Doe", "Smith", "Ram") > ["John", "Doe", "Smith", "Ram"] Supported Browser: Chrome 45 and above Edge 12 and above Firefox 25 and above Opera 26 and above Safari 9 and above Akanksha_Rai _saurabh_jaiswal sagartomar9927 ysachin2314 javascript-array JavaScript 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 How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2021" }, { "code": null, "e": 180, "s": 28, "text": "The array.of() function is an inbuilt function in JavaScript that creates a new array instance with variables present as the argument of the function. " }, { "code": null, "e": 188, "s": 180, "text": "Syntax:" }, { "code": null, "e": 223, "s": 188, "text": "Array.of(element0, element1, ....)" }, { "code": null, "e": 505, "s": 223, "text": "Parameters: Parameters present are element0, element1, .... which are basically an element for which the array creation is done. Return Value: It simply returns a new Array instance. Browser Support: Here 2nd column contained int values are versions of the corresponding browser. " }, { "code": null, "e": 517, "s": 505, "text": "Examples: " }, { "code": null, "e": 574, "s": 517, "text": "Input: Array.of(10, 20, 30)\nOutput: > Array [10, 20, 30]" }, { "code": null, "e": 725, "s": 574, "text": "Explanation: Here in input arguments of the array.of() function is numbers converted into an array containing the same argument shown in the output. " }, { "code": null, "e": 789, "s": 725, "text": "Input: Array.of(\"Ram\",\"Geeta\")\nOutput: > Array [\"Ram\", \"Geeta\"]" }, { "code": null, "e": 992, "s": 789, "text": "Explanation: Here in input arguments of the array.of() function is string converted into an array containing the same argument shown in the output.Let’s see JavaScripts program on Array.of() function: " }, { "code": null, "e": 1003, "s": 992, "text": "JavaScript" }, { "code": "<script> // Here the Array.of() method creates a new Array instance with // a variable number of arguments, regardless of // number or type of the arguments. console.log(Array.of(0, 0, 0)); console.log(Array.of(11, 21, 33)); console.log(Array.of(\"Ram\",\"Geeta\")); console.log(Array.of('geeksforgeeks')); console.log(Array.of(2,3,4,'Sheeta'));</script>", "e": 1364, "s": 1003, "text": null }, { "code": null, "e": 1374, "s": 1364, "text": "Output: " }, { "code": null, "e": 1492, "s": 1374, "text": "> Array [0, 0, 0]\n> Array [11, 21, 33]\n> Array [\"Ram\", \"Geeta\"]\n> Array [\"geeksforgeeks\"]\n> Array [2, 3, 4, \"Sheeta\"]" }, { "code": null, "e": 1620, "s": 1492, "text": "Application: Whenever we need to get elements of an array that time we take the help of the Array.of( ) method in JavaScript. " }, { "code": null, "e": 1631, "s": 1620, "text": "JavaScript" }, { "code": "<script> console.log(Array.of(['Ram', 'Rahim', 'Geeta', 'Sheeta']));</script>", "e": 1710, "s": 1631, "text": null }, { "code": null, "e": 1720, "s": 1710, "text": "Output: " }, { "code": null, "e": 1772, "s": 1720, "text": "> Array [Array [\"Ram\", \"Rahim\", \"Geeta\", \"Sheeta\"]]" }, { "code": null, "e": 1907, "s": 1772, "text": "Polyfills provide a way to implement new features into old browsers that do not support the newest updated version of JavaScript code." }, { "code": null, "e": 2081, "s": 1907, "text": "Array.of( ) function does not support by Internet Explorer browser. As a developer, it’s your responsibility to provide a code that runs everywhere ( browser in this case )." }, { "code": null, "e": 2135, "s": 2081, "text": "So let’s see how to create a polyfill for Array.of( )" }, { "code": null, "e": 2143, "s": 2135, "text": "Steps :" }, { "code": null, "e": 2205, "s": 2143, "text": "Check if Array.of( ) function is supported in browser or not." }, { "code": null, "e": 2302, "s": 2205, "text": "Now create a function expression named Array.of( ) . This function takes the items of the array." }, { "code": null, "e": 2363, "s": 2302, "text": "Now create an array and push all the argument items into it." }, { "code": null, "e": 2400, "s": 2363, "text": "Now return the array created by you." }, { "code": null, "e": 2411, "s": 2400, "text": "Javascript" }, { "code": "<script> // check if Array.of( ) feature present in your browser or not if(!Array.of){ // Create a function Array.of = function() { let newArr = []; // Pushing all the arguments into newArr for(let items in arguments){ newArr.push(arguments[items]); } // return the array return newArr; } } </script>", "e": 2788, "s": 2411, "text": null }, { "code": null, "e": 2797, "s": 2788, "text": "Output :" }, { "code": null, "e": 2924, "s": 2797, "text": "> Array.of(1, 2, 3, 4, 5, 6)\n> [1, 2, 3, 4, 5, 6]\n\n> Array.of(\"John\", \"Doe\", \"Smith\", \"Ram\")\n> [\"John\", \"Doe\", \"Smith\", \"Ram\"]" }, { "code": null, "e": 2943, "s": 2924, "text": "Supported Browser:" }, { "code": null, "e": 2963, "s": 2943, "text": "Chrome 45 and above" }, { "code": null, "e": 2981, "s": 2963, "text": "Edge 12 and above" }, { "code": null, "e": 3002, "s": 2981, "text": "Firefox 25 and above" }, { "code": null, "e": 3021, "s": 3002, "text": "Opera 26 and above" }, { "code": null, "e": 3040, "s": 3021, "text": "Safari 9 and above" }, { "code": null, "e": 3053, "s": 3040, "text": "Akanksha_Rai" }, { "code": null, "e": 3070, "s": 3053, "text": "_saurabh_jaiswal" }, { "code": null, "e": 3085, "s": 3070, "text": "sagartomar9927" }, { "code": null, "e": 3097, "s": 3085, "text": "ysachin2314" }, { "code": null, "e": 3114, "s": 3097, "text": "javascript-array" }, { "code": null, "e": 3125, "s": 3114, "text": "JavaScript" }, { "code": null, "e": 3223, "s": 3125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3284, "s": 3223, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3356, "s": 3284, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3396, "s": 3356, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3448, "s": 3396, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3489, "s": 3448, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3535, "s": 3489, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 3577, "s": 3535, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3631, "s": 3577, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3686, "s": 3631, "text": "How do you run JavaScript script through the Terminal?" } ]
Bitwise Complement Operator (~ tilde)
10 Dec, 2021 Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1’s become 0’s and vice versa. The operator for the bitwise complement is ~ (Tilde). Example: Input: ~ 0000 0011Output: 1111 1100 Input: 1110 0111Output: 0001 1000 The bitwise complement operator should be used carefully. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And the result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit). Input: n = 2Binary form of 2 = 0010Bitwise complement operation on 2 = ~ 0010 = 1101 1101 is equivalent to decimal value 13. Expected output: 13Correct Output : -3 The compiler returns the 2’s complement of the input value. C C++ Java Python3 C# Javascript // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ int n = 2; printf("Bitwise complement of %d : %d", n, ~n); return 0;} // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int a = 2; cout << "Bitwise complement of " << a << " : " << ~a;} // Java program to implement// the above approachimport java.io.*; // Driver codeclass GFG{ public static void main (String[] args) { int a = 2; System.out.println("Bitwise complement of " + a + " : " + ~a); }} # Python3 program to implement# the above approach # Driver coden = 2print("Bitwise complement of {n} :", ~n) // C# program to implement // the above approachusing System; class GFG{ static public void Main(){ int a = 2; Console.WriteLine("Bitwise complement of " + a + " : " + ~a);}} <script> // JavaScript program to implement // the above approach // Driver codelet a = 2;document.write("Bitwise complement of " + a + " : " + ~a); // This code is contributed by Potta Lokesh </script> Output: Bitwise complement of 2 : -3 Explanation:The bitwise complement of 2 (~2) is -3 instead of 13, but why? When numbers are printed in base-10, the result of a NOT operation can be surprising. In particular, positive numbers can become negative and vice versa. Let’s first find the binary representation of bitwise complement of 2 which is -3 The negative numbers are stored as the two’s complement of the positive counterpart. 2’s Complement:Two’s complement is an operation on binary numbers. The 2’s complement of a number is equal to the complement of that number plus 1. Example: Bitwise complement Operation of 2 (~ 0010 ): 1101 Calculate 2’s complement of 3: Binary form of 3 = 0011 1’s Complement of 3 = 1100 Adding 1 to 1’s complement = 1100 +12’s complement of 3 = 1101 Note: The bitwise Complement of 2 is same as the binary representation of -3 Thus it can be concluded from the above example that- For any integer n, the bitwise complement of n will be -(n+1).Bitwise complement of N = ~N (represented in 2’s complement form).2’complement of ~N= -(~(~N)+1) = -(N+1). For any integer n, the bitwise complement of n will be -(n+1). Bitwise complement of N = ~N (represented in 2’s complement form). 2’complement of ~N= -(~(~N)+1) = -(N+1). lokeshpotta20 C-Operators cpp-operator Java-Operators Bit Magic C Language C++ Java Programming Language Python cpp-operator Java-Operators Bit Magic Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2021" }, { "code": null, "e": 95, "s": 28, "text": "Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java" }, { "code": null, "e": 364, "s": 95, "text": "The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1’s become 0’s and vice versa. The operator for the bitwise complement is ~ (Tilde)." }, { "code": null, "e": 373, "s": 364, "text": "Example:" }, { "code": null, "e": 409, "s": 373, "text": "Input: ~ 0000 0011Output: 1111 1100" }, { "code": null, "e": 443, "s": 409, "text": "Input: 1110 0111Output: 0001 1000" }, { "code": null, "e": 809, "s": 443, "text": "The bitwise complement operator should be used carefully. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And the result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit)." }, { "code": null, "e": 991, "s": 809, "text": "Input: n = 2Binary form of 2 = 0010Bitwise complement operation on 2 = ~ 0010 = 1101 1101 is equivalent to decimal value 13." }, { "code": null, "e": 1030, "s": 991, "text": "Expected output: 13Correct Output : -3" }, { "code": null, "e": 1090, "s": 1030, "text": "The compiler returns the 2’s complement of the input value." }, { "code": null, "e": 1092, "s": 1090, "text": "C" }, { "code": null, "e": 1096, "s": 1092, "text": "C++" }, { "code": null, "e": 1101, "s": 1096, "text": "Java" }, { "code": null, "e": 1109, "s": 1101, "text": "Python3" }, { "code": null, "e": 1112, "s": 1109, "text": "C#" }, { "code": null, "e": 1123, "s": 1112, "text": "Javascript" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ int n = 2; printf(\"Bitwise complement of %d : %d\", n, ~n); return 0;}", "e": 1296, "s": 1123, "text": null }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ int a = 2; cout << \"Bitwise complement of \" << a << \" : \" << ~a;}", "e": 1488, "s": 1296, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*; // Driver codeclass GFG{ public static void main (String[] args) { int a = 2; System.out.println(\"Bitwise complement of \" + a + \" : \" + ~a); }}", "e": 1749, "s": 1488, "text": null }, { "code": "# Python3 program to implement# the above approach # Driver coden = 2print(\"Bitwise complement of {n} :\", ~n)", "e": 1865, "s": 1749, "text": null }, { "code": "// C# program to implement // the above approachusing System; class GFG{ static public void Main(){ int a = 2; Console.WriteLine(\"Bitwise complement of \" + a + \" : \" + ~a);}}", "e": 2072, "s": 1865, "text": null }, { "code": "<script> // JavaScript program to implement // the above approach // Driver codelet a = 2;document.write(\"Bitwise complement of \" + a + \" : \" + ~a); // This code is contributed by Potta Lokesh </script>", "e": 2289, "s": 2072, "text": null }, { "code": null, "e": 2297, "s": 2289, "text": "Output:" }, { "code": null, "e": 2326, "s": 2297, "text": "Bitwise complement of 2 : -3" }, { "code": null, "e": 2555, "s": 2326, "text": "Explanation:The bitwise complement of 2 (~2) is -3 instead of 13, but why? When numbers are printed in base-10, the result of a NOT operation can be surprising. In particular, positive numbers can become negative and vice versa." }, { "code": null, "e": 2637, "s": 2555, "text": "Let’s first find the binary representation of bitwise complement of 2 which is -3" }, { "code": null, "e": 2722, "s": 2637, "text": "The negative numbers are stored as the two’s complement of the positive counterpart." }, { "code": null, "e": 2871, "s": 2722, "text": "2’s Complement:Two’s complement is an operation on binary numbers. The 2’s complement of a number is equal to the complement of that number plus 1. " }, { "code": null, "e": 2880, "s": 2871, "text": "Example:" }, { "code": null, "e": 2930, "s": 2880, "text": "Bitwise complement Operation of 2 (~ 0010 ): 1101" }, { "code": null, "e": 3077, "s": 2930, "text": "Calculate 2’s complement of 3: Binary form of 3 = 0011 1’s Complement of 3 = 1100 Adding 1 to 1’s complement = 1100 +12’s complement of 3 = 1101 " }, { "code": null, "e": 3156, "s": 3077, "text": "Note: The bitwise Complement of 2 is same as the binary representation of -3 " }, { "code": null, "e": 3210, "s": 3156, "text": "Thus it can be concluded from the above example that-" }, { "code": null, "e": 3379, "s": 3210, "text": "For any integer n, the bitwise complement of n will be -(n+1).Bitwise complement of N = ~N (represented in 2’s complement form).2’complement of ~N= -(~(~N)+1) = -(N+1)." }, { "code": null, "e": 3442, "s": 3379, "text": "For any integer n, the bitwise complement of n will be -(n+1)." }, { "code": null, "e": 3509, "s": 3442, "text": "Bitwise complement of N = ~N (represented in 2’s complement form)." }, { "code": null, "e": 3550, "s": 3509, "text": "2’complement of ~N= -(~(~N)+1) = -(N+1)." }, { "code": null, "e": 3564, "s": 3550, "text": "lokeshpotta20" }, { "code": null, "e": 3576, "s": 3564, "text": "C-Operators" }, { "code": null, "e": 3589, "s": 3576, "text": "cpp-operator" }, { "code": null, "e": 3604, "s": 3589, "text": "Java-Operators" }, { "code": null, "e": 3614, "s": 3604, "text": "Bit Magic" }, { "code": null, "e": 3625, "s": 3614, "text": "C Language" }, { "code": null, "e": 3629, "s": 3625, "text": "C++" }, { "code": null, "e": 3634, "s": 3629, "text": "Java" }, { "code": null, "e": 3655, "s": 3634, "text": "Programming Language" }, { "code": null, "e": 3662, "s": 3655, "text": "Python" }, { "code": null, "e": 3675, "s": 3662, "text": "cpp-operator" }, { "code": null, "e": 3690, "s": 3675, "text": "Java-Operators" }, { "code": null, "e": 3700, "s": 3690, "text": "Bit Magic" }, { "code": null, "e": 3705, "s": 3700, "text": "Java" }, { "code": null, "e": 3709, "s": 3705, "text": "CPP" } ]
How to transform child elements preserve the 3D transformations ?
30 Apr, 2021 The CSS transform-style property is used to transform child elements to preserve the 3D transformations. The transform-style property is used to specify that the children of an element are positioned in 3D space or flattened with respect to the plane of the element. The preserve-3d property value on an element, one can preserve the 3D transformations of its child element. Syntax: transform-style: preserve-3d Property values: preserve-3d: This value enables the child elements to preserve their 3D position. Example 1: HTML <!DOCTYPE html><html> <head> <style> h2 { color: green; } .parent { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* Now its child's 3d-position is preserved which means childrens of the this element should be positioned in the 3D-space not in a plane */ transform-style: preserve-3d; } .child { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } </style> </head> <body> <center> <h2>GeeksforGeeks</h2> <b>CSS transform-style Property</b> <div class="parent"> <div class="child"></div> </div> </center> </body></html> Output: transform-style:preserve 3d Example 2: HTML <!DOCTYPE html><html> <head> <style> h2 { color: green; } .parent { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* Now its child's 3d-position is preserved which means childrens of the this element should be positioned in the 3D-space not in a plane */ transform-style: preserve-3d; } .child { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } .gfg1 { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* flat is default value whose children element are lying in the plane of the element itself */ transform-style: flat; } .gfg2 { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } </style> </head> <body> <center> <h2>GeeksforGeeks</h2> <br /> <table> <tr> <td width="350px"> <div> <b>Flat(default) Property Value</b> <div class="parent"> <div class="child"></div> </div> </div> </td> <td width="350px"> <div> <b>preserve-3d Property Value</b> <div class="gfg1"> <div class="gfg2"></div> </div> </div> </td> </tr> </table> </center> </body></html> Output: flat and preserve 3d properties CSS-Properties CSS-Questions Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2021" }, { "code": null, "e": 403, "s": 28, "text": "The CSS transform-style property is used to transform child elements to preserve the 3D transformations. The transform-style property is used to specify that the children of an element are positioned in 3D space or flattened with respect to the plane of the element. The preserve-3d property value on an element, one can preserve the 3D transformations of its child element." }, { "code": null, "e": 412, "s": 403, "text": "Syntax: " }, { "code": null, "e": 441, "s": 412, "text": "transform-style: preserve-3d" }, { "code": null, "e": 458, "s": 441, "text": "Property values:" }, { "code": null, "e": 540, "s": 458, "text": "preserve-3d: This value enables the child elements to preserve their 3D position." }, { "code": null, "e": 553, "s": 540, "text": "Example 1: " }, { "code": null, "e": 558, "s": 553, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h2 { color: green; } .parent { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* Now its child's 3d-position is preserved which means childrens of the this element should be positioned in the 3D-space not in a plane */ transform-style: preserve-3d; } .child { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } </style> </head> <body> <center> <h2>GeeksforGeeks</h2> <b>CSS transform-style Property</b> <div class=\"parent\"> <div class=\"child\"></div> </div> </center> </body></html>", "e": 1425, "s": 558, "text": null }, { "code": null, "e": 1433, "s": 1425, "text": "Output:" }, { "code": null, "e": 1461, "s": 1433, "text": "transform-style:preserve 3d" }, { "code": null, "e": 1473, "s": 1461, "text": "Example 2: " }, { "code": null, "e": 1478, "s": 1473, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h2 { color: green; } .parent { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* Now its child's 3d-position is preserved which means childrens of the this element should be positioned in the 3D-space not in a plane */ transform-style: preserve-3d; } .child { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } .gfg1 { margin: 20px; border: 1px double; height: 200px; width: 200px; background-color: green; transform: rotateX(15deg); /* flat is default value whose children element are lying in the plane of the element itself */ transform-style: flat; } .gfg2 { margin: 20px; border: 1px dashed; height: 250px; width: 250px; background-color: lightgreen; transform: rotateX(45deg); } </style> </head> <body> <center> <h2>GeeksforGeeks</h2> <br /> <table> <tr> <td width=\"350px\"> <div> <b>Flat(default) Property Value</b> <div class=\"parent\"> <div class=\"child\"></div> </div> </div> </td> <td width=\"350px\"> <div> <b>preserve-3d Property Value</b> <div class=\"gfg1\"> <div class=\"gfg2\"></div> </div> </div> </td> </tr> </table> </center> </body></html>", "e": 3243, "s": 1478, "text": null }, { "code": null, "e": 3251, "s": 3243, "text": "Output:" }, { "code": null, "e": 3283, "s": 3251, "text": "flat and preserve 3d properties" }, { "code": null, "e": 3298, "s": 3283, "text": "CSS-Properties" }, { "code": null, "e": 3312, "s": 3298, "text": "CSS-Questions" }, { "code": null, "e": 3319, "s": 3312, "text": "Picked" }, { "code": null, "e": 3323, "s": 3319, "text": "CSS" }, { "code": null, "e": 3340, "s": 3323, "text": "Web Technologies" }, { "code": null, "e": 3438, "s": 3340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3477, "s": 3438, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3516, "s": 3477, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3555, "s": 3516, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3584, "s": 3555, "text": "Form validation using jQuery" }, { "code": null, "e": 3621, "s": 3584, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3654, "s": 3621, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3715, "s": 3654, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3758, "s": 3715, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3830, "s": 3758, "text": "Differences between Functional Components and Class Components in React" } ]
Find n-th term of series 1, 3, 6, 10, 15, 21 | Practice | GeeksforGeeks
Given a number N, find the Nth term in the series 1, 3, 6, 10, 15, 21... Example 1: Input : N = 4 Output: 10 Explanation: The 4th term of the Series is 10. Example 2: Input : N = 3 Output: 6 Explanation: The 3rd term of the Series is 6. Your Task: You don't need to read input or print anything. Your task is to complete the function findNthTerm() which takes an Integer N as input and returns the answer. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 104 0 bhaskarkurukuri12 weeks ago The simple and simplified solution in C++: int findNthTerm(int N) { return (N*N+N)/2; } 0 shobhitgautam19992 weeks ago class Solution { static int findNthTerm(int N) { if(N == 1) { return 1; } int counter=2; int sum = 1; while(N !=1) { N--; sum = sum+counter; counter = counter + 1; } return sum; }}; 0 rumi1w8ry3 weeks ago def findNthTerm(self, N): # code here return (N*N+N)//2 +1 rb0012 months ago // Code By Rahul Bisht public: int findNthTerm(int N) { // code here return (N*(N+1))/2; }}; 0 samirmistry12 months ago class Solution { static int findNthTerm(int N) { // code here int[] arr = new int[N]; arr[0] =1; for(int i=1;i<N;i++) { arr[i] = (i+1) + arr[i-1]; /* arr[1] = 1 2 = 2+arr[1] 3 = 3 + arr[3] 4 = 4 + arr[4] */ } return (arr[N-1]); } }; 0 mayank180919992 months ago int findNthTerm(int N) { // code here return (N*N+N)/2; } -1 rsbly7300953 months ago class Solution { findNthTerm(N){ return (N*((N+1)/2)) } } 0 ishangarg23 months ago recursive solution: int sum = 0; if(N == 0) return 0; sum = findNthTerm(N-1); return sum + N; +1 sayanmazumder9993 months ago JAVA int sum = 1; for(int i = 2; i<N+1; i++) sum += i; return sum; 0 kirankolte21563 months ago class Solution { static int findNthTerm(int N) { // code here return N*(N+1)/2; }} 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": 311, "s": 238, "text": "Given a number N, find the Nth term in the series 1, 3, 6, 10, 15, 21..." }, { "code": null, "e": 324, "s": 313, "text": "Example 1:" }, { "code": null, "e": 397, "s": 324, "text": "Input :\nN = 4 \nOutput:\n10\nExplanation:\nThe 4th term of the Series is 10." }, { "code": null, "e": 408, "s": 397, "text": "Example 2:" }, { "code": null, "e": 479, "s": 408, "text": "Input :\nN = 3 \nOutput:\n6\nExplanation:\nThe 3rd term of the Series is 6." }, { "code": null, "e": 650, "s": 481, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findNthTerm() which takes an Integer N as input and returns the answer." }, { "code": null, "e": 714, "s": 652, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 743, "s": 716, "text": "Constraints:\n1 <= N <= 104" }, { "code": null, "e": 745, "s": 743, "text": "0" }, { "code": null, "e": 773, "s": 745, "text": "bhaskarkurukuri12 weeks ago" }, { "code": null, "e": 816, "s": 773, "text": "The simple and simplified solution in C++:" }, { "code": null, "e": 871, "s": 818, "text": "int findNthTerm(int N) { return (N*N+N)/2; }" }, { "code": null, "e": 873, "s": 871, "text": "0" }, { "code": null, "e": 902, "s": 873, "text": "shobhitgautam19992 weeks ago" }, { "code": null, "e": 1215, "s": 902, "text": "class Solution { static int findNthTerm(int N) { if(N == 1) { return 1; } int counter=2; int sum = 1; while(N !=1) { N--; sum = sum+counter; counter = counter + 1; } return sum; }};" }, { "code": null, "e": 1217, "s": 1215, "text": "0" }, { "code": null, "e": 1238, "s": 1217, "text": "rumi1w8ry3 weeks ago" }, { "code": null, "e": 1309, "s": 1238, "text": "def findNthTerm(self, N):\n # code here \n return (N*N+N)//2" }, { "code": null, "e": 1312, "s": 1309, "text": "+1" }, { "code": null, "e": 1330, "s": 1312, "text": "rb0012 months ago" }, { "code": null, "e": 1354, "s": 1330, "text": " // Code By Rahul Bisht" }, { "code": null, "e": 1439, "s": 1354, "text": "public: int findNthTerm(int N) { // code here return (N*(N+1))/2; }};" }, { "code": null, "e": 1441, "s": 1439, "text": "0" }, { "code": null, "e": 1466, "s": 1441, "text": "samirmistry12 months ago" }, { "code": null, "e": 1857, "s": 1466, "text": "class Solution {\n static int findNthTerm(int N) {\n // code here\n int[] arr = new int[N];\n arr[0] =1;\n for(int i=1;i<N;i++)\n {\n arr[i] = (i+1) + arr[i-1];\n /*\n arr[1] = 1\n 2 = 2+arr[1]\n 3 = 3 + arr[3]\n 4 = 4 + arr[4]\n */\n }\n\n return (arr[N-1]);\n \n }\n};" }, { "code": null, "e": 1859, "s": 1857, "text": "0" }, { "code": null, "e": 1886, "s": 1859, "text": "mayank180919992 months ago" }, { "code": null, "e": 1967, "s": 1886, "text": " int findNthTerm(int N) {\n // code here\n return (N*N+N)/2;\n }" }, { "code": null, "e": 1970, "s": 1967, "text": "-1" }, { "code": null, "e": 1994, "s": 1970, "text": "rsbly7300953 months ago" }, { "code": null, "e": 2064, "s": 1994, "text": "class Solution {\n findNthTerm(N){\n return (N*((N+1)/2))\n }\n}" }, { "code": null, "e": 2066, "s": 2064, "text": "0" }, { "code": null, "e": 2089, "s": 2066, "text": "ishangarg23 months ago" }, { "code": null, "e": 2109, "s": 2089, "text": "recursive solution:" }, { "code": null, "e": 2205, "s": 2109, "text": " int sum = 0; if(N == 0) return 0; sum = findNthTerm(N-1); return sum + N; " }, { "code": null, "e": 2208, "s": 2205, "text": "+1" }, { "code": null, "e": 2237, "s": 2208, "text": "sayanmazumder9993 months ago" }, { "code": null, "e": 2242, "s": 2237, "text": "JAVA" }, { "code": null, "e": 2328, "s": 2242, "text": " int sum = 1; for(int i = 2; i<N+1; i++) sum += i; return sum;" }, { "code": null, "e": 2330, "s": 2328, "text": "0" }, { "code": null, "e": 2357, "s": 2330, "text": "kirankolte21563 months ago" }, { "code": null, "e": 2476, "s": 2359, "text": "class Solution { static int findNthTerm(int N) { // code here return N*(N+1)/2; }}" }, { "code": null, "e": 2622, "s": 2476, "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": 2658, "s": 2622, "text": " Login to access your submissions. " }, { "code": null, "e": 2668, "s": 2658, "text": "\nProblem\n" }, { "code": null, "e": 2678, "s": 2668, "text": "\nContest\n" }, { "code": null, "e": 2741, "s": 2678, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2926, "s": 2741, "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": 3210, "s": 2926, "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": 3356, "s": 3210, "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": 3433, "s": 3356, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 3474, "s": 3433, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 3502, "s": 3474, "text": "Disable browser extensions." }, { "code": null, "e": 3573, "s": 3502, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 3760, "s": 3573, "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." } ]
How to abort a merge conflict in Git?
When doing a merge, you may run into one or more conflicts. Now what if we are not quite ready to handle this conflict yet. Perhaps you have several conflicts and you don't have enough time to spend on resolving these conflicts. In situations like this we can easily go back to the state before we started the merge. To abort the merge, we can use the following command $ git merge --abort Note that if we execute this command after resolving some conflicts and staging the changes, then these changes would not be saved. Once the command is fired, we are back to the clean state i.e., the state before we started the merge. We can understand this from the below diagram. There are two branches, master and feature, and each one is operating on the same file. When we merge the feature branch with the master branch, we will end up with a merge conflict error. Now if we abort the merge conflict we will get back to the state before the conflict as shown in the diagram. Let us see this in action to understand how to abort a merge conflict. Step 1 − Create a repository with initial commit with hello.txt file. $ git init Initialized empty Git repository in E:/tut_repo/.git/ $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo hello>hello.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git commit -m 'hello.txt' [master (root-commit) d861f5f] hello 1 file changed, 1 insertion(+) create mode 100644 hello.txt Step 2 − Create a new branch feature. Switch to feature branch and create a new commit by editing second line in hello.txt file $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git branch feature $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git switch feature Switched to branch 'feature' $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature) $ echo hello feature >> hello.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature) $ git commit -m 'hello feature' [feature 4b2c833] hello feature 1 file changed, 1 insertion(+) Step 3 − Switch to master branch and perform a new commit by adding a new line to hello.txt. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature) $ git switch master Switched to branch 'master' $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ cat hello.txt hello $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ echo hello master>>hello.txt $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git add . $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git commit -m 'hello master' [master 6b1e9a4] hello master 1 file changed, 1 insertion(+) Step 4 − We will now merge changes from feature branch to the master branch. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git merge feature Auto-merging hello.txt CONFLICT (content): Merge conflict in hello.txt Automatic merge failed; fix conflicts and then commit the result. $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master|MERGING) The output shows that the branch is in an intermediate state of merging as the automatic merging failed due to conflict. Step 5 − Now we decide to abort the merge conflict. Before aborting we can check the status of the repository using git status. $$ git status -s UU hello.txt The UU status shows the file hello.txt is in the unmerged state in the working directory and the staging area. Step 6 − Finally let’s abort the conflict $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master|MERGING) $ git merge --abort $ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master) $ git status On branch master nothing to commit, working tree clean From the output it is clear that after aborting the merge (master|MERGING) has changed to (master). Also, if we check git status it will indicate that the working tree is clean.
[ { "code": null, "e": 1504, "s": 1187, "text": "When doing a merge, you may run into one or more conflicts. Now what if we are not quite ready to handle this conflict yet. Perhaps you have several conflicts and you don't have enough time to spend on resolving these conflicts. In situations like this we can easily go back to the state before we started the merge." }, { "code": null, "e": 1557, "s": 1504, "text": "To abort the merge, we can use the following command" }, { "code": null, "e": 1577, "s": 1557, "text": "$ git merge --abort" }, { "code": null, "e": 1812, "s": 1577, "text": "Note that if we execute this command after resolving some conflicts and staging the changes, then these changes would not be saved. Once the command is fired, we are back to the clean state i.e., the state before we started the merge." }, { "code": null, "e": 2158, "s": 1812, "text": "We can understand this from the below diagram. There are two branches, master and feature, and each one is operating on the same file. When we merge the feature branch with the master branch, we will end up with a merge conflict error. Now if we abort the merge conflict we will get back to the state before the conflict as shown in the diagram." }, { "code": null, "e": 2229, "s": 2158, "text": "Let us see this in action to understand how to abort a merge conflict." }, { "code": null, "e": 2299, "s": 2229, "text": "Step 1 − Create a repository with initial commit with hello.txt file." }, { "code": null, "e": 2683, "s": 2299, "text": "$ git init\nInitialized empty Git repository in E:/tut_repo/.git/\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo hello>hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'hello.txt'\n[master (root-commit) d861f5f] hello\n1 file changed, 1 insertion(+)\ncreate mode 100644 hello.txt" }, { "code": null, "e": 2811, "s": 2683, "text": "Step 2 − Create a new branch feature. Switch to feature branch and create a new commit by editing second line in hello.txt file" }, { "code": null, "e": 3290, "s": 2811, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git branch feature\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git switch feature\nSwitched to branch 'feature'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ echo hello feature >> hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git commit -m 'hello feature'\n[feature 4b2c833] hello feature\n1 file changed, 1 insertion(+)" }, { "code": null, "e": 3383, "s": 3290, "text": "Step 3 − Switch to master branch and perform a new commit by adding a new line to hello.txt." }, { "code": null, "e": 3853, "s": 3383, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git switch master\nSwitched to branch 'master'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat hello.txt\nhello\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo hello master>>hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'hello master'\n[master 6b1e9a4] hello master\n1 file changed, 1 insertion(+)" }, { "code": null, "e": 3930, "s": 3853, "text": "Step 4 − We will now merge changes from feature branch to the master branch." }, { "code": null, "e": 4200, "s": 3930, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git merge feature\nAuto-merging hello.txt\nCONFLICT (content): Merge conflict in hello.txt\nAutomatic merge failed; fix conflicts and then commit the result.\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master|MERGING)" }, { "code": null, "e": 4321, "s": 4200, "text": "The output shows that the branch is in an intermediate state of merging as the automatic merging failed due to conflict." }, { "code": null, "e": 4449, "s": 4321, "text": "Step 5 − Now we decide to abort the merge conflict. Before aborting we can check the status of the repository using git status." }, { "code": null, "e": 4479, "s": 4449, "text": "$$ git status -s\nUU hello.txt" }, { "code": null, "e": 4590, "s": 4479, "text": "The UU status shows the file hello.txt is in the unmerged state in the working directory and the staging area." }, { "code": null, "e": 4632, "s": 4590, "text": "Step 6 − Finally let’s abort the conflict" }, { "code": null, "e": 4833, "s": 4632, "text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master|MERGING)\n$ git merge --abort\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git status\nOn branch master\nnothing to commit, working tree clean" }, { "code": null, "e": 4933, "s": 4833, "text": "From the output it is clear that after aborting the merge (master|MERGING) has changed to (master)." }, { "code": null, "e": 5011, "s": 4933, "text": "Also, if we check git status it will indicate that the working tree is clean." } ]